skip to Main Content

code
I want the "elem" parameter of my component to be another component based on the boolean that is passed into my arrow function.

I have tried passing in "mobile" as a parameter into these arrow functions as it was a parameter of my <Homebar> hook. I’m not exactly sure how local variables work in JSX. Should I instead pass in "mobile=mobile" to set the value as a default param value? Should I just hard code an if else statement before my return? Or are arrow functions not possible within return statements?

2

Answers


  1. ReactJS at the base level uses JavaScript itself, so you can pass in parameters the same way as JavaScript callbacks and functions.

    Example:

    import React from 'react';
    
    const Component = () => {
      const handleClick = (name) => {
        // Handle the click event with the param
        console.log('Recording parameter:', name);
      };
    
      return (
        <div>
          <button onClick={() => handleClick('Bob')}> // pass parameter here
            Click me (Bob)
          </button>
        </div>
      );
    };
    export default Component;
    
    

    For passing parameter with default value, you can pass it as (param = true)

    Although, this is available in the documentation itself. You should refer that first in order to understand React and JS:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

    Login or Signup to reply.
  2. Your elem properties don’t appear to accept a function so it looks to me like you just want some conditional rendering

    return (
      <div className="navbar">
        <Leftbar elem={<Contact pos="left" />} />
        <Midbar elem={mobile && <Socials pod="mid" />} />
        <Rightbar
          elem={
            <>
              {mobile && <Socials pos="left" />}
              <Sections pos="right" />
            </>
          }
        />
      </div>
    );
    

    FYI Boolean props should not be set with ={true}. You can simplify your Homebar component using the following

    return <Homebar mobile={screenSize.width <= 600} />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search