A
A
ArturPetrov2019-09-14 21:24:43
React
ArturPetrov, 2019-09-14 21:24:43

What would this code look like with class components instead of functional ones and without hooks?

Hello! I studied building React applications only with class components, and did not use functional components, and I don’t understand hooks very well, I just know that they somehow replace state.
Therefore, I don’t know how to remake this code into the one I need ... I ask you for help.
Here is the sandbox code:
https://codesandbox.io/s/twilight-sky-y74zx

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
i1yas, 2019-09-14
@ArturPetrov

class FeedPost extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showComments: false
    }
  }
  handler = () => {
    this.setState({
      showComments: !this.state.showComments
    })
  };
  render = () => {
    const {post} = this.props;
    return <li>
      <div>{post.title}</div>
      <div
        onClick={this.handler}
        style={{
          cursor: "pointer",
          color: "blue",
          textDecoration: "underline",
          userSelect: "none"
        }}
      >
        {this.state.showComments ? "Hide comments" : "Show comments"}
      </div>
      {this.state.showComments && (
        <ul>
          {post.comments.map((comment, i) => (
            <li key={i}>{comment.text}</li>
          ))}
        </ul>
      )}
      <Link to={`/post/${post.id}`}>Open</Link>
    </li>
  }
}

The rest of the components do not need to be touched.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question