Advanced conditional component rendering in react

2019-07-22 11:26发布

I have a link in jsx. I may create new component for the link in the future but for now I wanted to use simple jsx. I also have a boolean prop that is telling me whether I should render the link or not. If not I want to render plain text in a span or div.

This is how I do it now:

{isPassed && <a href={'/uri'}>
  <span>Import</span>
</a>}
{!isPassed && <span>Import</span>}

This is how I can probably do it better:

{isPassed && <a href={'/uri'}>
  <span>Import</span>
</a> || <span>Import</span>}

What is the best practice handling conditional rendering like this? I want to make it more readable. First example duplicates the condition and in second example it is not apparent what is going to be rendered.

1条回答
我想做一个坏孩纸
2楼-- · 2019-07-22 11:49

You can as well try using ternary operator, we feel it's very readable for us.

{
  isPassed ? 
  <a href={'/uri'}><span>Import</span></a> : 
  <span>Import</span>
}

But in case of multiple conditions, then as well write a renderComponent method, like:

class SomeComponent extends Component {

    renderComponent(isPassed) {
      switch(isPassed) {
         case 0:
            return <span>One</span>
         case 1:
            return <span>Two</span>
         default:
            return <span>None</span>
      }
    }

    render() {
       return {
          <div>{ this.renderComponent(this.props.isPassed) }</div>
       }
    }
}

Further if you have complex components using props, then use the render component with more options:

renderComponent({ isPassed, text }) {
  switch(isPassed) {
     case 0:
        return <span>One {text}</span>
     case 1:
        return <span>Two {text}</span>
     default:
        return <span>None</span>
  }
}

// Say this.props has => isPassed and text as a key
<div>{ this.renderComponent(this.props) }</div>
查看更多
登录 后发表回答