React-router: Did you guys really think it's was a good idea to nest all those ternary operators?

Created on 24 Aug 2017  路  4Comments  路  Source: ReactTraining/react-router

Most helpful comment

Rewritten without the ternaries:

  render() {
    const { match } = this.state
    const { children, component, render } = this.props
    const { history, route, staticContext } = this.context.router
    const location = this.props.location || route.location
    const props = { match, location, history, staticContext }

    if (component)
      return match ? React.createElement(component, props) : null;

    if (render)
      return match ? render(props) : null;

    if (typeof children === 'function')
      return children(props);

    if (children && !isEmptyChildren(children))
      return React.Children.only(children);

    return null;
  }

This way is shorter, more readable, and the clarity makes the comments redundant.

All 4 comments

Yes.

Edit: Sorry, that was asinine and overly snarky. I apologize for that terse reply.

The current form is @ryanflorence's preference. If you have an idea for an alternate structure, a PR is best. Just critiquing without any guidance doesn't make for a productive conversation. This often happens with the docs too, where someone has an issue with something about it and doesn't offer up an alternative. It's easy to say something sucks, but hard to offer a concrete example of another way. Luckily, @jimbolla put something together below, so let's take that idea and run with it!

Rewritten without the ternaries:

  render() {
    const { match } = this.state
    const { children, component, render } = this.props
    const { history, route, staticContext } = this.context.router
    const location = this.props.location || route.location
    const props = { match, location, history, staticContext }

    if (component)
      return match ? React.createElement(component, props) : null;

    if (render)
      return match ? render(props) : null;

    if (typeof children === 'function')
      return children(props);

    if (children && !isEmptyChildren(children))
      return React.Children.only(children);

    return null;
  }

This way is shorter, more readable, and the clarity makes the comments redundant.

Oh, I like that. Thanks, Jim! We've also got some other places with nested ternaries, I believe. I'll see about wrapping that up into a PR.

@timdorr hehe, no offense taken really. I just lost it when I had a lot of stuff to do and had to parse that to understand what was going on. @jimbolla change is an improvement. Compact can be nice but there's a breaking point, and people have different tolerances and/or styles. I get that. No worries. Just had to vent.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ryansobol picture ryansobol  路  3Comments

maier-stefan picture maier-stefan  路  3Comments

Waquo picture Waquo  路  3Comments

yormi picture yormi  路  3Comments

ackvf picture ackvf  路  3Comments