简体   繁体   中英

How to pass props to a React Router route

I'm trying to pass data from App to Home component but I don't know how in this situation.

In my App.js, I have firebase auth which holds email when logged in. I need to pass this to Home component but I don't know how in this situation.I know how to pass data by doing somthing like <Home user={user}> this but not right now.

In where should I put passing data in code like this?

<Route exact  path="/" component={Home} />

I attached my code in CodeSandbox

https://codesandbox.io/s/heuristic-mestorf-8qbx9?fontsize=14&hidenavigation=1&theme=dark

There are App.js Home.js and Login.js

What i did in App.js is rendering pages and only to see pages when logged in. Login.js is logging in with firebase auth and finally in Home component, I want to print out user's email.

Can somebody give me clues or help me please?? I will be very thankful:))

To pass props into a react-router route you must use a slightly different syntax

<Route
  exact
  path='/'
  render={(props) => <Home {...props} auth={authState} />}
/>

In this case, authState would be your firebase user data. It could be a boolean, or any other data you want to pass in as a prop.

Then in your Home component you will receive the prop and can use it however you want:

function Home({auth}) {
  return (
    <div>
      {auth ? <h1>Logged In</h1> : <h1>Logged Out</h1>}
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM