Pengenalan React Redux Bagian 1

Home-Office Work Station | HD photo by Caspar Camille Rubin (@casparrubin) on Unsplash

Photo by @casparrubin on Unsplash, accessed 15/07/2019

Pengertian React Redux

React Redux adalah sebuah Library yang memberikan kita beberapa methods yang memungkinkan untuk konek dengan React Komponen kita dan Redux State kita.

Berikut diagram bagaimana React dan Redux bisa berinteraksi / berkomunikasi :

React Redux Flow Diagram
React Komponen dan Redux State

Dalam aplikasi React Redux, React komponen tidak perlu lagi memperhatikan state React sendiri. Sebagai gantinya, state akan diambil oleh Redux store dan akan dilewatkan sebagai props ke React komponen. Action dispatching method juga akan dilewatkan sebagai props ke React komponen sebagai event handlers. Ketika pengguna membuat sebuah event, React komponen bisa dispatch actions untuk memperbarui Redux store. Sehingga, membuat React komponen memperbarui views sejak React komponen mendapatkan props dari Redux Store.

Contoh : Codesanbox

Mengatur React dan Redux di Lokal

buat dengan Create React App dengan cara :

npx create-react-app project-name 
cd project-name 

React Redux tidak diinstall bersamaan saat kita install React, sehingga kita harus install libary tersebut dengan cara

npm install redux react-redux

Selanjutnya, kamu bisa import React Redux di app.js file :

import React from 'react'
import { render } from 'react-dom'
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'
//...

Cobalah untuk mengetik beberapa code berikut pada app.js

import React from "react";
import ReactDOM from "react-dom";
import { createStore, combineReducers } from "redux";
import { Provider, connect } from "react-redux";

//action creator
const addItem = (name, price) => {
  return {
    type: "ADD_ITEM",
    item: {
      name: name,
      price: price
    }
  };
};

const deleteItem = index => {
  return {
    type: "DELETE_ITEM",
    index: index
  };
};

//reducer
const reducer = (state = [], action) => {

  switch (action.type) {
   case "ADD_ITEM":
      return [...state, action.item];
    case "DELETE_ITEM":
      return [
        ...state.slice(0, action.index),
        ...state.slice(action.index + 1)
      ];
    default:
      return state;
  }
};

//store
var store = createStore(reducer);


//presentational components
const Item = props => {
  return (
    <div>
      <div>
        Item : {props.name} | Price: {props.price}
      </div>
      <button onClick={() => props.onDelete(props.index)}>Delete</button>
    </div>
  );
};

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: "", price: "" };
  }
  handleChangeName(event) {
    this.setState({ name: event.target.value });
  }
  handleChangePrice(event) {
    this.setState({ price: event.target.value });
  }
  addItem(){
    this.props.onAdd(this.state.name, this.state.price)
    this.setState({ name: "", price: "" })
  }
  render() {
    return (
      <div>
        <input
          onChange={this.handleChangeName.bind(this)}
          value={this.state.name}
        />
        <input
          onChange={this.handleChangePrice.bind(this)}
          value={this.state.price}
        />
        <button
          onClick={() => this.addItem()}>
          Add
        </button>
      </div>
    );
  }
}

const ItemsList = props => {
  return (
    <div>
      <Input onAdd={props.onAdd} />
      {props.items.map((item, index) => {
        return (
          <Item
            onDelete={props.onDelete}
            index={index}
            name={item.name}
            price={item.price}
          />
        );
      })}
    </div>
  );
};

const mapStateToProps = state => {
  return {
    items: state
  };
};

const mapDispatchToProps = dispatch => {
  return {
    onAdd: (name, price) => {
      console.log(dispatch(addItem(name, price)));
      console.log(store.getState());
    },
    onDelete: id => {
      console.log(dispatch(deleteItem(id)));
    }
  };
};

//container components
const ItemsListContainer = connect(mapStateToProps, mapDispatchToProps)(
  ItemsList
);

const App = () => {
  return (
    <Provider store = {store}>
      <div>
        <ItemsListContainer />
      </div>
    </Provider>
  );
}



export default App;

Menggunakan Codesandbox untuk React Redux

Pada dependency klik react-redux.Juga lihatlah untuk menambahkan redux juga.

Lalu, import React Redux pada file index.js

import React from 'react'
import { render } from 'react-dom' 
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'

Cobalah ketikan code index.js seperti berikut :

import React from "react";
import ReactDOM from "react-dom";
import { createStore, combineReducers } from "redux";
import { Provider, connect } from "react-redux";

//action creator
const addItem = (name, price) => {
  return {
    type: "ADD_ITEM",
    item: {
      name: name,
      price: price
    }
  };
};

const deleteItem = index => {
  return {
    type: "DELETE_ITEM",
    index: index
  };
};

//reducer
const reducer = (state = [], action) => {

  switch (action.type) {
   case "ADD_ITEM":
      return [...state, action.item];
    case "DELETE_ITEM":
      return [
        ...state.slice(0, action.index),
        ...state.slice(action.index + 1)
      ];
    default:
      return state;
  }
};

//store
var store = createStore(reducer);


//presentational components
const Item = props => {
  return (
    <div>
      <div>
        Item : {props.name} | Price: {props.price}
      </div>
      <button onClick={() => props.onDelete(props.index)}>Delete</button>
    </div>
  );
};

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: "", price: "" };
  }
  handleChangeName(event) {
    this.setState({ name: event.target.value });
  }
  handleChangePrice(event) {
    this.setState({ price: event.target.value });
  }
  addItem(){
    this.props.onAdd(this.state.name, this.state.price)
    this.setState({ name: "", price: "" })
  }
  render() {
    return (
      <div>
        <input
          onChange={this.handleChangeName.bind(this)}
          value={this.state.name}
        />
        <input
          onChange={this.handleChangePrice.bind(this)}
          value={this.state.price}
        />
        <button
          onClick={() => this.addItem()}>
          Add
        </button>
      </div>
    );
  }
}

const ItemsList = props => {
  return (
    <div>
      <Input onAdd={props.onAdd} />
      {props.items.map((item, index) => {
        return (
          <Item
            onDelete={props.onDelete}
            index={index}
            name={item.name}
            price={item.price}
          />
        );
      })}
    </div>
  );
};

const mapStateToProps = state => {
  return {
    items: state
  };
};

const mapDispatchToProps = dispatch => {
  return {
    onAdd: (name, price) => {
      console.log(dispatch(addItem(name, price)));
      console.log(store.getState());
    },
    onDelete: id => {
      console.log(dispatch(deleteItem(id)));
    }
  };
};

//container components
const ItemsListContainer = connect(mapStateToProps, mapDispatchToProps)(
  ItemsList
);

const App = () => {
  return (
    <div>
      <ItemsListContainer />
    </div>
  );
}

const rootElement = document.getElementById("root");

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  rootElement
);

Contoh : Codesanbox

NB : Artikel ini merupakan series dari React Redux Tutorial

Referensi :

React Router Redux from Microsoft

Tagged , , , , ,

Leave a Reply

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