Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React/JSX - changing element type conditionally with minimal code duplication

Let's say I have something that is:

<div>
  {/* a lot of code */}
</div>

But if some condition is true, I want it to be:

<tr>
  {/* same code as before */}
</tr>

Is there any way to achieve this without a huge amount of code duplication from copy pasting?

like image 576
rococo Avatar asked Apr 21 '26 16:04

rococo


1 Answers

You could render the content in a variable using React.Fragment and choose the enclosing element depending on the condition.

Example

class App extends Component {
  state = { condition: true };

  render() {
    const { condition } = this.state;
    const content = (
      <Fragment>
        <h1>Hello world</h1>
        <h2>This is a lot of text...</h2>
      </Fragment>
    );

    return condition ? <div> {content} </div> : <tr> {content} </tr>;
  }
}
like image 183
Tholle Avatar answered Apr 23 '26 07:04

Tholle