Say I have a parent component and one child component.
The props
has ten keys, but child needs only three.
What is the better way to pass props to child component?
class Parent extends Component {
render() {
{ /*pass all the ten keys into child*/ }
<Child {...this.props} />
}
}
or
class Parent extends Component {
render() {
{ /*pass only the needed keys into child*/ }
<Child key1={key1} key2={key2} key3={key3}/>
}
}
Passing Props from Parent to Child in React If you happen to know all of the props, then you could pass them all by just listing them out individually as the new props for the child component.
First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.
Passing all the props generally isn't a good idea. More props means more things that will cause the child component to unnecessarily re-render. However, it can be convenient to use the spread operator on a subset of those props. For example, a parent component may receive a lot of props, but doesn't use most of them and instead hands all but one or two off to a child component. Consider this example using something like redux-form:
export function Form({ handleSubmit, ...rest }) {
return (
<form onSubmit={handleSubmit}>
<Field name="name" component={FormInput} />
<SaveButton {...rest} />
</form>
);
}
The outer form component only cares about the submit function. Other props indicating whether the form is dirty, valid, etc, would be used by the <SaveButton />
to determine whether or not to disable the button.
This is convenient because we avoid having to declare props for a component that doesn't use them. We just pass them through. But as stated previously, use this pattern with caution, making sure you're aware of which props you're actually handing down, because it could cause performance issues or even side effects.
In fact, I'd go so far as to say that if you find yourself passing props down through a hierarchy frequently, you probably have a design problem and should be leveraging your redux store more efficiently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With