I'm creating a component that contains an input that directs the user to a new tab upon pressing enter or clicking the search button. The search button functions correctly, however I'm having trouble getting the input to call the handleSubmit method on enter key press. As of now, pressing the enter key does nothing. How can I achieve this? code:
const LinkCard = (props) => {
const [searchInput, setSearchInput] = useState("");
const handleChange = (e) => {
setSearchInput(e.target.value);
};
const handleClick = (e) => {
e.preventDefault();
location.assign("http://www.mozilla.org");
};
const handleSubmit = (e) => {
e.preventDefault();
location.assign("http://www.mozilla.org");
};
return (
<Flex borderWidth="1px" borderRadius="lg" alignItems="center">
{props.icon}
<Box>{props.websiteName}</Box>
<InputGroup>
<Input
placeholder={"Search " + props.websiteName}
onChange={handleChange}
onSubmit={handleSubmit}
flexGrow="1"
m="2%"
/>
<Link href={props.url} passHref={true}>
<a>
<InputRightElement m="2%">
<Button onClick={handleClick}>
<FaSearch />
</Button>
</InputRightElement>
</a>
</Link>
</InputGroup>
</Flex>
);
};
const [value, setValue] = React.useState('');
return (
<form
onSubmit={e=> {
e.preventDefault();
location.assign('?wd=' + value)
}}>
<input value={value} onChange={(e)=> setValue(e.currentTarget.value)} />
<button type="submit">Search</button>
</form>
)
or
const [value, setValue] = React.useState('');
return (
<>
<input
value={value}
onChange={(e)=> setValue(e.currentTarget.value)}
onKeyPress={e=> {
if (e.key === 'Enter') {
location.assign('?wd=' + value)
}
}}
/>
<button onClick={()=> location.assign('?wd=' + value)}>Search</button>
</>
);
There are 2 possible ways you can achieve that:
submitHandler:const handleSubmit = e => {
e.preventDefault();
if (e.key === "Enter") {
location.assign("http://www.mozilla.org");
}
};
form around your input and add submit an event:<form onSubmit={handleSubmit}>
<Input
placeholder={"Search " + props.websiteName}
onChange={handleChange}
onSubmit={handleSubmit}
flexGrow="1"
m="2%"
/>
</form>;