1

Can you create an array of React elements eg something like:

const Component = () => {

  const myArray = [{<p>Hi</p>}]

  return(
    // Stuff
  )
}
2
  • 3
    yes without curlyBrackets Commented Apr 22, 2020 at 16:54
  • 1
    The React documentation explains this in the JSX in depth part. Commented Apr 22, 2020 at 17:15

1 Answer 1

1

Sure.

const myArray = [<p>1</p>, <p>2</p>, <p>3</p>];

// Fragment is included because everything in return needs to be wrapped in a single tag
return (
    <Fragment>{ myArray }</Fragment>
)

Also note that {'s are used to embed logic inside JSX

const foo1 = 'foo';
const foo2 = 'bar';
const myArray = [<p>{foo1}</p>, <p>{foo2}</p>];

return (
    <Fragment>
        {myArray.map((item, index) => (
            <span key={index}>
               <h1>{ 'Element #' + index }</h1>
               {item}
            </span>
        )}
    </Fragment>
)
Sign up to request clarification or add additional context in comments.

Comments

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.