Skip to main content

14.09 Connecting Store To React

Installing react-redux

npm install --save react-redux

index.js

index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore } from "redux";
import App from "./App";
import "./index.css";
import registerServiceWorker from "./registerServiceWorker";
import reducer from "./store/reducer";

const store = createStore(reducer);

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
registerServiceWorker();

Counter.js

Counter.js
import React, { Component } from "react";
import { connect } from "react-redux";
import CounterControl from "../../components/CounterControl/CounterControl";
import CounterOutput from "../../components/CounterOutput/CounterOutput";

class Counter extends Component {
state = {
counter: 0,
};

counterChangedHandler = (action, value) => {
switch (action) {
case "inc":
this.setState((prevState) => {
return { counter: prevState.counter + 1 };
});
break;
case "dec":
this.setState((prevState) => {
return { counter: prevState.counter - 1 };
});
break;
case "add":
this.setState((prevState) => {
return { counter: prevState.counter + value };
});
break;
case "sub":
this.setState((prevState) => {
return { counter: prevState.counter - value };
});
break;
}
};

render() {
return (
<div>
<CounterOutput value={this.props.ctr} />
<CounterControl
label="Increment"
clicked={() => this.counterChangedHandler("inc")}
/>
<CounterControl
label="Decrement"
clicked={() => this.counterChangedHandler("dec")}
/>
<CounterControl
label="Add 5"
clicked={() => this.counterChangedHandler("add", 5)}
/>
<CounterControl
label="Subtract 5"
clicked={() => this.counterChangedHandler("sub", 5)}
/>
</div>
);
}
}

const mapStateToProps = (state) => {
return {
ctr: state.counter,
};
};

export default connect(mapStateToProps)(Counter);