Multi-line JavaScript inside JSX?

Viewed 1308

Is it possible to write a multiline js code in JSX?

return (
      <b>{
      const a = props.users.find((user) => user.id === post.userId)
      console.log(a) // I want to console.log
      return a
      }</b>
);
1 Answers

If you want to do multi-line JavaScript code, you can wrap your JS code with an IIFE, for example:

  <>
    {(() => {
      const a = [1, 2, 3].find((el) => el === 2)
      // as much code as you want ...
      // ...
      // ...
      console.log(a)
    })()}
  </>

Just in case you don't know, <> & </> are called React fragments, you can use any valid JSX element you want, for example, you can use instead <div>, <b>, <p> or anything like that.

Related