snake snake - 9 months ago 34
React JSX Question

React form still refreshes even after addying event.prefeventDefault

Can anyone explain to me why my react form is still refreshing after submitting? I'm making a simple todo list to get familiar with react and I can't seem to figure out this bug. What I'm trying to do is add a task to a list, the display that list. Check out this codepen to see my code, sorry for the poor formatting.

class TaskList extends React.Component {
render() {
var taskEntries = this.props.entries;

function createTasks(task) {
return <li key={task.key}>{task.text}</li>
}

var listTasks = taskEntries.map(createTasks);

return (
<ul>
{listTasks}
</ul>
);
}
}

class Task extends React.Component {
constructor() {
super();
this.state = {
tasks: [],
};
this.addTask = this.addTask.bind(this);
}

addTask(evt) {
evt.preventDefault;
var taskArray = this.state.tasks;

taskArray.push(
{
text: this.textInput.value,
key: Date.now()
}
);

this.setState({
tasks: taskArray
});
}

render() {
return (
<div>
<form onSubmit={this.addTask}>
<label htmlFor="title">Title of Task</label>
<input type="text" ref={(input) => { this.textInput = input; }} />
<label htmlFor="description">Description</label>
<input type="submit"/>
</form>
<TaskList entries={this.state.tasks} />
</div>
);
}
}

var destination = document.querySelector(".container");

ReactDOM.render(
<Task />,
destination
);

Answer Source

you should change

evt.preventDefault

to

evt.preventDefault()