0

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 }) }
    );
  }
}
0

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Any idea why I'd get Unexpected token '<' on the i?
@noclist Are you sure you're using the file extension .jsx, not .js? JSX is a superset of JavaScript, and you need to be using JSX to use the embedded html tags.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.