What does the ...
do in this React (using JSX) code and what is it called?
These three dots are called spread operator. Spread operator helps us to create a copy state or props in react.
Using spread operator in react state
const [myState, setMyState] = useState({
variable1: 'test',
variable2: '',
variable3: ''
});
setMyState({...myState, variable2: 'new value here'});
in the above code spread operator will maintain a copy of current state and we will also add new value at same time, if we don't do this then state will have only value of variable2 spread operator helps us to write optimize code
Those are called spreads. Just as the name implies. It means it's putting whatever the value of it in those array or objects.
Such as :
let a = [1, 2, 3];
let b = [...a, 4, 5, 6];
console.log(b);
> [1, 2, 3, 4, 5, 6]
The three dots in JavaScript are spread / rest operator.
Spread operator
The spread syntax allows an expression to be expanded in places where multiple arguments are expected.
myFunction(...iterableObj);
[...iterableObj, 4, 5, 6]
[...Array(10)]
Rest parameters
The rest parameter syntax is used for functions with variable number of arguments.
function(a, b, ...theArgs) {
// ...
}
The spread / rest operator for arrays was introduced in ES6. There's a State 2 proposal for object spread / rest properties.
TypeScript also supports the spread syntax and can transpile that into older versions of ECMAScript with minor issues.
That's property spread notation. It was added in ES2018 (spread for arrays/iterables was earlier, ES2015), but it's been supported in React projects for a long time via transpilation (as "JSX spread attributes" even though you could do it elsewhere, too, not just attributes).
{...this.props}
spreads out the "own" enumerable properties in props
as discrete properties on the Modal
element you're creating. For instance, if this.props
contained a: 1
and b: 2
, then
<Modal {...this.props} title='Modal heading' animation={false}>
would be the same as
<Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}>
But it's dynamic, so whatever "own" properties are in props
are included.
Since children
is an "own" property in props
, spread will include it. So if the component where this appears had child elements, they'll be passed on to Modal
. Putting child elements between the opening tag and closing tags is just syntactic sugar — the good kind — for putting a children
property in the opening tag. Example:
class Example extends React.Component {
render() {
const { className, children } = this.props;
return (
<div className={className}>
{children}
</div>
);
}
}
ReactDOM.render(
[
<Example className="first">
<span>Child in first</span>
</Example>,
<Example className="second" children={<span>Child in second</span>} />
],
document.getElementById("root")
);
.first {
color: green;
}
.second {
color: blue;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Spread notation is handy not only for that use case, but for creating a new object with most (or all) of the properties of an existing object — which comes up a lot when you're updating state, since you can't modify state directly:
this.setState(prevState => {
return {foo: {...prevState.foo, a: "updated"}};
});
That replaces this.state.foo
with a new object with all the same properties as foo
except the a
property, which becomes "updated"
:
const obj = {
foo: {
a: 1,
b: 2,
c: 3
}
};
console.log("original", obj.foo);
// Creates a NEW object and assigns it to `obj.foo`
obj.foo = {...obj.foo, a: "updated"};
console.log("updated", obj.foo);
.as-console-wrapper {
max-height: 100% !important;
}
It's just defining props in a different way in JSX for you!
It's using ...
array and object operator in ES6 (object one not fully supported yet), so basically if you already define your props, you can pass it to your element this way.
So in your case, the code should be something like this:
function yourA() {
const props = {name='Alireza', age='35'};
<Modal {...props} title='Modal heading' animation={false} />
}
so the props you defined, now separated and can be reused if necessary.
It's equal to:
function yourA() {
<Modal name='Alireza' age='35' title='Modal heading' animation={false} />
}
These are the quotes from React team about spread operator in JSX:
JSX Spread Attributes If you know all the properties that you want to place on a component ahead of time, it is easy to use JSX:
var component = <Component foo={x} bar={y} />;
Mutating Props is Bad
If you don't know which properties you want to set, you might be tempted to add them onto the object later:
var component = <Component />;
component.props.foo = x; // bad
component.props.bar = y; // also bad
This is an anti-pattern because it means that we can't help you check the right propTypes until way later. This means that your propTypes errors end up with a cryptic stack trace.
The props should be considered immutable. Mutating the props object somewhere else could cause unexpected consequences so ideally it would be a frozen object at this point.
Spread Attributes
Now you can use a new feature of JSX called spread attributes:
var props = {};
props.foo = x;
props.bar = y;
var component = <Component {...props} />;
The properties of the object that you pass in are copied onto the component's props.
You can use this multiple times or combine it with other attributes. The specification order is important. Later attributes override previous ones.
var props = { foo: 'default' };
var component = <Component {...props} foo={'override'} />;
console.log(component.props.foo); // 'override'
What's with the weird ... notation?
The ... operator (or spread operator) is already supported for arrays in ES6. There is also an ECMAScript proposal for Object Rest and Spread Properties. We're taking advantage of these supported and developing standards in order to provide a cleaner syntax in JSX.
The ...
(spread operator) is used in react to:
provide a neat way to pass props from parent to child components. e.g given these props in a parent component,
this.props = {
username: "danM",
email: "dan@mail.com"
}
they could be passed in the following manner to the child,
<ChildComponent {...this.props} />
which is similar to this
<ChildComponent username={this.props.username} email={this.props.email} />
but way cleaner.