Skip to content

Instantly share code, notes, and snippets.

@eezhal92
Created September 8, 2018 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eezhal92/1a5a23db12c0775382ebf9069f568a02 to your computer and use it in GitHub Desktop.
Save eezhal92/1a5a23db12c0775382ebf9069f568a02 to your computer and use it in GitHub Desktop.
Sharing basic react
import React from 'react';
import ReactDOM from 'react-dom';
function TodoItem (props) {
return <div>{props.title}</div>
}
function TodoList (props) {
return (
<div>
{props.todos.map((item) => {
return <TodoItem
key={item.id}
title={item.judul}
/>
})}
</div>
)
}
class AddTodoForm extends React.Component {
handleSubmit = (event) => {
event.preventDefault()
const todoTitle = event.target.title.value
this.props.onAddTodo(todoTitle)
event.target.reset()
}
render () {
return (
<form onSubmit={this.handleSubmit}>
<input name="title" placeholder="Add todo..." />
<button type="submit">Add</button>
</form>
)
}
}
class App extends React.Component {
constructor(props) {
super(props)
}
state = {
title: 'Foobar',
todos: [
{
id: 1,
judul: 'Eat',
},
{
id: 2,
judul: 'Pray',
},
{
id: 3,
judul: 'Code',
},
]
}
componentDidMount () {
this.readTodosFromLocalStorage()
}
readTodosFromLocalStorage = () => {
let todos = []
try {
todos = JSON.parse(localStorage.getItem('persistedTodos'))
} catch (err) {
}
this.setState({ todos })
}
handleOnAddTodo = (todoTitle) => {
const todo = {
id: (Math.random() * 1000).toFixed(0),
judul: todoTitle,
}
this.setState((previousState) => {
const { todos: previousTodos } = previousState
return { todos: previousTodos.concat(todo) }
}, () => {
this.saveToLocalStorage()
})
}
saveToLocalStorage () {
const { todos } = this.state
localStorage.setItem('persistedTodos', JSON.stringify(todos))
}
render () {
const { todos } = this.state
return (
<React.Fragment>
<TodoList todos={todos} />
<AddTodoForm onAddTodo={this.handleOnAddTodo} />
</React.Fragment>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment