10

passing react Props as mentioned in the image, I want to know is that any cleaner way to pass the multiple props in React.

enter image description here

Hao Wu
  • 17,573
  • 6
  • 28
  • 60
Anuj Srivastava
  • 103
  • 1
  • 1
  • 7

6 Answers6

13

According to react eslint rules it is not recommended to use props spreading for readability and maintenance reasons, Read more about the rule here

So what you can do is either leaving it as it is or group similar props into one object and pass it for example:

const entity = { getEntity, entityKeyAccess, setEntityKeyAccess };
const display = { display, setDisplay };
const child = { childKeyAccess, setChildKeyAccess };
// And so on you get the idea I guess.

<PanelEntity panelData={panelData} entity={entity} display={display} child={child} />;

This way now anyone using this component will be able to understand your props easily (of course don't forget to document your props) and you decluttered the component without using props spreading.

Mohamed Wagih
  • 1,246
  • 6
  • 17
12

If the name and key values are the same you can use spread syntax

Example

<PanelEntity { ...{ panelData, setGetEntity, getEntity} } />

Same as doing this

<PanelEntity 
      panelData={panelData} 
      setGetEntity={setGetEntity} 
      getEntity={getEntity} />
Randall
  • 2,414
  • 3
  • 35
  • 63
2

Yes, you can put them all together in an object and pass them as one using spread like this:

const Panel = (props) => {
  const nextProps = {
    key1: val1,
    key2: val2,
    key3: val3
  };

  return(<PanelEntity {...nextProps}/>);
}


Ran Marciano
  • 1,431
  • 5
  • 13
  • 30
1

you can pass in this way

const Foo = () => 

  const multipleProps = { 
    prop1: 'value', 
    prop2: 'value',
    Entity= 'entity value'
  };

 
  return <PanelEntity {...multipleProps} />;
}
Muhammad Muzamil
  • 1,013
  • 2
  • 18
  • 25
0

You can make a getter to get you all the props needed then you can spread them into the component

    class Panels extends React.Component {
      get panelProps() {
        const {propA, propB} = this.props;
        
        return {
          propA,
          propB,
          functionA: () => this.customFunction(),
          functionB: (value) => this.customFunction2(value),
        }
      }
      
      render() {
        return(
          <PanelEntity { ...this.panelProps } />
        );
      }

    }
buzatto
  • 9,704
  • 5
  • 24
  • 33
0

The example Randall gave is 100% an awesome solution

But to give some advice when your components start looking like OP's props It would be better to use a global state manager, like RTK, to cleanup a couple of the props needed. You can define dispatchers and reducers that can be used anywhere as well

Just a little 2c from my side ^-^

Ruben Verster
  • 301
  • 1
  • 8