Skip to content

Instantly share code, notes, and snippets.

@jepras
Created October 21, 2018 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jepras/80b06435b56299a6820c4aa5986e0872 to your computer and use it in GitHub Desktop.
Save jepras/80b06435b56299a6820c4aa5986e0872 to your computer and use it in GitHub Desktop.
mapStateToProps & mapDispatchToProps injects redux into the component to use. In Presentional, submitMessage dispatches Redux function submitNewMessage with local React state input. This is then rendered with this.props.messages as messages is the state in Redux.
// Awesome sandbox: https://codesandbox.io/s/13on9ykl1l
// 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;
// Change code below this line
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>
{this.props.messages.map( (message, idx) => {
return (
<li key={idx}>{message}</li>
)
})
}
</ul>
</div>
);
}
};
// Change code above this line
const mapStateToProps = (state) => {
return {messages: state}
};
const mapDispatchToProps = (dispatch) => {
return {
submitNewMessage: (message) => {
dispatch(addMessage(message))
}
}
};
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