Skip to main content
react-redux-example

Getting Started With React Redux Using React

We will create simple reactjs application and connect with react redux. React is a popular front-end framework to create single-page applications. The Redux is a state management tool. It helps you write applications that behave consistently, run in different environments (client, server, and native).

React Redux is the official React binding for Redux. It lets your React components read data from a Redux store, and dispatch actions to the store to update data.

We will add an employee module to this React Redux Example Tutorial. we can add new employees into the state and store them into store objects. we can also fetch all employee data from the store and display it in an HTML table.

What is Redux

The Redux uses the state of your application is kept in a store and each component can access any state that it needs from this store.

The Redux has the following three main concepts –

  • Store : The store holds the application state. There is only one store in any Redux application.
  • Reducers : Reducers are pure functions that take the current state of an application, perform an action and return a new state.
  • Action : The Actions are events. They are the only way you can send data from your application to your Redux store.

Checkout Other tutorials:

Why Do We Need Redux?

The main difficulty in single-page applications is the sharing of data between different components.The Redux solves this issue using store the application state.

The file structure would be like the below –

  • src
    • app.js – The main containers file.
    • AddEmployee.js – This is a dumb file for creating a new employee.
    • Employee.js – This is a dumb file for the employee list.
  • actions
    • index.js
    • models.js – The Employee module actions file.
  • reducers
    • index.js
    • empReducer.js – The Employee module reducers file.
  • containers
    • CreateEmployee.js – This is the Smart Component for Create Employee.
    • EmployeeList.js – The is the Smart Component for Employee List.

There are two types of component that exists in react redux integration. The Dumb component, which is static, and the Smart component have all logic and is connected to the store.

Create React Application

We will create react application using the below command –

create-react-app react-redux-app-example

The above command will create react react-redux-app-example application and install all basic dependencies.

Install React Dependencies

This react example has the following external dependencies and, needs to install into our application using npm.

Bootstrap 4 will use to list and create forms for the employee module.

npm install bootstrap --save

Added below entry into src/index.js file.

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

Installed redux and react-redux package for Redux functionality.

npm install redux react-redux --save

Installed node-uuid package for auto-incremented value for the id field.

npm install node-uuid --save

How To Connect Redux With React Application

We will follow the following steps to connect redux with react state.

We will create actions/models.js file and add the below code into this file –

export const ADD_EMPLOYEE = 'ADD_EMPLOYEE';

We will create actions/index.js file and add the below code into this file –

import { ADD_EMPLOYEE} from './models';
import {default as UUID} from "node-uuid";

export const createEmployee = ({ name, age, salary }) => ({
  type: ADD_EMPLOYEE,
  payload: {
    id:UUID.v4(),
    name,
    age,
    salary
  }
});

We will create reducers/empReducer.js file and add the below code into this file –

import { ADD_EMPLOYEE} from '../actions/models';

export default function empReducer(state = [], action) {
  switch (action.type) {
    case ADD_EMPLOYEE:
      return [...state, action.payload];
    default:
      return state;
  }
}

We will create reducers/index.js file and add the below code into this file –

import { combineReducers } from 'redux';
import emps from './empReducer';

export default combineReducers({
    emps: emps
});

Now, Create a smart add employee component into the containers folder. Let’s create container/CreateEmployee.js and added the below code –

import { connect } from 'react-redux';
import { createEmployee } from '../actions';
import AddEmployee from '../AddEmployee';

const mapDispatchToProps = dispatch => {
  return {
    onAddEmployee: emp => {
      dispatch(createEmployee(emp));
    }
  };
};

export default connect(
  null,
  mapDispatchToProps
)(AddEmployee);

Now, Create Dumb components into app/AddEmployee folder, We will add the below code into this file.

import React from 'react';

class AddEmployee extends React.Component {
 state = {
 	name: '',
 	age : 0,
 	salary :0
 }
 //handle input changes
  inputChange = e => {
  	this.setState({[e.target.name] : e.target.value});
  };
  handleSubmit = e => {
    console.log(this.state);
  	e.preventDefault();
    console.log('fffff');
  	if(this.state.name.trim() !== '') {
      this.props.onAddEmployee(this.state);
      this.handleReset();
  	}
  };

  handleReset = e => {
  	this.state = {
	 	name: '',
	 	age : 0,
	 	salary :0
	 }
  };
  render() {
    return (

<div>
          <form onsubmit="{" this.handlesubmit="" }="">

<div classname="form-group">
            <label htmlfor="emaployeename">Employee Name</label>
            <input type="text" classname="form-control" placeholder="Employee Name" name="name" onchange="{" this.inputchange="" }="" value="{" this.state.name="">
</div>



<div classname="form-group">
            <label htmlfor="emaployeeAge">Employee Age</label>
              <input type="text" placeholder="Employee Age" classname="form-control" name="age" onchange="{" this.inputchange="" }="" value="{" this.state.age="">
</div>


<div classname="form-group">
          <label htmlfor="emaployeeSalary">Employee Salary</label>
              <input type="text" placeholder="Employee Salary" classname="form-control" name="salary" onchange="{this.inputChange}" value="{this.state.salary" }="">
</div>


<div>
            <button type="submit" classname="btn btn-primary ml-2">Add Employee</button>
            <button type="button" classname="btn btn-warning ml-2" onclick="{" this.handlereset="" }="">
              Reset
            </button>
</div>

        </form>
</div>

    );
  };
}


export default AddEmployee;

Create handler method and static HTML form to get input from the user.

Now, we need to import this AddEmployee.js file inside src/App.js file.

import React from 'react';
import CreateEmployee from './containers/CreateEmployee';

function App() {
  return (

	<div classname="container">

		<div classname="row">

			<div classname="col-md-6">
					<createemployee>
				  </createemployee>
		    </div>
				 
		</div>

	</div>

      

  );
}

export default App;

Let’s run this react redux tutorial using npm start, if everything is fine, you will see add employee form.

Listing Component Integration With React Redux

Already, integrated add employee features with this react redux tutorial. Now, we will display all employee list on the home page.

Create Smart Component For Employee List

We will EmployeeList.js file into components/ folder, this file will have employee data iteration logic and bind data with tr element.

import React from 'react';
import { connect } from 'react-redux';
import Emp from '../Employee';

function EmployeeList({ emps, onDelete }) {
  console.log(emps);
  return (

<div>
      {emps.map(emp =&gt; {
        return (
          <emp emp="{" }="" key="{" emp.id="">
        );
      })}
    </emp></div>

  );
}

const mapStateToProps = state =&gt; {
  return {
    emps: state.emps
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(EmployeeList);

Created Dumb Component For Employee List

We will create employee dumb component under app/Employee.js folder.This file will have static data with html elements.

import React from 'react';

export default ({ emp: { id, name, age, salary }, onDelete }) =&gt; {
  return (
    
    
      { name }
      { age }
      { salary }
    
  )
};

Bind Employee List With Main Container

We will call employee list component into main app.js container.

...
import EmpList from './containers/EmployeeList';

function App() {
  return (
  .....
      <emplist>

</emplist>
<table classname="table table-bordered">

<thead>

<tr>

<th scope="col">Name</th>


<th scope="col">Age</th>


<th scope="col">Salary</th>

</tr>

</thead>


<tbody>
</tbody>

</table>

   ...
  );
}

export default App;

Save the file and go to the http://localhost:3000/

If everything is configured and coded fine then we can be able to add and display the employee.

Leave a Reply

Your email address will not be published. Required fields are marked *