Can you use props on React.Fragment?

7.1k Views Asked by At

I know that a React Fragment can be used to group child components like this:

render() {
  return (
    <React.Fragment>
      <Foo />
      <Bar />
      <Baz />
    </React.Fragment>
  );
}

But can you add props to it? Say you want to use the spread operator:

<React.Fragment {...otherProps}>
  ...
</React.Fragment>
2

There are 2 best solutions below

2
On BEST ANSWER

No, you can't. As per the React docs on Fragments:

key is the only attribute that can be passed to Fragment. In the future, we may add support for additional attributes, such as event handlers.

Therefore, if you want to add props to a wrapper component, switch to a good ol' div.

0
On

Not at all because if you think to pass props like this -

<React.Fragment {...otherProps}>
....
<React.Fragment />

it means

< {...otherProps}>
</>

Which isn't right and Reactjs doesn't recommend using it like this.