Skip to content
Advertisement

Is there something wrong with using this pattern in React?

Everywhere where I saw React code written by other people and also me for most of my time since I started working in React a year ago I saw this kind of pattern for passing props.

    <Player 
     currentSong={currentSong}
     isPlaying={isPlaying}
     setIsPlaying={setIsPlaying}
     setCurrentSong={setCurrentSong}
    />

I’ve just realised recently that you can write the same thing like this:

<Player {...{ currentSong, isPlaying, setIsPlaying, setCurrentSong }} />

Is there something wrong with this or why is nobody using this implementation?

Advertisement

Answer

The second form you’re using is the object destructuring assignment. Basically, an elegant way would be:

   const setIsPlaying = true;
   const currentSong = 'my girl';

   const props = {
     currentSong,
     isPlaying: true,
     setIsPlaying,
   };

   return (<Player {...props} />);

Note I’m using the shorthand form to pass object properties setIsPlaying and currentSong (when the property has the same name of the variable in the same scope, don’t need to repeat).

Advertisement