I’m a newbie to react and I’m trying to route on a different set of components after a form (in my case a search bar) has been submitted (using onSubmit event). I have my search component wrapped in withRouter and have the history deconstructed. I’ve tried using onClick and the push does trigger, but does not seem to do anything with onSubmit. Hoping for your advise.
Thank you
Search component
const SearchAppBar = (props) => {
const {
history,
onPlatformDrop,
onPlatformChange,
onPriceRangeDrop,
clearPriceRange,
searchQuery,
setSearchQuery,
clearGenre,
onDropDownChange,
} = props;
return (
<Box sx={{ flexGrow: 1 }}>
<Search
sx={{
width: { xs: "85vw", md: "50vw", lg: "30vw" },
margin: "auto",
marginBottom: "20px",
}}
>
<form action="/" method="get" style={{ display: "flex" }}>
<StyledInputBase
defaultValue={searchQuery}
autoComplete="off"
placeholder="Search All Games…"
inputProps={{ "aria-label": "search" }}
type="search"
name="s"
id="site-search"
/>
<SearchIconWrapper>
<IconButton
type="submit"
onSubmit={(e) => {
history.push("/find");
clearGenre();
clearPriceRange();
onPlatformChange("");
onPlatformDrop("All Platforms");
onPriceRangeDrop("All Price Range");
onDropDownChange("All Genres");
setSearchQuery(e.target.value);
}}
>
<SearchIcon style={{ color: "#55597d" }} />
</IconButton>
</SearchIconWrapper>
</form>
</Search>
</Box>
);
};
export default withRouter(SearchAppBar);
Then on my App, i have something like this:
<Route
path="/find"
exact
render={(props) => (
<div>
<Search
onPlatformChange={onPlatformChange}
onPlatformDrop={onPlatformDrop}
clearPriceRange={clearPriceRange}
onPriceRangeDrop={onPriceRangeDrop}
searchQuery={searchQuery}
setSearchQuery={setSearchQuery}
clearGenre={clearGenre}
onDropDownChange={onDropDownChange}
/>
</div>
)}
/>;
>Solution :
The onSubmit
handler should be on the form
element, not the button submitting the form. Remove the form action and method. You will also need to prevent the default form action from occurring, if you don’t then the form is submitted and the page reloads.
<form
style={{ display: "flex" }}
onSubmit={(e) => { // handles form submission
e.preventDefault(); // prevents default form action
history.push("/find"); // navigate
...
setSearchQuery(e.target.s.value); // <-- access field value
}}
>
<StyledInputBase
...
name="s" // <-- access in submit handler
...
/>
<SearchIconWrapper>
<IconButton type="submit">
<SearchIcon style={{ color: "#55597d" }} />
</IconButton>
</SearchIconWrapper>
</form>