Reputation: 154
The error is unexpected token, expected "," in the render return function. I am using babel and linking this file in an html file. I removed the comment class and component for viewing purposes. Also I removed the comment form component.
Here is main.js:
class App extends React.Component {
constructor(props) {
super(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = { comments : [] }
}
handleSubmit(event) {
// ...
}
render() {
const comments = this.state.comments.map((comment) => {
<Comment author={comment.author} message={comment.message} />
});
const formcomment = <CommentForm handleSubmit = {this.handleSubmit} />;
return (
{comments}
{formcomment} // ERROR HERE
)
}
}
ReactDOM.render(<App />, document.getElementById("root"))
Upvotes: 2
Views: 5355
Reputation: 762
The other answers are also correct, but I encountered an additional case where this error occurs as well.
interface Props {
className?: string
background: BackgroundStyle
children: React.ReactNode
style?: any // Pass-through the style property to the root element
}
export default (props:Props) => {
return (
<div
className={cx('BackgroundStyle', getBackgroundStyleClassName(props.background), props.className)}
style={...props.style}
>
{getBackgroundStyleInner(props.background)}
{props.children}
</div>
)
}
The above component results in the same error when a style
prop is passed in: unexpected token, expected "," in the render return function
. The issue in this case is that the props.style
pass-through is incorrect. The line should be: style={props.style}
with no destructuring.
Upvotes: 0
Reputation: 113
Have you tried wrapping your return value in a div
or fragment(<></>
)?
Upvotes: 0
Reputation: 7454
The problem occurs, because JSX requires you to only have one root element. In your case you're having two root elements.
If you want to return multiple elements, you need to wrap them into some sort of container, most of the time a simple div
will be sufficient:
return (
<div>
{comments}
{formcomment}
</div>
);
If the div
is disrupting your styling, you might want to use a Fragment
instead.
Read more about JSX in general here and here.
EDIT:
As Emile Bergeron pointed out, you can also return an array as of React 16.2:
render() {
return [comments, formcomment];
}
Upvotes: 6
Reputation: 91
The problem is that you are trying to render multiple elements without a parent container.
You should be able to fix this by adding <Fragment> ... </Fragment>
(or, more simply, <> ... </>
) around the contents of your return statement. This will give the JSX transpiler a single element to render with.
The usual fix for this is using a "wrapper div", but using a Fragment like this is the new way of wrapping elements without adding nodes to the DOM.
Checkout out this page to learn more about this problem and React fragments.
Upvotes: 1