Skip to content Skip to sidebar Skip to footer

React OnChange Event Will Not Fire On Custom Input

I have a custom input component like so: import * as React from 'react'; const Input = (props) => { return (

Solution 1:

If you are using a custom component like your Input, you have to specify all the props, as you can see you are giving an onChange prop to your Input component without passing it to the input tag.

import * as React from "react";

const Input = (props) => {
  
  return (
    <input
      type={props.type}
      name={props.name}
      className={props.className}
      value={value}
      onChange={props.onChange}
    />
  );
};
export default Input;

Solution 2:

You need to handle your onChange() from your Input component. Otherwise, it won't fire directly.

import * as React from "react";
const Input = (props) => {
  return (
    <input
       type={props.type}
       name={props.name}
       className={props.className}
       value={value}
       onChange={ev => props.onChange}
    />
 );
};
export default Input;

Solution 3:

Please try this. You can give the state for input in parent component and update from child accordingly.

Input.js

import * as React from "react";

const Input = (props) => {
  
  return (
    <input
      type={props.type}
      name={props.name}
      className={props.className}
      value={props.value}
      onChange={e => props.handleInputData(e.target.value)}

    />
  );
};
export default Input;

Second component

import React from 'react'

export default function secondComponent() {
  const [inputData,handleInputData] = useState("");
  return (
    <div>
      <Input
        type="text"
        id="subject"
        className="rounded-sm px-4 py-3 mt-3 focus:outline-none w-full border bg-transparent border- 
          gray-300"
        placeholder="Subject"
        handleInputData={handleInputData}
        value={inputData}
      />
    </div>
  )
}

Solution 4:

in your Input component, you have not used the passed onChange anywhere, that's why it is not firing up

<Input
  .
  .
  .
  onChange={props.onChange}
/>

Also ,one important step, the value should be the state of useEffect as the updater. if you don't do this, the value will not update, and it will be readonly

so, pass props as follows:

const [subject, setSubject] = useState('');

<Input
  .
  .
  value={subject}
  onChange={e => setSubject(e.target.value)}
/>

Solution 5:

Thanks for the suggestions,

React package was out-dated and running an update seems to have fixed my problems!


Post a Comment for "React OnChange Event Will Not Fire On Custom Input"