I have a simple search bar and I want to pre-populate it with some data. I've tried using value but it doesn't let the user change the value in the search bar afterward.
<input type="search" class="navBarSearchForm3 form-control rounded searchterm2" placeholder="search term" value={comparelinks}></input>
I'd like the searchbar to already have a value and let the user be able to change it. Do I need some JS for it or can it be done with just HTML?
CodePudding user response:
You are missing the handle of the change. So, you need to edit the value when the user changes something on the input it would be like:
In this case, I'd use React Hooks (useState) to be able to set one default value and being able to change it.
And finally, use that seCompareLinks when user onChange
in the input.
You can see it working here: https://codesandbox.io/s/practical-dewdney-wj7j2?file=/src/App.js:0-543
import React from 'react';
import "./styles.css";
export default function App() {
const [comparelinks, setComparelinks] = React.useState('default value');
const handleChange = (e) => {
setComparelinks(e.target.value);
}
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<input type="search" class="navBarSearchForm3 form-control rounded searchterm2" placeholder="search term" value={comparelinks} onChange={handleChange}></input>
</div>
);
}
CodePudding user response:
You have to handle the update of the input as well, considering you use hooks:
const [comparelinks, setCompareLinks] = useState()
const handleChange = (event) => {
setCompareLinks(event.target.value)
}
<input type="search" class="navBarSearchForm3 form-control rounded searchterm2" placeholder="search term" value={comparelinks} onChange={handleChange}></input>