Skip to content

Instantly share code, notes, and snippets.

@jillesme
Last active August 30, 2018 09:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jillesme/b39e97c70c91dd26c565a4bab1a3d194 to your computer and use it in GitHub Desktop.
Save jillesme/b39e97c70c91dd26c565a4bab1a3d194 to your computer and use it in GitHub Desktop.
React, Redux and react-redux
import React, { Component } from 'react';
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'
// create-react-app specific
import logo from './logo.svg';
import './App.css';
const FRAMEWORKS = ['React', 'Angular', 'Vue', 'Ember'];
// ACTION CREATORS
function setFilter(by) {
return { type: 'SET_FILTER', by };
}
// REDUCER
const initialState = {
filterBy: ''
}
function reducer(state = initialState, action) {
switch (action.type) {
case 'SET_FILTER':
console.log(`Our filter was ${state.filterBy} but is now ${action.by}!`);
// return a new object
return Object.assign({}, state, {
filterBy: action.by
})
default:
return state
}
}
// STORE
const store = createStore(reducer);
// react-redux
const mapStateToProps = (state) => {
return {
filterBy: state.filterBy
}
}
const mapDispatchToProps = (dispatch) => {
return {
updateFilter: (ev) => dispatch(setFilter(ev.target.value))
}
}
class FilterList extends Component {
render() {
const { filterBy, updateFilter } = this.props;
return (
<div>
<input type="text" onChange={updateFilter}/>
<List items={FRAMEWORKS} filterBy={filterBy} />
</div>
)
}
}
// very important!
FilterList = connect(mapStateToProps, mapDispatchToProps)(FilterList);
const List = ({ items, filterBy }) => {
return (
<ul>
{
items
.filter(item => item.indexOf(filterBy) > -1)
.map((item, i) => <li key={i}>{item}</li>)
}
</ul>
)
}
class App extends Component {
render() {
return (
<Provider store={store}>
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<div className="App-intro">
<FilterList />
</div>
</div>
</Provider>
);
}
}
export default App;
@jillesme
Copy link
Author

jillesme commented Nov 6, 2016

I know FilterList could be a functional component too now and that it would be even better to add <List .../> as one of <FilterList>'s {this.props.children} but that's outside the scope of the post! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment