React use parameters in jsx variable

I’m new to react and I’m trying to substitute a part of a jsx return I’m repeating in a react component, but there are slight differences in each repetition so I want to pass a simple boolean as a parameter to the variable so I can check those inside jsx. Here is what I’ve done so far:

function links(condition){
   console.log("Condition is: " + condition);
   return(<h1 className={`mr-10  ${ condition === true ? 'flex' : 'hidden' }`>Test</h1>);
}

const Navbar = () => { 
   return( <nav>
       <div> {links.call(false)} </div> 
       <div> {links.call(true)} </div>
   </nav> 
); }

This returns Condition is: then Condition is: Undefined in the console. How can I achieve this?

>Solution :

Down there you can see the "proper" way of using react:

function Links({ condition }) {
  return(
    <h1 className={`mr-10  ${ condition === true ? 'flex' : 'hidden' }`>
      Test
    </h1>
  );
}

const Navbar = () => { 
  return(
    <nav>
      <div>
        <Links condition={false} />
      </div> 
      <div>
        <Links condition={true} />
      </div> 
    </nav> 
  );
}

Note:

  • Better call you component with a caps: link => Link
  • To call a component use <Component {...props} />
  • The props (parameters) are passed as a object in the first parameter of the function

Leave a Reply