I'm learning React from this channel. Recently, I stumbled upon React Hooks from here. So, I tried to convert a class based component to hook based. Here is my class based component:
import React, { Component } from 'react';
class AddNinja extends Component {
state = {
name: null,
age: null,
skill: null,
}
handleChange = e => {
this.setState({
[e.target.id]: e.target.value,
})
}
handleSubmit = e => {
e.preventDefault();
this.props.addNinja(this.state);
}
render() {
return (
<div>
<form onSubmit={ this.handleSubmit }>
<label htmlFor="name">Name: </label>
<input type="text" id="name" onChange={ this.handleChange } />
<label htmlFor="age">Age: </label>
<input type="number" id="age" onChange={ this.handleChange } />
<label htmlFor="skill">Skill: </label>
<input type="text" id="skill" onChange={ this.handleChange } />
<button>Submit</button>
</form>
</div>
)
}
}
Here is my converted component: https://codesandbox.io/s/n0lw4wo550?module=%2Fsrc%2FAddNinja.js
But I'm getting following error:
This is a standard JavaScript error when trying to call a function before it is defined. This error occurs if you try to execute a function that is not initialized or is not initialized correctly. This means that the expression did not return a function object.
The React. js "Uncaught TypeError: X is not a function" occurs when we try to call a value that is not a function as a function, e.g. calling the props object instead of a function. To solve the error, console. log the value you are calling and make sure it is a function.
To update your React version, install the latest versions of the react and react-dom packages by running npm install react@latest react-dom@latest . If you use create-react-app , also update the version of react-scripts . Copied! The command will update the versions of the react-related packages.
To check which React version is your project using you need to open the package. json. Take a look under the dependencies section. It should list all of the dependencies of your project and one of those should be React.
React hooks are available in React v16.8.0
. updated your react and react dom version to 16.8.0
.
"react": "16.8.0",
"react-dom": "16.8.0",
Here is your code with updated verion:https://codesandbox.io/s/qq90900xr4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With