Los Morales Los Morales - 1 year ago 84
React JSX Question

React way to "setState" in a pure ES2015 function

React newb here. I have a pure function that returns a form (presentation component). In this form I need to handle onChange events for those text fields that are controlled. FWIU, I need to this.setState(...) in my onChange event handlers. However due to this being a pure function, I don't have access to this.setState(). Is there a nice way to set the state on these onChange events in a ES2015 function? I'm also using redux if this helps. Example code:

import React, {PropTypes} from 'react'

const ApplicationForm = ({submitHandler, person}) => (
<form onSubmit={e => submitHandler(e)}>
<label htmlFor="firstName">First Name:</label>
<input type="text" name="firstName" onChange={e => setState(e.target.value)} value={person.firstName || ''}/>

Answer Source

That is a Stateless Function, there is no state to set

If you're using redux, you probably want to trigger a redux action in the onChange, passing the new value as an argument, and have the action update the value of firstName in the redux store for person.firstName

I would recommend taking a look at redux-form to reduce a bunch of boilerplate

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download