This would cause an error:
test = {
a: <div></div><div></div>
}
while this is all right:
test = {
a: <div></div>
}
so how to wrap two componet in the same key in react?
This would cause an error:
test = {
a: <div></div><div></div>
}
while this is all right:
test = {
a: <div></div>
}
so how to wrap two componet in the same key in react?
Use a React.Fragment:
You can do it like this:
test = {
a: (
<React.Fragment>
<div></div>
<div></div>
</React.Fragment>
)
}
Shorthand:
test = {
a: (
<>
<div></div>
<div></div>
</>
)
}
React fragments allow you to render sibling children together without rendering anything in the DOM.
The only prop that React.Fragment can take is a key prop which you would use if you plan on wrapping items in a mapped array. This prop can't be used in the shorthand version.
You can read more about Fragments here.
You can also accomplish it without a React.Fragment like this:
test = {
a: [
<div></div>,
<div></div>
]
}
But this method isn't as easy to read as the Fragment solution and you can't assign it a key prop if needed. Fragments are the best practice solution according to React's documentation.