Skip to content

Instantly share code, notes, and snippets.

@devarajchidambaram
Created October 11, 2018 11:55
Show Gist options
  • Save devarajchidambaram/24d839c269b0c4ad35e6a70d8a3a0e8a to your computer and use it in GitHub Desktop.
Save devarajchidambaram/24d839c269b0c4ad35e6a70d8a3a0e8a to your computer and use it in GitHub Desktop.
React js + redux
import React ,{Component} from "react";
import { connect } from 'react-redux';
alert(connect)
class Counter extends Component{
constructor(props){
super(props);
// this.state = {
// count : 0
// }
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
}
increment(){
this.props.dispatch({ type: 'INCREMENT' });
// this.setState({
// count: this.state.count + 1
// })
}
decrement(){
this.props.dispatch({ type: 'DECREMENT' });
// this.setState({
// count: this.state.count - 1
// })
}
render(){
return ( <div>
<h2>Counter</h2>
<div>
<button onClick={this.decrement}>-</button>
<span> {this.props.count}</span>
<button onClick={this.increment}>+</button>
</div>
</div>
)
}
}
function mapStateToProps(state) {
return {
count: state.count
};
}
export default connect(mapStateToProps)(Counter);;
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Counter from './Counter';
import * as serviceWorker from './serviceWorker';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
const initialState = {
count: 0
};
function reducer(state = initialState, action) {
//alert("actionType=>"+ action.type)
switch(action.type) {
case 'INCREMENT':
return {
count: state.count + 1
};
case 'DECREMENT':
return {
count: state.count - 1
};
default:
return state;
}
}
const store = createStore(reducer);
const App = () => (
<Provider store= {store}>
<Counter/>
</Provider>
);
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment