Vina Chan
Vina Chan

Reputation: 209

Cannot convert hooks code to a class in React

I am currently trying to write a class from the example I saw that uses hooks, however, I am can't make things work. Can someone help me with this? Here's the code. It's adding a field dynamically in React. The error says: ./src/App.js Line 27:34: 'handleInputChange' is not defined no-undef Line 34:34: 'handleInputChange' is not defined no-undef Line 38:36: 'handleAddClick' is not defined no-undef

import React from "react";

export default class App extends React.Component {

  constructor(props) {
    super(props);

     this.state = {
      inputList: [{ firstName: "", lastName: "" }]
    };

    this.handleAddClick = this.handleAddClick.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
  }

  // handle input change
   handleInputChange = (e, index) => {
   const { name, value } = e.target;
   const list = [...this.state.inputList];
   list[index][name] = value;
   this.setState({ inputList: list });
 }


  // handle click event of the Add button
  handleAddClick = () => {
    this.setState({
     inputList: [...this.state.inputList, { firstName: '', lastName: '' }]
    });
  }

 render() {
 return (
  <div className="App" >
    {
      this.state.inputList.map((x, i) => {
        return (
          <div className="box">
            <input
              name="firstName"
              placeholder="Enter First Name"
              value={x.firstName}
              onChange={e => handleInputChange(e, i)}
            />
            <input
              className="ml10"
              name="lastName"
              placeholder="Enter Last Name"
              value={x.lastName}
              onChange={e => handleInputChange(e, i)}
            />

            <div className="btn-box">
              <button onClick={handleAddClick}>Add</button>}
          </div>
          </div>
        );
      })
    }
    < div style={{ marginTop: 20 }}> {JSON.stringify(this.state.inputList)}</div >
  </div >
   );
 }
}

Here's the code that uses hooks and it works fine: https://www.cluemediator.com/add-or-remove-input-fields-dynamically-with-reactjs

Upvotes: 0

Views: 62

Answers (1)

Grant Singleton
Grant Singleton

Reputation: 1651

Call it with this

<button onClick={this.handleAddClick}>Add</button>}

You need to use this when accessing functions in a class component

Upvotes: 2

Related Questions