简体   繁体   中英

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?

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 and add onChange event handler using native js. If the custom control is not a third party control then you could add the onChange handler inside the Form.Control componenet 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);
  };

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}
/>

Try using event onInput instead:

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

I can't believe I made this silly mistake. The issue is due to the fact that I omitted the tag and placed the submit button within the <Form.Group> which doesn't have the property to handle onSubmit event. So I changed this

    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>

    )

It was modified to this:

    return (
    <Form onSubmit={handleSubmit} >
        <Form.Group controlId='searchbox' >
            <Form.Control
                className="auth-input" 
                type='text'
                placeholder="Search..."
                onChange={(e) => setSearch(e.target.value)}
            >
            </Form.Control>
            <Button type='submit'>Submit</Button>
        </Form.Group>
    </Form>

    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM