Created
October 21, 2018 08:16
-
-
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.
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
// 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