Joseph Chambers
Joseph Chambers

Reputation: 4068

How to refactor && () when returning component

I've recently came into a project where the developers are using this unfamiliar syntax where they did something like this:

    {this.props.something === 'Foo' && (
      <React.Fragment>
       Here
      </React.Fragment>
    )}

How else could I rewrite this?

Upvotes: 0

Views: 93

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149020

@Jonas Wilms' answer covers what the syntax means very nicely. However, since you asked specifically about how this could be rewritten, here are some alternative solutions that you might find preferable in certain circumstances.

Supposing you start off with a component like this:

class MyComp extends Component {
  render() {
    return (
      <div>
        {this.props.something === 'Foo' && (
          <React.Fragment>
            Here
          </React.Fragment>
        )}
      </div>
    );
  }
}

You can convert it to this:

class MyComp extends Component {
  render() {
    let content;
    if (this.props.something === 'Foo') {
      content = (
        <React.Fragment>
          Here
        </React.Fragment>
      );
    }

    return (
      <div>{content}</div>
    );
  }
}

or this:

class MyComp extends Component {
  conditionalContent(something) {
    if (something === 'Foo') {
      return (
        <React.Fragment>
          Here
        </React.Fragment>
      );
    }
  }

  render() {
    return (
      <div>
        {this.conditionalContent(this.props.something)}
      </div>
    );
  }
}

or even this:

const ConditionalComponent = ({ show }) => {
  if (show) {
    return (
      <React.Fragment>
        Here
      </React.Fragment>
    );
  }
}

class MyComp extends Component {
  render() {
    let content;
    if (this.props.something === 'Foo') {
      content = (
        <React.Fragment>
          Here
        </React.Fragment>
      );
    }

    return (
      <div>
        <ConditionalComponent show={this.props.something === 'Foo'}/>
      </div>
    );
  }
}

Of course, there are many other variations you could come up with. This hopefully is enough to get you to think more about how to structure your component for optimum readability.

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138267

Due to short circuiting in JavaScript, the whole code basically either evaluates to false if the condition

 this.props.something === 'Foo' 

is not fullfilled, otherwise (if the condition gets fullfilled) it'll evaluate to the following React Component instance. As React will filter out falsy values (including the false) during rendering, this will render the Fragment if something is foo, otherwise it doesn't render anything.

Upvotes: 4

Related Questions