Reputation: 113
passing react Props as mentioned in the image, I want to know is that any cleaner way to pass the multiple props in React.
Upvotes: 11
Views: 20730
Reputation: 362
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 ^-^
Upvotes: 0
Reputation: 2858
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} />
Upvotes: 12
Reputation: 1531
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}/>);
}
Upvotes: 2
Reputation: 1456
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.
Upvotes: 14
Reputation: 313
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 } />
);
}
}
Upvotes: 0
Reputation: 1242
you can pass in this way
const Foo = () =>
const multipleProps = {
prop1: 'value',
prop2: 'value',
Entity= 'entity value'
};
return <PanelEntity {...multipleProps} />;
}
Upvotes: 1