Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)}>
 <div>
            <label htmlFor="firstName">First Name:</label>
            <input type="text" name="firstName" onChange={e => setState(e.target.value)} value={person.firstName || ''}/>
 </div>
...
</form>
)
like image 973
Los Morales Avatar asked Aug 16 '16 20:08

Los Morales


1 Answers

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

like image 95
CheapSteaks Avatar answered Sep 30 '22 18:09

CheapSteaks