Skip to content

Instantly share code, notes, and snippets.

@janek26
Created November 8, 2018 23:01
Show Gist options
  • Save janek26/0ad516ab155fdd134a4635cef6e9e55c to your computer and use it in GitHub Desktop.
Save janek26/0ad516ab155fdd134a4635cef6e9e55c to your computer and use it in GitHub Desktop.
import React, { Component } from 'react'
// <TODO /> COMPONENT
// React function component ( without state => stateless )
const Todo = ({ todo }) => <li>{todo}</li>
// <TODOS /> COMPONENT
// React function component ( without state => stateless )
const Todos = ({
// destructure todo and default to empty array ( when undefined default to [] )
todos = [],
}) => (
<ul>
{
// Array.map() runs through all items and returns an array of the returned values
// so [0, 1, 2, 3].map(x => x * 2) returns [0, 1, 4, 6]
}
{todos.map(todo => (
<Todo todo={todo} />
))}
</ul>
)
// <APP /> COMPONENT with logic/state
// React class component ( with state => stateful )
export default class TodosApp extends Component {
// state defaults
state = {
textInput: '',
todos: [],
}
// one way to declare an instance method
add = () => {
const { textInput: newTodo } = this.state
// call setState with function as arg ( this.setState(oldState => newState) )
this.setState(({ todos }) => ({
// add newTodo as first item
todos: [newTodo, ...todos],
// reset TextField
textInput: '',
}))
}
// another way to declare an instance method
render() {
const { textInput, todos } = this.state
return (
<div>
<h1>Todos</h1>
<div style={{ display: 'flex' }}>
<input
style={{ flex: 1 }}
value={textInput}
// inline function
onChange={({ target: { value: textInput } }) =>
// call setState with new state as arg ( this.setState(newState) )
this.setState({ textInput })
}
// onKeyPress is called before onChange and is a native javascript event
// we just handle Enter to add a Todo, that way the user don't have to click the Add Button
onKeyPress={
// && expects both to be true and runs from left to right. In (exp1 && exp2) when exp1 is false, exp2 will never be called
// it's the same as exp1 ? exp2 : undefined which is called an inline if and equal to
// if (exp1) {
// exp2
// } else {
// // nothing
// }
({ key }) => key === 'Enter' && this.add()
}
/>
<button
// extracted function
onClick={this.add} // same as onClick={e => this.add(e)} but add doesn't need any args to run and ignores them when provided
>
Add
</button>
</div>
{
// Render todos
}
<Todos todos={todos} />
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment