Created
October 19, 2018 12:34
-
-
Save jepras/2883ab620fbad6fbfd202a935f658661 to your computer and use it in GitHub Desktop.
React & Redux basic connected
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 Code: | |
const ADD = 'ADD'; | |
const addMessage = (message) => { | |
return { | |
type: ADD, | |
message | |
} | |
}; | |
const messageReducer = (state = [], action) => { | |
switch (action.type) { | |
case ADD: | |
return [ | |
...state, | |
action.message | |
]; | |
default: | |
return state; | |
} | |
}; | |
const store = Redux.createStore(messageReducer); | |
// React Code: | |
class DisplayMessages extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
input: '', | |
messages: [] | |
} | |
this.handleChange = this.handleChange.bind(this); | |
this.submitMessage = this.submitMessage.bind(this); | |
} | |
handleChange(event) { | |
this.setState({ | |
input: event.target.value | |
}); | |
} | |
submitMessage() { | |
const currentMessage = this.state.input; | |
this.setState({ | |
input: '', | |
messages: this.state.messages.concat(currentMessage) | |
}); | |
} | |
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.state.messages.map( (message, idx) => { | |
return ( | |
<li key={idx}>{message}</li> | |
) | |
}) | |
} | |
</ul> | |
</div> | |
); | |
} | |
}; | |
const Provider = ReactRedux.Provider; | |
class AppWrapper extends React.Component { | |
// render the Provider here | |
render () { | |
return( | |
<Provider store={store}> | |
<DisplayMessages /> | |
</Provider> | |
) | |
} | |
// change code above this line | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment