Search code examples
reactjsfunctionreact-hooksconstructorcomponents

How to transform this function component into a class component? (React.js)


I am new to React and struggle to transform this function component into a class component with a constructor(). I can't figure out how to transform the functions happening onSubmit and onClick.

Thank you very much.

The function component:

import React, { useState, Component } from 'react';
import { render } from 'react-dom';
import './Options.css';

const Test = (props) => {
  const [links, setLinks] = useState([]);
  const [link, setLink] = useState('');

  function handleSubmit(e) {
    e.preventDefault();
    const newLink = {
      id: new Date().getTime(),
      text: link,
    };
    setLinks([...links].concat(newLink));
    setLink('');
  }

  function deleteLink(id) {
    const updatedLinks = [...links].filter((link) => link.id !== id);
    setLinks(updatedLinks);
  }

  return (
    <div className="OptionsContainer">
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          onChange={(e) => setLink(e.target.value)}
          value={link}
        />
        <button type="submit"> + </button>
      </form>
      {links.map((link) => (
        <div key={link.id}>
          <div>{link.text}</div>
          <button onClick={() => deleteLink(link.id)}>Remove</button>
        </div>
      ))}
    </div>
  );
};

export default Test;

Solution

  • When we work with class components a couple of things got changed, we have a new object this.state, a new function this.setState, you have to bind your functions on the constructor if you want to have access to this inside it. I think you'll learn way more if you read the code, so here this is your component as a class component:

    import React, { Component } from 'react';
    
    import './Options.css';
    
    class App extends Component {
      constructor() {
        super()
        this.state = {
          links: [],
          link: '',
        }
    
        this.handleSubmit = this.handleSubmit.bind(this);
      }
    
      handleSubmit(e) {
        e.preventDefault();
        const newLink = {
          id: new Date().getTime(),
          text: this.state.link,
        };
        
        this.setState({links: [...this.state.links, newLink], link: ''});
      }
    
      deleteLink(id) {
        const updatedLinks = [...this.state.links].filter((link) => link.id !== id);
        this.setState({...this.state, links: updatedLinks });
      }
    
      render() {
        console.log(this.state)
        return (
          <div className="OptionsContainer">
            <form onSubmit={this.handleSubmit}>
              <input
                type="text"
                onChange={(e) => this.setState({ ...this.state, link: e.target.value})}
                value={this.state.link}
              />
              <button type="submit"> + </button>
            </form>
            {this.state.links.map((link, index) => (
              <div key={link.id}>
                <span>{link.text}</span>
                <button onClick={() => this.deleteLink(link.id)}>Remove</button>
              </div>
            ))}
          </div>
        );
      }
    };
    
    export default Test;