user2029958 user2029958 -4 years ago 180
Javascript Question

React/Redux, how to get user input

i am following the usage with React Redux tutorial. Something I really don't get is how to retrieve user input.

They build a FilterLink container, whose mapDispatchToProps is

const mapDispatchToProps = (dispatch, ownProps) => {
return {
onClick: () => {
dispatch(setVisibilityFilter(ownProps.filter))
}
}
}


So it injects its ownProps.filter to the connected presentational component. If we go and see how this container is construced

const Footer = () => (
<p>
Show:{" "}
<FilterLink filter="SHOW_ALL">All</FilterLink>{", "}
<FilterLink filter="SHOW_ACTIVE">Active</FilterLink>{", "}
<FilterLink filter="SHOW_COMPLETED">Completed</FilterLink>
</p>
)


Ok, there is the "filter" property. That's clear.

Now I want to build a text filter on the same example. So first here is my presentational component

const TodoSearch = ({onSubmit}) => (
<form
onSubmit={e => {
e.preventDefault()
onSubmit()
}}
>
<input placeholder="Text search" />
<input type="submit" value="Go" />
</form>
)


But when I come to write the container I don't know how to get user input

const mapDispatchToProps = (dispatch) => {
return {
onSubmit: () => {
dispatch(setTextSearch(????))
}
}
}


It's something I would do with jQuery $(#text).val() but... is it the best way?

Later on on the same tutorial they build a little form to add a todo to the list. Ok, let's go and see how they catch input then.

let AddTodo = ({ dispatch }) => {
let input

return (
<div>
<form onSubmit={e => {
e.preventDefault()
if (!input.value.trim()) {
return
}
dispatch(addTodo(input.value))
input.value = ''
}}>
<input ref={node => {
input = node
}} />
<button type="submit">
Add Todo
</button>
</form>
</div>
)
}


Wait, where's the magic here? Did they inject value into "input" variabile with that ref trick? Is that correct?
So if there were 20 input fields, have I to use 20 variables with 20 different refs?

Any help is appreciate, thank you

Answer Source

Change your submit function to the following.

const mapDispatchToProps = (dispatch) => {
    return {
        onSubmit: (evt) => {
            dispatch(setTextSearch(evt.target.querySelector('input').value)
        }
    }
}

Also,

const TodoSearch = ({onSubmit}) => (
    <form
        onSubmit={e => {
            e.preventDefault()
            onSubmit(e)
        }}
    >
        <input placeholder="Text search" />
        <input type="submit" value="Go" />
    </form>
)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download