dipole_moment dipole_moment - 25 days ago 5
React JSX Question

Sending textarea value to a redux action creator

I have the following component:

const myComponent = ({handleClick, default = ''}) => (
<div>
<textarea name="myTextArea" defaultValue={default}></textarea>
<button onClick={(myTextArea) => handleClick(myTextArea})}>Done</button>
</div>
)


Dispatch mapping:

const mapDispatchToProps = (dispatch) => {
return {
handleClick: (myTextArea) => {
console.log(myTextArea); // This is syntheticMouseEvent
}
}
}


myTextArea
is always of type
syntheticMouseEvent


Am I doing something wrong? Where is my value?

Answer

You're getting the event for the button click, which has nothing to do with the text area. There's a couple different ways you can handle things. One is to implement the "controlled inputs" pattern and keep the current value of the text area in state (either Redux state or component state). Another is to save a "ref" to the text area, and retrieve its value from the real DOM element when the button is clicked.

I have links to a number of articles on React and Forms as part of my React/Redux links list, which explain what the "controlled input" pattern is and how you can use it.