ThomasReggi
ThomasReggi

Reputation: 59355

Conditionally add element based on prop

How are you supposed to conditionally add a element like I have below? I only want <div className='next-field__connected-wrapper'> to be exist within if the withFilter prop is true.

  render: function () {
    if (this.props.withFilter) {
      return (
        <div>
          <div className='next-card next-card__section next-card__section--no-bottom-spacing'>
            <div className='next-field__connected-wrapper'>
              { this.props.children }
            </div>
          </div>
        </div>
      )
    } else {
      return (
        <div>
          <div className='next-card next-card__section next-card__section--no-bottom-spacing'>
            { this.props.children }
          </div>
        </div>
      )
    }
  }

Upvotes: 0

Views: 52

Answers (1)

Jordan Running
Jordan Running

Reputation: 106027

Keep in mind that JSX elements are just JavaScript objects and you can assign them to variables and pass them around like any other:

render: function () {
  let inner = this.props.children;

  if (this.props.withFilter) {
    inner = (
      <div className='next-field__connected-wrapper'>
        {inner}
      </div>
    );
  }

  return (
    <div>
      <div className='next-card next-card__section next-card__section--no-bottom-spacing'>
        {inner}
      </div>
    </div>
  );
}

Upvotes: 2

Related Questions