Build yourself a Redux
Starting point for creating JSFiddles with React. This uses React with Addons.
by justindeal
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://npmcdn.com/react@latest/dist/react-with-addons.js"></script>
<script src="https://npmcdn.com/react-dom@latest/dist/react-dom.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="app"></div>
Babel + JSX
const initialState = {
nextNoteId: 1,
notes: {}
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'createNote': {
const id = state.nextNoteId
const newNote = {
id,
content: ''
}
return Object.assign({}, state, {
nextNoteId: state.nextNoteId + 1,
notes: Object.assign({}, state.notes, {
[id]: newNote
})
})
}
case 'updateNote': {
const {id, content} = action
const editedNote = Object.assign({}, state.notes[id], {
content
})
return Object.assign({}, state, {
notes: Object.assign({}, state.notes, {
[id]: editedNote
})
})
}
default:
return state
}
}
const createStore = (reducer) => {
let state = undefined;
const store = {
dispatch: (action) => {
state = reducer(state, action);
console.log(state);
},
getState: () => state
}
store.dispatch({type: '@@redux/INIT'})
return store;
}
const store = createStore(reducer);
const Note = ({note, onChangeNote}) => (
<li>
<input
type="text"
value={note.content}
onChange={(event) => onChangeNote(note.id, event.target.value)}
/>
</li>
)
const NoteList = ({notes, onChangeNote}) => (
<ul>
{
Object.keys(notes).map(id =>
<Note
key={id}
note={notes[id]}
onChangeNote={onChangeNote}
/>
)
}
</ul>
)
const NoteEditor = ({notes, onAddNote, onChangeNote}) => (
<div>
<NoteList notes={notes} onChangeNote={onChangeNote}/>
<button onClick={onAddNote}>New Note</button>
</div>
)
class NoteListContainer extends React.Component {
constructor(props) {
super()
this.state = props.store.getState()
this.onAddNote = this.onAddNote.bind(this)
this.onChangeNote = this.onChangeNote.bind(this)
}
onAddNote() {
this.props.store.dispatch({
type: 'createNote'
})
this.setState(this.props.store.getState())
...