React Base Fiddle (JSX)
Starting point for creating JSFiddles with React.
HTML
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="app">
<!-- This element's contents will be replaced with your component. -->
</div>
Babel + JSX
class ToDo extends React.Component {
constructor() {
super()
this.state = {
todos: [],
inputValue: null
}
this.changeValue = this.changeValue.bind(this)
this.addTodo = this.addTodo.bind(this)
this.removeTodo = this.removeTodo.bind(this)
}
changeValue(e) {
this.setState({inputValue: e.target.value})
}
addTodo(e) {
e.preventDefault()
const newTodoItem = {
id: Date.now(),
inputValue: this.state.inputValue
}
if(!this.state.inputValue.length) return
this.setState(state => ({
todos: state.todos.concat(newTodoItem),
inputValue: ''
}))
}
removeTodo(e) {
const et = e.target
const attr = et.getAttribute("data-key");
this.setState(state => ({
todos: state.todos.filter(item => item.id != attr)
}))
}
render() {
return(
<div>
<form onSubmit={this.addTodo}>
<input
type='text'
name='todo'
placeholder='Enter a ToDo'
value={this.state.inputValue}
onChange={this.changeValue}
/>
<input type='submit' value='Add' />
<span>ToDos: {this.state.todos.length}</span>
</form>
<TodoList items={this.state.todos} itemClickEvent={this.removeTodo} />
</div>
)
}
}
class TodoList extends React.Component {
render() {
const items = this.props.items
return(
<ul>
{
items.map(item => (
<li key={item.id} data-key={item.id} onClick={this.props.itemClickEvent}>{item.inputValue}</li>
))
}
</ul>
)
}
}
ReactDOM.render(<ToDo />, document.querySelector('#app'))