best way to Pass Multiple Props In React js

Viewed 9399

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

5 Answers

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.

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} />

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}/>);
}


you can pass in this way

const Foo = () => 

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

 
  return <PanelEntity {...multipleProps} />;
}

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 } />
        );
      }

    }
Related