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?
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>;
})}
Arrow functions details
Sandbox
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>;
})}
</>
);
}
https://codesandbox.io/s/naughty-lamport-hps84d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With