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
You can dispatch an action that accepts the input value when the submit button is pressed. You can then perform the required actions on the captured value in your redux reducer. Dispatch an action from your component. The above snippets are basic structural examples of how you can accomplish this task.
Solution: Writing an input with React hooksuseInput() will accept an argument called opts , which will allow the developer to pass other input type of properties. Inside useInput() I will create a state hook that will contain the value of the input element and it will be updated onChange event listener .
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>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With