React component syntax using HTML and CSS

Viewed 36

Attempting to create a simple like/unlike component with React. How can I render this component with <i class="fal fa-thumbs-down"> markup and classes to style the icons? My syntax here is off somewhere.

class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }

  render() {
    if (this.state.liked) {
      return (
        <i class="fal fa-thumbs-down"></i>
        { onClick: () => this.setState({ liked: false }) }
      );
    }

    return (
      <i class="fal fa-thumbs-up"></i>
      { onClick: () => this.setState({ liked: true }) }
    );
  }
}
1 Answers
return (
   <i class="fal fa-thumbs-down" onClick={ () => this.setState({ liked: !this.state.liked}) } />
)

I made three changes:

  1. onClick is a prop passed to i, just like class is.
  2. i is now self-closing
  3. instead of conditionally rendering, the logic in onClick is conditional (it flips the existing state when clicked)

Also, I'd strongly recommend switching over to functional components instead of class components. They're much cleaner (and more fun!) to work with.

Related