Creating User Interface

Learn to create the UI.

To give you an idea of how a basic UI can connect to Redux, we will use a bit of jQuery magic.

Note: this example is very simple and should never be used in a real application.

Let’s store our current UI in ui.js. The jQuery UI will create a simple view of the current recipes in the store:

import $ from 'jquery';
import store from './store';

function updateUI() {
  const { recipes } = store.getState();
  const renderRecipe = (recipe) => `<li>${ recipe.name }</li>`;

  $('.recipes > ul').html(recipes.map(renderRecipe));
}

export default function loadUI() {
  $('#app').append(`
    <div class="recipes">
      <h2>Recipes:</h2>
      <ul></ul>
    </div>
  `);

  store.subscribe(updateUI);

  updateUI();
}

We are using jQuery’s append() method to add a new div to our application container and using the updateUI() function to pull the recipes list from our state and display the recipes as a list of unordered elements.

To make our UI respond to updates, we can register the updateUI() function within our store, inside loadUI():

Append the following to the ui.js file:

store.subscribe(updateUI);

Now it’s time to connect this UI logic into our application. We can do that by importing the loadUI() function from the file we’ve just created and calling it inside the app.js file:

import store from './store';
import loadUI from './ui';
import { addRecipe } from './actions/recipes';
import { addIngredient } from './actions/ingredients';

loadUI();

store.dispatch(addRecipe('Pancakes'));
store.dispatch(addIngredient('Pancakes', 'Egg', 3));

If you’ve done everything correctly, you should now see the UI in your browser.

To support adding recipes, we will add a simple input field and button and use our store’s dispatch() method and the addRecipe() action creator to send actions to the store. This action is in the ui.js file of the app below:

Get hands-on with 1400+ tech skills courses.