Skip to content

Instantly share code, notes, and snippets.

@sunil-bagde
Forked from joecritch/MyComponent.js
Created March 11, 2018 11:42
Show Gist options
  • Save sunil-bagde/e4735b5acff8b556f62ac7f9c65f075a to your computer and use it in GitHub Desktop.
Save sunil-bagde/e4735b5acff8b556f62ac7f9c65f075a to your computer and use it in GitHub Desktop.
Passing specific props in React / JSX
class MyComponent extends React.Component {
render() {
const {location, todos, users} = this.props;
//
// ... do things with your variables!
//
return (
<MyChild {...{location, todos, user}} />
// equivalent to:
// <MyChild location={location} todos={todos} user={user} />
);
}
}

Passing specific props in React / JSX

A shortcut pattern to pass down props (of the same name and value) to child components. This removes the need for value repetition.

How it works

  1. ES6 can destruct assignments, so instead of const location = this.props.location, you can do const {location} = this.props.
  2. ES6 can also use a shorthand syntax in object literals, so {location: location} can just be {location}
  3. JSX has its own syntax called "Spread Attributes", which allows you to provide the tag with a plain object, and each key and value will be used in the attribute, respectively. So, <MyChild {...this.props} /> would be the equivalent to <MyChild location={this.props.location} todos={this.props.todos} user={this.props.user} />, etc.
  4. But if you don't want to pass all props: as per the example, you can create a new plain object, containing object-shorthand values.

Some further reading:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment