React: Use Provider to Connect Redux to React

Hello,
Use Provider to Connect Redux to React

In this exercise we make the link between redux part et React part with “react-redux”, OK. But I don’t understand how “react-redux” make the link between the state of the component and the global state of redux because there isn’t same properties between both.
In redux there is a propertie “message” without “s”, and in React component there is the property “messages” with one “s”.

How “react-redux” make the link between:
image
and:
image

// Redux:
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:

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() {  
    this.setState((state) => {
      const currentMessage = state.input;
      return {
        input: '',
        messages: 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 below this line
  render() {
  return <Provider store={store}>
  <DisplayMessages/>
  </Provider>
  }

  // Change code above this line
};

But I don’t understand how “react-redux” make the link between the state of the component and the global state of redux because there isn’t same properties between both.

There isn’t a connection between the component state and the redux “global state”. They are two different things. The Provider just makes the redux state available to its children components. In the next lesson you will learn how to use connect and mapStateToProps to hook into that and get the redux state you want in the the component props.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.