I am trying to make a simple to-do list on React. I do not use hooks as I haven’t learned how to use them yet. The problem is the states for the fields of the to-do list aren’t updating.
I put together a form with the fields I want to have on the task list and connected them to states through values. I then made a function that captures the values and updates the states through setState. What am I doing wrong?
class Form extends React.Component {
render() {
const {
taskInput,
priorityInput,
dateChange,
dateInput,
textInput,
handleChange,
handleClick,
isSaveButtonDisabled
} = this.props
return (
<form>
<label
htmlFor="task-input"
>
Tarefa:
<input
type="text"
id="task-input"
name="taskInput"
value={ taskInput }
onChange={ handleChange }
/>
</label>
<label
htmlFor="priority-input"
>
Prioridade:
<select
id="priority-input"
name="priorityInput"
value={ priorityInput }
onChange={ handleChange }
>
<option>Baixa</option>
<option>Normal</option>
<option>Alta</option>
<option>Urgente</option>
</select>
</label>
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
taskInput: '',
priorityInput: 'Baixa',
dateInput: '',
textInput: '',
isSaveButtonDisabled: true,
savedTasks: [],
};
}
handleChange = ({ target }) => {
const { name, value } = target;
this.setState({
[name]: value,
}, () => {
this.setState({ isSaveButtonDisabled: this.validateFields() })
});
}
2
Answers
In your onChange function you are not running the function passed. They are treated as values by react and not actual functions. I think this is because the actual implementation is from somewhere else. You should pass it in as a return function like this:
Update this on all your onChange functions that are called from the props. If it still doesnot work, try changing your handleChange function in your app component,
To :
Show where you call your Form component inside the App component and ensure props where well passed to Form
Your options fields should also have a value props, which refer to the actual value passed like this :
I hope I was helpful
using functional components is the way forward and as pointed out by @ThiefMaster and @Anes
using functional components and react hook, you have
}
Your form will look like this
NOTE: Please kindly learn about functional components and react hooks as I’m also learning but this will give you insight to what you’re referred to.