Billedresultat for redux image Exercise: Redux part 1 (Actions, Reducers and Store)

Idea: Introduction to Redux (Vanilla).
Background: Actions Reducers and Store

In this exercise you have to create a very simple Javascript (vanilla) App using Redux to handle user events.
It could look like this:


The user can click on a button to change the color of the big square.

 

Step 1 (project creation and adding Redux and semantic-ui)
Open VSCode and create a new folder 'color' with 2 files 'index.js' and a "default" 'index.html' page.

In the html-file, add a cdn for 'semantic-ui' and 'redux' and a script-tag to include the index.js file:


<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.js"></script>
<script src="index.js"></script>

 

Step 2 (Buttons and Label)
Add 3 Buttons and a Label/Canvas to the page. Add relevant id's and class's to the elements.

 

Step 3 (Actions and Action Creators)
In this projekt we have only 3 simple actions: {type : 'RED'} {type : 'BLUE'} and {type : 'GREEN'}.
Implement 3 action creator functions: red( ), blue( ) and green( ). Each returning their matching action object.

Step 4 (Reducers)
Create a reducer function: colorReducer(state, action). The function should take a color/state and an action object as arguments and return a new color/state.
Hint: The color/state could be a string of css-class'. If the function return a string with new css-class' (e.g.: "ui label massive red") - the return value can be used in a render-function to set the class property
of the Label/Canvas and change the elements color.


Step 5 (Store)
Use Redux.createStore(reducer) to create a new Store and assign the new Store to a const: store


Step 6 (Render-function)
Create a function render() to set the className of the Label/Canvas. The function will be used as callback-function to store.subscribe(callback).
Hint: If the Label/Canvas have an id, use: document.getElementById("id").className = store.getState().toString( )

 

Step 7 (subscribe)
The Store object have a subscribe method, that takes a callback-function as argument. The Store invokes the callback funktion when the state in the store has changed.
Call store.subscribe(render) - and render( ) will be invoked every time the state has changed.

 

Step 8 (onclick and store.dispatch(action))
For each button, add an eventhandler to the onClick-event. A click on a button should result in a call of the dispatch-method on the store object.
Hint: Use store.dispatch(action) and use the action creation function to create the action-argument.


Congratulation! - Redux is great, and so are you!!

/ Henrik H