Skip to content

Instantly share code, notes, and snippets.

@joecritch
Last active September 29, 2021 15:16
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save joecritch/d2da97925e7f66802fc7 to your computer and use it in GitHub Desktop.
Save joecritch/d2da97925e7f66802fc7 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:

@cdomigan
Copy link

Thanks for this!! :-)

@sunil-bagde
Copy link

sunil-bagde 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