Cezary Burzykowski Cezary Burzykowski - 4 years ago 403
React JSX Question

React - onClick event not working

I've just started learning React.js and currently I'm working on simple "to do" app. I have encountered problem with onClick event on my submit button, it doesn't seem to work. I think I have got a problem with passing props to parent elements.

Here is my code:



var Application = React.createClass ({
getInitialState: function() {
return {
title: "Your to do list",
subTitle: "What do you have to do?",
tasks: [],
}
},
addTask: function(event) {
event.preventDefault();
alert("it works!");
},
removeTask: function() {
var taskList = this.state.tasks;
var currentTask = taskList.find(function(task) {
return task.key == event.target.key;
});
currentTask.remove();
event.preventDefault();
alert("it works!");
},
render: function() {
return (
<div className="app-container">
<Header title={this.state.title} />
<NewTaskForm subTitle={this.state.subTitle} onChange= {this.addTask} />
<TaskContainer tasks={this.state.tasks} />
</div>
);
}
});


function Header(props) {
return (
<div className="app-title">
<h1>{props.title}</h1>
</div>
);
}

function NewTaskForm(props) {
return (
<div className="new-task-area">
<form>
<label for="new-task">{props.subTitle}</label>
<input type="text" id="new-task" placeholder="Type in task" />
<button type="submit" onClick={function() {props.onChange;}}>Add task!</button>
</form>
</div>
);
}

NewTaskForm.propTypes = {
onChange: React.PropTypes.func.isRequired,
};


function TaskContainer(props) {
return (
<div className="new-task-container">
{props.tasks.map(function(task) {
return (
<p key={task.key}>{task.text}</p>
);
})}
</div>
);
}


ReactDOM.render(<Application />, document.getElementById("container"));

<!DOCTYPE html>
<html>
<head>
<title>React to do app!</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet">
<link rel="stylesheet" href="css/style.css" type="text/css" />
</head>
<body>
<div id="container"></div>
<script type="text/javascript" src="js/react.js"></script>
<script type="text/javascript" src="js/react-dom.js"></script>
<script type="text/javascript" src="js/babel-browser.min.js"></script>
<script type="text/babel" src="js/app.jsx"></script>
</body>
</html>





I would really appreciate any help because I've been trying to solve this for some time now.

Answer Source

you didn't call the function:

<button type="submit" onClick={function() {props.onChange();}}>Add task!</button>

you can also write it like this:

<button type="submit" onClick={props.onChange}>Add task!</button>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download