reactjs

React's props with the same name as their value


Can we pass props to a component that has the same name and value implicitly?

Example: Let's say that I have a variable called x: const x = 1; and I have a component that has a prop called x. Can I pass it this variable as value implicitly? like that: <div x/>?


Solution

  • Booleans can be passed implicitly to the component as @Ajay also pointed out in comments, like

    <div x />
    

    which is basically equivalent to

    <div x={true} />
    

    If your variable is something other than a boolean, then you need to write it like

    <div x={x} />
    

    If you have several non-boolean variables, you can have two options:

    A. Form an object, then use spread operator in the component

    const cmpProps = {
       x,
       y,
       foo,
       bar
    }
    
    <Comp {...cmpProps} />
    

    B. Same as above, but directly in the component

    <Comp {...{x,y,foo,bar}} />
    
    // can be used alongside other props
    <Comp key={getCellId()} color="yellow" size={user.size} {...{x,y,foo,bar}} />