Tags

Front End

Passing Values from a Component to Redux Form

Most of the developers will be using Redux Forms for their form handling and getting inputs from users. Here in this article, we'll see how we are going to pass values from one component to another. Let's get our components right here.

Below is a codesandbox of an app using a redux-form:

index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import store from "./store";
import MyParentComponentWrapper from "./MyParentComponentWrapper";
import LatLngForm from "./latLngForm";
const rootEl = document.getElementById("root");
ReactDOM.render(
 

, rootEl );

MyParentComponentWrapper.js
import React from "react";
import { connect } from "react-redux";
import { change, formValueSelector } from "redux-form";
import { compose, withProps, lifecycle } from "recompose";
import {
   withScriptjs,
   withGoogleMap,
   GoogleMap,
   Marker
} from "react-google-maps";
const formSelector = formValueSelector("form");

const MyMapComponent = compose(

  withProps({
    googleMapURL:
"https://maps.googleapis.com/maps/api/js?key=AIzaSyCYSleVFeEf3RR8NlBy2_PzHECzPFFdEP0&libraries=geometry,drawing,plac
es",
   loadingElement: 
, containerElement:
, mapElement:
}), lifecycle({ componentWillMount() { const refs = {}; this.setState({ onMarkerMounted: ref => { refs.marker = ref; }, onPositionChanged: () => { const position = refs.marker.getPosition(); console.log(position.toString()); this.props.onMakerPositionChanged(position); } }); } }), withScriptjs, withGoogleMap )(props => { return ( {props.isMarkerShown && ( )} ); }); class MyParentComponentWrapper extends React.Component { constructor(props) { super(props); this.state = { isMarkerShown: false }; this.onMakerPositionChanged = this.onMakerPositionChanged.bind(this); } onMakerPositionChanged(position) { this.props.dispatch(change("form", "lat", position.lat())); this.props.dispatch(change("form", "lng", position.lng())); } render() { return (
 
); } } const mapStateToProps = state => ({ position: { lat: parseFloat(formSelector(state, "lat")), lng: parseFloat(formSelector(state, "lng")) } }); export default connect(mapStateToProps)(MyParentComponentWrapper);
latLngForm.js
import React from "react";
import { connect } from "react-redux";
import { Field, reduxForm } from "redux-form";

let LatLngForm = () => {
  return (
  
Lat: Lng: ); }; LatLngForm = reduxForm({ form: "form" })(LatLngForm); LatLngForm = connect(state => ({ initialValues: { lat: -34.397, lng: 150.644 } }))(LatLngForm); export default LatLngForm;
store.js
import { createStore, combineReducers } from 'redux';
import { reducer as reduxFormReducer } from 'redux-form';

const reducer = combineReducers({
    form: reduxFormReducer, // mounted under "form"
});

const store = (window.devToolsExtension
    ? window.devToolsExtension()(createStore)
    : createStore)(reducer);

export default store;

Get the full code in CodeSandbox.

Notice that after setting up the form inlatLngForm.js , I use connect in the map container to dispatch reduxForm 's change action when your marker is moved. This is what updates
the store.

I also pass position in as a prop to to set the position of your marker. This means that the marker's position is always based off of the form'svalues, and that
moving the map's markers manually changes the form's value. This will allow you to set the position manually via the fields, or by dragging and dropping the marker.

mapStateToProps in the is the important piece here. redux-form automatically stores the values in the state for us, this is where we retrieve it.
Notice these lines at the top of the file:

import { change, formValueSelector } from "redux-form";
...
const formSelector = formValueSelector("form");

This sets up our form selector. "form" being the identifier for the form. Now, to retrieve these values from our state, we do:

const mapStateToProps = (state) => ({
   position: {
     lat: formSelector(state, 'lat'),
     lng: formSelector(state, 'lng') // The key here is the name you
passed into the field.
  }
});

Then we use connect to actually connect the component to the store:

connect(mapStateToProps)(MyMapComponent);

Redux does its magic and now our fields are available via this.props.position in our component! Hope this tutorial was helpful.

Thanks to Praveen Kumar for being our guest writer this week.

Who Are Ronald James?

We are a leading niche digital & tech recruitment specialist for the North East of England. We Specialise in the acquisition of high-performing technology talent across a variety of IT sectors including Digital & Technology Software Development.

Our ultimate goal is to make a positive impact on every client and candidate we serve - from the initial call and introduction, right up to the final delivery, we want our clients and candidates to feel they have had a beneficial and productive experience.

Contact our Team

If you’re looking to start your journey in sourcing talent or find your dream job, you’ll need a passionate, motivated team of experts to guide you. Check out our Jobs page for open vacancies. If interested, contact us or call 0191 620 0123 for a quick chat with our team.

Let's be Friends!

Follow us on our blog, FacebookLinkedInTwitter or Instagram to follow industry news, events, success stories and new blogs releases.

 

Back to Blog

</Follow Us>