0 points

Use Provider to Connect Redux to React


dashboard

Thu Nov 12 2020 23:41:22 GMT+0000 (UTC)

Posted by @bifrost #react.js

// 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 COMPONENTS*****/
  
 // React Code:

  class DisplayMessages extends React.Component {
  
 /*CONSTRUCTOR*/
  
    constructor(props) {
      super(props);
      this.state = {
        input: '',
        messages: []
      }
      this.handleChange = this.handleChange.bind(this);
      this.submitMessage = this.submitMessage.bind(this);
    }
    
 /*METHODES*/
  
    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>
      );
    }
  };
  
  
 /*PROVIDER*/
  
  const Provider = ReactRedux.Provider;

/*MAIN COMPONENTS*/
  class AppWrapper extends React.Component {
    // Below is the code required to pass the test
    render() {
      return (
        <Provider store={store}>
          <DisplayMessages />
        </Provider>
      );
    }
    // Above is the code required to pass the test
  };
content_copy Copy

Create a list with REACT REDUX

https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-use-provider-to-connect-redux-to-react/301435