This project is to understand how redux can be used with react. Everything is in a single script for better understandability. When developing a complex redux-react app, you'll need to modularize (eg. components, actions, reducers etc.)
- Clone the project
git clone https://github.com/prabushitha/single-script-react-with-redux.git
- Install dependenies
npm install
- Run the project
npm start
There are basically 6 steps you need to follow.
1. Create middleware [Optional : But most of the times you'll need a middleware to make your work easier]
const middleware = applyMiddleware(createLogger());
We'll create a single reducer
const initialState = {
toggled:false
};
const reducer = (state=initialState, action)=>{
switch (action.type){
case 'TOGGLE':
return {toggled:!state.toggled};
default:
return state;
}
};
const store = createStore(reducer,middleware);
class TodoElement extends React.Component{
_toggle(){
this.props.dispatch({type:"TOGGLE",payload:'content'});
}
render(){
return (<button onClick={this._toggle.bind(this)} >{this.props.toggled?'Hide':'Show'}</button>);
}
}
const Todo = connect((state)=>{
return {
toggled:state.toggled
};
})(TodoElement);
ReactDOM.render(<Provider store={store}><Todo /></Provider>, document.getElementById('root'));
registerServiceWorker();
If you have new ideas to improve please create a issue and make a pull request