All we need is an easy explanation of the problem, so here it is.
The project in question is using React-16.2.0 which has the capability to use Fragments and the Fragment shorthand.
https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html
While the full-length syntax works fine…
import React, { Fragment, Component } from 'react';
class TestingFragment extends Component {
render() {
return (
<Fragment>
<span>This is a fragment of text </span>
<div>Another part of the fragment</div>
</Fragment>
)
}
};
export default TestingFragment
The shorthand fails to compile and I am at a loss as to why this is. Fore example…
import React, { Component } from 'react';
class TestingFragment extends Component {
render() {
return (
<>
<span>This is a fragment of text </span>
<div>Another part of the fragment</div>
</>
)
}
};
export default TestingFragment
Which fails to compile as follows…
Failed to compile
./src/testingFragments.js
Syntax error: Unexpected token (6:4)
4 | render() {
5 | return (
> 6 | <>
| ^
7 | <span>This is a fragment of text </span>
8 | <div>Another part of the fragment</div>
9 | </>
This error occurred during the build time and cannot be dismissed.
Is there something here I am missing about the Fragment shorthand syntax?
How to solve :
I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.
Method 1
I think this is a reason:
https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html#support-for-fragment-syntax
create-react-apps currently use Babel 6.26.0
for full support React.Fragment is needed Babel v7.0.0-beta.31 and above
======================= EDIT
It’s working now with create-react-app v2
https://reactjs.org/blog/2018/10/01/create-react-app-v2.html
Method 2
You can use the poor man’s fragment shorthand as a quick fix: [
,
]
render(){
return [
<div key="f">foo</div>,
<div key="b">bar</div>
]
}
as array of nodes is a valid jsx element. You need to add a key
prop to each of them manually though as Anarno pointed out.
Method 3
Fragment syntax is only supported by Babel v7.0.0-beta.31 & above.
Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0