Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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:

@cdomigan

This comment has been minimized.

Copy link

cdomigan commented Jul 20, 2017

Thanks for this!! :-)

@im-sunil

This comment has been minimized.

Copy link

im-sunil commented Mar 1, 2018

Passing a addition or remaining props came from react router or any other wrapping component

<Sidebar {...{ loading, title, list }} {...this.props} />
render() {
        const { players, loading } = this.state;
        const list = players.map(player => player.name);
        const title = "Players";
        return (
            <div className="container">
                <Sidebar {...{ loading, title, list }} {...this.props} />
            </div>
        );
Access remaining props ...props
function Sidebar({ title, list, loading, location, match, ...props }) {}
function Sidebar({ title, list, loading, location, match, ...props }) {
    console.log(props);
    return loading === true ? (
        <h1>LOADING</h1>
    ) : (
        <div className="header">
            <h3>{title}</h3>
    )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.