Best way for destructuring props in React
How to Object destructuring in child component in REACT
Destructuring state/props in React - javascript
What is the point of always destructuring?
I was wondering if there is any difference between this two ways of destructuring props
const Component = ({prop1, prop2}) => { ... }const Component = (props) => {
const {prop1, prop2} = props;
...
}Is there any advantage or disadvantage on choosing one over the other? Could you run into rerendering issues in the second option because it creates a new variable on each render (if the prop is an object or an array)?
React will pass an object down to MyComponent that looks like this:
{ person: { name: "ALEN", age: 40 } }
Because you specify the properties name and age in your object destructuring and not person, it will be undefined.
You can declare the function like this:
const MyComponent = ({ person: { name,age } }) => {
return (
<div>
<h1> HI THERE I M {name}</h1>
</div>
);
}
You are getting person in props, not name and age, you can follow like this.
First destruct person from props then destruct name and age from person.
const MyComponent = ({ person }) => {
const { name, age } = person;
return (
<div>
<h1> HI THERE I M {name}</h1>
</div>
);
};
What eslint is telling you with the react/destructuring-assignments error is that assignments like:
const data = this.state.data;
can be rewritten into:
const { data } = this.state;
This also works for function arguments, so:
onChange = e => { ... }
can be written as
onChange = ({target: {value, name}}) => { ... }
The next error for react/no-access-state-in-setstate tells you that you are writing:
this.setState({
data: { ...this.state.data, [e.target.name]: e.target.value }
});
when you should be writing:
this.setState(prevState => ({
data: { ...prevState.data, [e.target.name]: e.target.value }
}));
or, if you combine it with the react/destructuring-assignments rule:
onChange = ({target: {name, value}}) =>
this.setState(prevState => ({
data: { ...prevState.data, [name]: value }
}));
You can read more about those two rules here:
react/destructuring-assignment
react/no-access-state-in-setstate
Destructuring is basically syntatic sugar Some Eslint configurations prefer it (which I'm guessing is your case).
It's basically declaring the values and making them equal to the bit of syntax you don't want to repeat, for Ex, given react props:
this.props.house, this.props.dog, this.props.car
destructured --->
const { house, dog, car } = this.props;
So now you can just use house, or dog or whatever you want. It's commonly used with states and props in react, here is more doc about it, hope it helps. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment