Sample React & Redux Application
Sample React & Redux working application
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const { createStore, bindActionCreators } = Redux;
const { Provider, connect } = ReactRedux;
//REDUX:
const ADD='ADD';
const addMessage =(message)=>{
return {
type:ADD,
message
};
}
const messageReducer = (state=[], action)=>{
switch(action.type){
case ADD:
return state.concat(action.message);
break;
default:
return state;
}
}
const store = Redux.createStore(messageReducer);
//REACT:
class DisplayMessages extends React.Component {
constructor(props){
super(props);
this.state={
input:'',
};
}
handleChange(event){
this.setState({
input: event.target.value
})
};
submitMessage(){
this.props.submitNewMessage(this.state.input);
this.setState((state)=>{
return{
input:'',
};
});
}
render(){
return (
<div>
<input onChange={this.handleChange.bind(this)} value={this.state.input}/>
<button onClick={this.submitMessage.bind(this)}>Submit</button>
<ul>
{this.props.messages.map((messages,idx)=>{
return(
<li key={idx}>{messages}</li>
)
})}
</ul>
</div>
);
}
}
//REACT-REDUX CONNECT:
const mapStateToProps = (state) =>{
return {
messages: state
}
}
const mapDispatchToProps = (dispatch)=>{
return {
submitNewMessage:(newMessage)=>{
dispatch(addMessage(newMessage))
}
}
}
const Container = connect(mapStateToProps,mapDispatchToProps)(DisplayMessages)
//Provider:
class AddWrapper extends React.Component{
render(){
return(
<Provider store={store}>
<Container/>
</Provider>
);
}
}
ReactDOM.render(<AddWrapper/>, document.getElementById('root'))
//HTML:<div id="root"></div>
Required Imports for React Application
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider, connect } from 'react-redux'
import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from './redux/reducers'
import App from './components/App'
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
ReactDOM.render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById('root')
);
*/
// Only change code below this line
console.log('Now I know React and Redux!')
You can use following links to test above code
Online Testing Environment https://codepen.io/
To test locally set up React in you PC using following Link
https://www.freecodecamp.org/news/install-react-with-create-react-app/