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>
);
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, man, you really helped me a lot!!
Please don't. How about you pull the code a few lines up, out of the markup and only return <b>{a}</b>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.