Spread operator with React component props

Can I use the spread operator to get all the props from a React component?, I know I can use destructuring to get the props in stateless functional component like this:

const Example = ({name, age, address}) => {
  return (
    <di>
      <p>{name}</p>
      <p>{age}</p>
      <p>{address}</p>
    </div>
  );
}

But what about if I have, let’s say, 10 props and I don’t wanna write all that down, is it possible to use the spread operator to pass all this props somehow?

const anotherExample = ({...props}) => {
return (
 <div> 
  <p>{name}</p>
   //...
 </div>
 );
}

You could but that’s the same as if you didn’t used the spread operator at all.

const anotherExample = ({...props}) => {

is the same as

const anotherExample = (props) => {

Yeah but in that case I have to write props.name, props.age, etc, I was wondering if there was a way to use destructing and the spread operator at the same time.

Hi !
Assuming that you want to just display each of those 10 props on a <p> tag, you can:

const anotherExample = (props) => {
return (
<div>
 {props.map(prop => 
 return (
  <p>{prop}</p>
);
)}
</div>
);
}

What you are doing here is to create an array of <p>{prop}</p> and set it as child of the <div>.
Sorry if I didn’t explain myself correctly !

You can’t do that.

What’s happening is that javascript allow you to choose the name you want to give to each object property, example:

const dosomething = ({x: hello, y: hello2, z: hello3}) => console.log(hello, hello2, hello3);

dosomething({x: 1, y: 2, z: 3});

When you don’t specify the name, like in ({x, y, z}), javascript will pick the same name for you: ({x: x, y: y, z: z}). This means that you must specify a name, be it manually or javascript doing it automatically for you.

Or maybe I could do this:

const Person = props => {
 const {...props } = props;
//...
}

Not possible either?

I get what you want, but at some point you have to tell JS what you need to access/use. What you’re trying to do is use properties without specifying the scope each time, like

const Person = props => {
  with(props) {
    return (
      <div> 
        <p>{name}</p>
       </div>
     );
  }
}

Note: don’t do the above. It used to be valid JS but causes all kinds of problems. And it will now just throw an error in strict mode.

You are trying to cut down typing, I get it, but being explicit is not a bad thing. Maybe this could also be a good point to rethink things and not pass so many props. If you think of each component as a function, and the props as arguments, then realistically you only want to give functions 3 arguments max, 4 if you really push it.

That’s literally the same as props

1 Like

Sorry, I think I misunderstood the question. So if you want to use name, age, address, etc without explicitly using destruction, you can’t. What I was saying is that you can just map blindly through your props, without knowing their content (wich I don’t recommend, btw.)