Search code examples
reactjsredux-form

React redux-form read value onchange from other component in real time


Here is the code https://codesandbox.io/s/7073llkj

The simple example use the redux-form-website-template to show the value, i am very new to react and redux-form, i even dont know what is this, i just wanna read the value very simple in other components.

import React, { Component } from "react";

class ComponentOne extends Component {
  render() {
    return (
      <div>
        <div>CompoenntOne: I wannna read the props.values.firstName here</div>
        <div>CompoenntOne: I wannna read the props.values.lastName here</div>
      </div>
    );
  }
}

export default ComponentOne;

Any way or example to show the value very simple in other components?


Solution

  • Everytime a SimpleForm's field value is changed, the updated value is kept in the Redux's Store.

    In order to get the form's values:

    1. First thing you have to do is to connect ComponentOne with the Redux's Store, in order to have access to the Form's state.
    2. Secondly, you can query the Store and get the SimpleForm's values.

    Something like that:

    import React, { Component } from 'react'
    import { connect } from 'react-redux'
    import { getFormValues } from 'redux-form'
    
    
    class ComponentOne extends Component {
      render() {
        const { values } = this.props
    
        return (
          <div>
            <div>CompoenntOne: I wannna read the values.firstName here</div>
            <div>CompoenntOne: I wannna read the values.lastName here</div>
          </div>
        )
      }
    }
    
    const mapStateToProps = state => ({
      // 2. Secondly, you can query the Store and get the `SimpleForm`'s field value.
      values: getFormValues('simple')(state) || {}
    })
    
    // 1. First thing you have to do is to connect `ComponentOne` with the Redux's Store,
    // in order to have access to the Form's state, because it's kept in the Store.
    export default connect(mapStateToProps)(ComponentOne)