Last active
May 27, 2019 09:51
-
-
Save uladzislau-stuk/c7e130eda07f29b9c06afa841e5e880d to your computer and use it in GitHub Desktop.
[Connect redux to the React app] #redux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Redux: | |
const ADD = 'ADD' | |
const addMessage = (message) => { | |
return { | |
type: ADD, | |
message: message | |
} | |
}; | |
const messageReducer = (state = [], action) => { | |
switch (action.type) { | |
case ADD: | |
return [ | |
...state, | |
action.message | |
]; | |
default: | |
return state | |
} | |
}; | |
const store = Redux.createStore(messageReducer) | |
// React: | |
const Provider = ReactRedux.Provider | |
const connect = ReactRedux.connect | |
class Presentational extends React.Component { | |
constructor(props) { | |
super(props) | |
this.state = { | |
input: '' | |
} | |
this.handleChange = this.handleChange.bind(this) | |
this.submitMessage = this.submitMessage.bind(this) | |
} | |
handleChange(event) { | |
this.setState({ | |
input: event.target.value | |
}) | |
} | |
submitMessage() { | |
this.setState({ | |
input: '' | |
}) | |
this.props.submitNewMessage(this.state.input) | |
} | |
render() { | |
return ( | |
<div> | |
<h2>Type in a new Message:</h2> | |
<input | |
value={this.state.input} | |
onChange={this.handleChange}/><br/> | |
<button onClick={this.submitMessage}>Submit</button> | |
<ul> | |
// Will be managed by Redux | |
{this.props.messages.map( (message, idx) => { | |
return ( | |
<li key={idx}>{message}</li> | |
) | |
}) | |
} | |
</ul> | |
</div> | |
) | |
} | |
} | |
// React-Redux: | |
const mapStateToProps = (state) => { | |
return {messages: state} | |
} | |
const mapDispatchToProps = (dispatch) => { | |
return { | |
submitNewMessage: (message) => { | |
dispatch(addMessage(message)) | |
} | |
} | |
} | |
// Component container: | |
const Container = connect(mapStateToProps, mapDispatchToProps)(Presentational) | |
class AppWrapper extends React.Component { | |
render() { | |
return ( | |
<Provider store={store}> | |
<Container/> | |
</Provider> | |
); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment