Home > Net >  Render a component in jsx if a certain condition is met
Render a component in jsx if a certain condition is met

Time:03-11

Really new to react, I have this part of navigation in my Navbar.js using react-router-dom useLocation hook, I am able to get the active path I have to views and I want to render custom text when a user arrives at the view with JSX something like

if(path==="login" || path==="signin"){
  `<h1>welcome</h1> ${userName}!` 
}

How can I check if condition A or B is met then render the appropriate text using jsx

CodePudding user response:

You must explicitly tell what to return, in your example you do not return anything. So, You can do either :

if (path === "login" || path === "signin") {
  return (
    <>
      <h1>welcome</h1> {userName}
    </>
  );
} else {
  return null;
}

Or use operator && to conditionally render.

{
  (path === "login" || path === "signin") && (
    <>
      <h1>welcome</h1> {username}
    </>
  );
}

Read more about conditional rendering [here]

CodePudding user response:

You need to:

  • Return the value
  • Use JSX and not a string
  • Put everything in a container such as a React Fragment

Such:

if(path==="login" || path==="signin") {
    return <>
        <h1>Welcome</h1>
        {userName}!
    </>;
}

… but that logic should probably be handled by your routes rather than an if statement.

CodePudding user response:

You can use the ternary operator for conditional rendering in JSX like

{path==="login" || path==="signin" ? <> <h1>welcome</h1> {userName} </> : null}

Simple :-)

  • Related