Create simple static Redux-reducer
Let's create reducer
export default function() {
return [
{ title: 'JavaScript: The Good Parts'},
{ title: 'Harry Potter'},
{ title: 'The Dark Tower'},
{ title: 'Eloquent Ruby'}
]
}
Then we should import it into the index.js
import { combineReducers } from 'redux';
import BooksReducer from './reducer_books'
const rootReducer = combineReducers({
books: BooksReducer
});
export default rootReducer;
Now let's create the class, which will accept the props from reducer
class BookList extends Component{
};
Let's write render method
class BookList extends Component{
render () {
return (
<ul className="list-group col-sm-4">
</ul>
)
}
};
The next step is to define a function, which will render the list of the elements. Props are not passed to this class still, but, let's imagine, that we do it.
class BookList extends Component{
renderList() {
return this.props.books.map((book) => {
return (
<li key={book.title} className="list-group-item">{book.title}</li>
);
});
}
render () {
return (
<ul className="list-group col-sm-4">
</ul>
)
}
};
And for now let's call function in the render method
class BookList extends Component{
renderList() {
return this.props.books.map((book) => {
return (
<li key={book.title} className="list-group-item">{book.title}</li>
);
});
}
render () {
return (
<ul className="list-group col-sm-4">
{this.renderList()}
</ul>
)
}
};
This class is going to be container. Don't forget to place it in a spacial directory, src/containers, for example.
So, now we are going to bind React and Redux together, to pass data from the reducer to container.
Let's move to the app.js component, and add our container there.
export default class App extends Component {
render() {
return (
<div>
<BookList/>
</div>
);
}
}
Lrt's import connect property from react-redux library
import {connect} from 'react-redux'
After that, let's add mapStateToProps method to the file which contains container class
class BookList extends Component{
renderList() {
return this.props.books.map((book) => {
return (
<li key={book.title} className="list-group-item">{book.title}</li>
);
});
}
render () {
return (
<ul className="list-group col-sm-4">
{this.renderList()}
</ul>
)
}
}
function mapStateToProps(state) {
return {
books: state.books
}
}
And now let's export class connected to the function we've write
export default connect(mapStateToProps)(BookList)