1

Let's say I have these 2 variables:

const test1 = (<div> ..... </div>); const test2 = (<div> ..... </div>); 

How do I combine them together (meaning - the code of test1 followed by the code of test2) into a "valid" variable called test3 and then render it like:

{this.array.length !== 0 ? test3 : null} 

?

2
  • That - "const test3 = test1 + test2;" ? Commented Nov 22, 2018 at 19:51
  • That didn't work.. Commented Nov 22, 2018 at 19:54

3 Answers 3

2

If you are using React 16.2+, use a Fragment:

{this.array.length !== 0 ? <React.Fragment>{test1}{test2}</React.Fragment> : null} 
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, thanks! (Will accept the answer in 8 minutes haha)
If your config supports it (I know the latest creat-react-app does) you can also do <><div>...</div><div>...</div></> and it is equivalent. Not that it makes a difference, just so you know the newer syntax if you see it.
0

You could use a React Fragment in combination of short-circuit syntax to get it short and sweet.

render() { const test3 = <React.Fragment>{test1}{test2}</React.Fragment>; return (this.array.length && test3); } 

Comments

0

You can make it even shorter by doing this if you're using latest versions of React. Don't have to type React.Fragment ;) The shorthand is <> and

const test3 = {this.array.length !== 0 ? <>{test1}{test2}</> : null } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.