最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Conditional rendering in React; is this THE way? - Stack Overflow

programmeradmin3浏览0评论

I was just looking into React to pare it to my go-to framework Vue and I was trying to conditionally render a button. When I looked into how to do this I made this:

import React from 'react'

export default class LikeButton extends React.Component {
  constructor(props) {
    super(props)
    this.state = { likes: 0 }
  }

  render() {
    return (
      <div>
        <button onClick={this.increment}>
          Likes: {this.state.likes}
        </button>
        {
          this.state.likes > 0 ? (
            <button onClick={this.reset}>
              Unlike
            </button>
          ) : ('')
        }
      </div>
    )
  }

  increment = () => this.setState({ likes: this.state.likes + 1 })
  reset     = () => this.setState({ likes: 0 })
}

Is this REALLY the way to go? I feel like the syntax is very very ugly, atleast pared to Vue with it's v-if and v-show directives. Or is there a better way to achieve this in a clean way?

I was just looking into React to pare it to my go-to framework Vue and I was trying to conditionally render a button. When I looked into how to do this I made this:

import React from 'react'

export default class LikeButton extends React.Component {
  constructor(props) {
    super(props)
    this.state = { likes: 0 }
  }

  render() {
    return (
      <div>
        <button onClick={this.increment}>
          Likes: {this.state.likes}
        </button>
        {
          this.state.likes > 0 ? (
            <button onClick={this.reset}>
              Unlike
            </button>
          ) : ('')
        }
      </div>
    )
  }

  increment = () => this.setState({ likes: this.state.likes + 1 })
  reset     = () => this.setState({ likes: 0 })
}

Is this REALLY the way to go? I feel like the syntax is very very ugly, atleast pared to Vue with it's v-if and v-show directives. Or is there a better way to achieve this in a clean way?

Share Improve this question asked Nov 7, 2020 at 15:30 Niels BosmanNiels Bosman 9762 gold badges10 silver badges19 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 4

You can make the conditional rendering look a bit nicer by using && instead of the conditional operator:

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = { likes: 0 }
  }

  render() {
    return (
      <div>
        <button onClick={this.increment}>
          Likes: {this.state.likes}
        </button>
        {
          this.state.likes > 0 && (
            <button onClick={this.reset}>
              Unlike
            </button>
          )
        }
      </div>
    )
  }

  increment = () => this.setState({ likes: this.state.likes + 1 })
  reset     = () => this.setState({ likes: 0 })
}
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg./react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg./react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>

But an even better improvement IMO would be to use a functional ponent instead of messing with objects and prototype methods, it makes things a lot more concise:

const App = () => {
  const [likes, setLikes] = React.useState(0);
  return (
    <div>
      <button onClick={() => setLikes(likes + 1)}>
        Likes: {likes}
      </button>
      {
        likes > 0 && (
          <button onClick={() => setLikes(0)}>
            Unlike
          </button>
        )
      }
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg./react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg./react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>

If you have multiple areas with conditional logic, you can separate them out into separate ponents for readability:

const Unlike = ({ setLikes }) => (
  <button onClick={() => setLikes(0)}>
    Unlike
  </button>
);
const App = () => {
  const [likes, setLikes] = React.useState(0);
  return (
    <div>
      <button onClick={() => setLikes(likes + 1)}>
        Likes: {likes}
      </button>
      {
        likes > 0 && <Unlike setLikes={setLikes} />
      }
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg./react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg./react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>

For the most part yes. You can simplify the statement though, you can use logical && instead of the ternary operator ? if you wish to display the data only in condition and nothing in the other.

this.state.likes > 0 && (
   <button onClick={this.reset}>Unlike</button
)

Additionally I'd like to point out, while this is not directly a use-case for your example, you can forgo the optional render if blocks in the return by having multiple returns in render (eg. a real life example with loader)

render() {
  if (isFetchingData) {
     return <Loader />
  }

  return (
    <div>
      My ponent
    </div>
  )
}

But on a more personal note, I genuinely think you'll get used to the syntax. It's probably not as elegant on the first sight as vue, but it actually allows you to have more powerful logic inside the render method by clearly separating javascript from html.

For inline rendering you could do

{
  this.state.likes > 0 &&
  <button onClick={this.reset}>Unlike</button>;
}

or in your render function

let like = null;
if (this.state.likes > 0) {
    like = <LogoutButton onClick={this.handleLogoutClick} />;
} 

and then

<div>
  <button onClick={this.increment}>Likes: {this.state.likes}</button>
  {like}
</div>;

I personally prefer the second but it's up to you

more info here

The main beauty of react es when you start splitting your code into functions. So May be you can have a function called renderButton() and let it decide what to render.

renderButton = () => {
// all code logic here
 if(this.state.likes > 0){
   return (<button>Unlike</button>)
 }
  return (<></>)
}

then in render function you can just {this.renderButton}

also you can do condition && statement.

You can also read about pure ponents which only contains the UI and the logic is written in some other ponent. There are many ways to write beautiful and clean code in react.

The main problem is that react is easy to start with and therefore many new developers will start writing code that is difficul to read.

Also i forgot to mention hooks which makes writing react much cleaner and easier.

发布评论

评论列表(0)

  1. 暂无评论