0

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?

2
  • 1
    Did you try to actually look up what .call does? Also, if you want to split code in that way, in my opinion you should almost always make links a component. Commented Sep 23, 2022 at 7:13
  • 1
    Why not directly calling links like: links(false) and links(true) in the JSX? Commented Sep 23, 2022 at 7:15

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

I see, so I have to create a component for it, right? This indeed worked. Thanks, guess I wasn't thinking the "react" way.
Yep, if you want to reuse the logic, you create a separated component and pass him down props and logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.