I have a form with a single input which is query for the search url -
<form className={styles.searchInputContainer} role="search" action="/search">
<label htmlFor={id} className={styles.searchLabel}>{constants.search}</label>
<input id={id} className={styles.searchInput} type="search" name="q" placeholder="Search..." autocomplete="off" />
</form>
At the moment, when I hit enter, the url will end with '/search?q=whatever_the_input_is'
I am currently doing logic elsewhere in the file to check if the search bar is on a particular page. With this boolean value (isShoppingPage
), I want to optionally append a 'type=shop' to the url when the user hits enter so it automatically only searches through the shop categories. I've tried appending 'type=shop' to the input value but then the url ends up having URL encoding. I'm confused as to how to conditionally add this without changing the name="q"
which the input currently has and needs.
CodePudding user response:
Instead of action
you can use onSubmit
prop of the form
.
import React, {useState} from 'react';
const Form = (props) => {
const {styles, id, constants} = props;
const [qValue, setQValue] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
// here you can make API call with q=qValue and type=shop
};
return (
<form className={styles.searchInputContainer} role="search" onSubmit={handleSubmit}>
<label htmlFor={id} className={styles.searchLabel}>{constants.search}</label>
<input id={id} className={styles.searchInput} type="search" name="q" placeholder="Search..." autocomplete="off" value={qValue} onChange={e => setQValue(e.target.value)} />
</form>
)
};
This is guide from react docs