'Can't include code execution at jsx top level?
For the following code, it will gives exception when include the line {console.log('hello');}
import "./styles.css";
export default function App() {
const ages = [1, 2];
return (
<>
{ages.map((age) => (
{console.log('hello');} //include this code gives unexpected token
<h1>{age}</h1>
))}
</>
);
}
What is the syntax rule that gives this error?
Solution 1:[1]
You are mixing syntax of arrow functions. There is an implicit return pattern which helps use skip the return
statement, but with that you cannot write statements inside your code. You have to write an expression to be returned.
Use the curly braces, along with return:
{ages.map((age) => {
console.log("hello");
return <h1>{age}</h1>;
})}
Solution 2:[2]
You are returning directly from a map callback function. This should work:
import "./styles.css";
export default function App() {
const ages = [1, 2];
return (
<>
{ages.map((age) => {
console.log("hello");
return <h1>{age}</h1>;
})}
</>
);
}
Solution 3:[3]
The returning value of a function in JSX has to be a React Node, so in order to call the function like that, you need to make it into a fragment, so that you do return a React Node.
import "./styles.css";
export default function App() {
const ages = [1, 2];
return (
<>
{ages.map((age) => (
<>
{console.log('hello')}
<h1>{age}</h1>
</>
))}
</>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Freestyle09 |
Solution 3 | william007 |