Panagiss
Panagiss

Reputation: 3720

Pass data from Child to other Child with React Hooks

So this is the Parent Function which passes the data to its children:

function Parent() {

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");


  return (
    <div className="Parent">
      <BrowserRouter>

          <Route exact path="/child1" render={ () =>
             <Child1 setUsername={setUsername} setPassword={setPassword} password={password} username={username}/> 
             />

          <Route exact path="/child2" 
            render={() =>
             <Child2 username={username} password={password}/>
            }/>

        </BrowserRouter>
    </div>
  );
}

export default Parent;

What i try to achieve is, that Child1 will get the data from an endpoint and it will store the data with setPassword() and setUsername() and the first Child redirects the page to the second Child (aka Child2).

The problem is that Child2 won't get the data somehow and actually when i console.log("Username: "+username) or console.log("Password: "+password) i get [object Object].

Child1:

export default function Child1({setPassword,setUsername,username,password}) {

  const history = useHistory();

  const handleClick = () => {
   setUsername("myUsername");
   setPassword("myPassword");
   history.push("/child2") 
  }

  return (
    <div>
      Child 1 Page
    <button onClick={handleClick}> A button</button>
    </div>
  );
}

Child2:

const Child2 = (username,password) => {


    useEffect(() => {
         console.log("Username: "+username);
         console.log("Password: "+password);
    }, [])

    return (
        <div >
           Child 2 Page
        </div>
    )
}

export default Child2

Upvotes: 0

Views: 44

Answers (2)

Taghi Khavari
Taghi Khavari

Reputation: 6582

that's because you're trying to console.log an object as string , when you use 'a string' + someKindOfObject the javascript will try to find a toString() function in someKindOfObject and if it couldn't find it it just outputs as [object object].

So you need to change your code to something like this:

// use proper destructuring
const Child2 = ({username,password}) => {


    useEffect(() => {
         console.log("Username: ", username);
         console.log("Password: ", password);
        // remove useEffect dependency so you can see the data in every render - maybe the first time is just undefined
    })

    return (
        <div >
           Child 2 Page
        </div>
    )
}

Upvotes: 1

Nisharg Shah
Nisharg Shah

Reputation: 19562

You forget { }

Explanation

You will get props from the parent in the props object in

const Child2 = (props) => {...}

and you can access it any parent props with props.* and you can also use the destructuring method

const Child2 = ({username,password}) => {...}

Upvotes: 1

Related Questions