Given this component:
import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
const NewGoalInput = props => {
return (
<input type="text" onKeyUp={handleKeyUp}/>
)
}
const handleKeyUp = (e) => {
if (e.key === "Enter") {
// TODO Add goal
}
}
export default NewGoalInput
How do I add a constructor where I can define the state without using the extends React.Component
syntax?
To simulate constructor in FC use useEffect.
That's it! EZ! This useEffect runs only once when the component loads and never runs after, just don't forget to add square brackets at the end.
Since it's a stateless component it doesn't have the component lifecycle. Therefor you can't specify a
constructor
.You have to extend
React.Component
to create a stateful component which then will need a constructor and you'll be able to use thestate
.Update Since React 16.8.0 and Hooks got introduced there are more options.
Stateless:
Stateful:
Has access to component lifecycle methods and local state.
Using Hooks:
Able to use
State Hook
andEffect Hook
.You don't. The kind of component in your example is called "stateless functional component". It has no state and no lifecycle methods. If you want your component to be stateful you'll have to write it as a class component.
Now that we have
useState
and hooks the answers are kind of out of date. I came across this question because I was doing something wrong. Here's some simplified code of what I was doing.This code was converted from a stateful class to a function using hooks, originally setting the default props in the constructor - but functions don't have constructors and that check happens every time the component re-renders:
useState
As you can see this results in an infinite loop. The solution is really quite simple. Here's a mock diff from the original.
Basically, just initialise the state from the props and don't do silly things like calling
useState
except in response to an event or callback of some type.