Add comments inside JSX in React
Last updated: October 31, 2023.
Inside the return statement of a React component, it is not possible to add comments like it is in plain JavaScript (or elsewhere in the non-JSX returning part of the function component).
It is also not possible to write a comment like in HTML. React treats this as if you are trying to insert a HTML element or custom component and will throw an error:
<!-- Adding this code inside JSX will throw an error -->
You must instead use {}
to escape JSX and use plain JavaScript. This allows you to add a comment just like you would in regular JavaScript.
Even for a single-line comment, it is important to use multi-line comment syntax (/* ... */
) because this prevents the closing curly brace of the escape to plain JavaScript (}
) being ignored and breaking your code.
For example:
import { useState } from 'react';
function App() {
const [count, setCount] = useState(0);
return (
<div className='card'>
{ /* Your comment here */ }
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
</div>
)
}
export default App;
You can also use single-line comment syntax (//) but, if so, you need to make sure that the closing curly brace is on the line after the comment (otherwise it would be ignored):
{ // ❌ Breaks code because } is ignored }
{
// ✅ The right way
}
The exception is when you write a comment inside the angle brackets <>
) of a JSX element, where attributes are added. Under the hood, React escapes from JSX to plain JavaScript in this space, so you can write comments there is the same way as plain JavaScript without escaping manually:
<div
/* This works */
// This also works
className='card'
>