onChange event is not being triggered in react js

Trying to make the onChange event of the following componenet to fire but it does not. When I type in the seach box nothing is printed on the console. No change is fired



const Search = () => {
    let history = useHistory()
    const [search, setSearch] = useState('')

    const handleSubmit = (e) => {
        e.preventDefault()
        if (search) {
            console.log("typing..")
            history.push(`/?search=${search}`)
        } else {
            history.push(history.push(history.location.pathname))
        }
    }
    return (
        <Form.Group controlId='searchbox' onSubmit={handleSubmit}>
            <Form.Control
                className="auth-input" 
                type='text'
                placeholder="Search..."
                onChange={(e) => setSearch(e.target.value)}
            >
            </Form.Control>
            <Button type='submit'>Submit</Button>
        </Form.Group>

    )
}
export default Search
const Home =()=>{
    return (<div><Search /><div>)
}

export default Home I still can't identify where the error is. How do I get it working?


Solution 1:

I am assuming Form.Control is a custom control or a third-party control, hence you cannot convert it to a controlled input. You could try creating a ref and get the value from the ref in the onChange event handler. If the custom control is not a third party control, then you could add the onChange handler inside the Form.Control component and pass a function reference to the control.

Edit:

Here is your solution : https://codesandbox.io/s/vigorous-mclean-4jusl?file=/src/App.js

In case you see an error in the sandbox, refresh the page. There seems to be some error with codesandbox.

Explanation:

Create a ref to access the input using useRef:

const controlref = useRef();

Pass the ref to the control:

<Form.Control
  onChange={handleChange}
  **ref={controlref}**
  type="text"
  placeholder="search..."
/>

Get the value in onChange using the ref:

  const handleChange = (e) => {
    console.log(controlref.current.value);
    setSearch(controlref.current.value);
  };

Solution 2:

Firstly, html "input" is a self closing element.

Secondly, You have missed the "value" inside the Input component.

Your code:

<Form.Control
    className="auth-input" 
    type='text'
    placeholder="Search..."
    onChange={(e) => setSearch(e.target.value)}
></Form.Control>

Solution:

<Form.Control
    className="auth-input" 
    type='text'
    placeholder="Search..."
    onChange={(e) => setSearch(e.target.value)}
    value={search}
/>