Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't include code execution at jsx top level?

Tags:

reactjs

jsx

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>
      ))}
    </>
  );
}

Edit thirsty-beaver-5t6c6j

What is the syntax rule that gives this error?

like image 329
william007 Avatar asked Feb 02 '26 20:02

william007


2 Answers

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

like image 81
Tushar Shahi Avatar answered Feb 04 '26 11:02

Tushar Shahi


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

like image 44
Freestyle09 Avatar answered Feb 04 '26 10:02

Freestyle09



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!