'How to pass multiples states at the same time to a child component from parent component in Reactjs? [closed]

I am new to Reactjs and thanks in advance. I have the states below:

const [firstName, setFirstName]=useState();
const [lastName, setLastName]=useState();

I want to pass both firstName and lastName to the child component from the parent component at the same time. How could I do that?



Solution 1:[1]

See the react docs for components and props

Components accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

When React sees an element representing a user-defined component, it passes JSX attributes (and children) to this component as a single object. We call this object “props”.

import { useState } from "react";

function ParentComponent() {
  const [firstName, setFirstName] = useState("John");
  const [lastName, setLastName] = useState("Smith");
  return (
    <div className="ParentComponent">
      <ChildComponent firstName={firstName} lastName={lastName} />
    </div>
  );
}

function ChildComponent(props) {
  return (
    <div className="ChildComponent">
      <p>firstName: {props.firstName}</p>
      <p>lastName: {props.lastName}</p>
    </div>
  );
}

Demo

Solution 2:[2]

If you mean that you want to pass firstName and lastName to child element, relevant to component where you declared the states then you just need to pass them as props

<Child firstName={firstName} lastName={lastName} />

and inside child you would access them like props

function Child(props){

console.log(props) //this will show props of child component, there are stored your statements

return(...something here...)
}

Solution 3:[3]

You could do it this way, assuming that your components are called Parent and Child:

export default function Parent(){
   const [firstName, setFirstName]=useState();
   const [lastName, setLastName]=useState();
   
   return (
     <Child firstName={firstName} lastName={lastName} />
   )

}

And you get them inside Child like so:

export default function Child(props){

  console.log(props.firstName, props.lastName)
  return <div></div>
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3