Multi-line JavaScript inside JSX?
Asked Answered
P

1

8

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>
);
Prothesis answered 9/2, 2021 at 11:53 Comment(1)
Look this post please: #59375922Revanchism
P
11

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.

Prothesis answered 9/2, 2021 at 11:53 Comment(2)
Thanks, man, you really helped me a lot!!Prothesis
Please don't. How about you pull the code a few lines up, out of the markup and only return <b>{a}</b>.Gambol

© 2022 - 2024 — McMap. All rights reserved.