simplest
simplest

Reputation: 217

React - Pass state as props to another component

I am trying to do a conditional render based upon user login. I have a Login component that is being passed the Hook of the username and password through customerLogin and setCustomerLogin:

function App() {

    const [customerLogin, setCustomerLogin] = useState([
        { username: "", password: "" }
    ]);

    return(
        <div className="App">
            <Navbar />
            <Switch>
                <Route path='/signup' component={Signup}/>                    
                <Route 
                    path='/login' 
                    render={() =>
                        <Login
                            customerLogin={customerLogin}
                            setCustomerLogin={setCustomerLogin}
                        />}
                    />
            </Switch>
        </div>
    );
}

I would like to do a conditional render based upon whether customerLogin is an empty string versus if a user is logged in and the customerLogin will be set to their username. I have two components SignedInLinks and SignedOutLinks that I would like to use the rendering for in my Navbar component:

const Navbar = () => {
    return (
        <nav className="nav-wrapper">
            <div className="container">
                <Link to='/' className="brand-logo left">Cars4U</Link>
                    <SignedOutLinks />             
            </div>
        </nav>
    )
};

export default Navbar

Upvotes: 0

Views: 84

Answers (1)

justelouise
justelouise

Reputation: 770

Hmm. The simplest solution I could think of atm is to pass a boolean in your Navbar component.

<Navbar isLoggedIn={!!customerLogin} />

Then on your Navbar component,

export const Navbar = ({ isLoggedIn }) => {
  return (
    <div className="container">
      {isLoggedIn ? <SignedInLinks /> : <SignedOutLinks />}
    </div>
  )
}

Upvotes: 1

Related Questions