Cursor jumps out of text field on a custom text field ! how to fix this? [Material-UI/TextField]

Viewed 528

Guys I was using the Material-UI text-field and made some custom theme options by by making it as a custom component .

Like Below :-

const CustomTextField = ({props}) =>{
return (
  <TexField
   label={props.label}
   name={props.label}
   value={props.row[props.label]}
   onChange={(e)=>props.handleChangeFunction(e)}
   />
 )
}

In My Component I inject like below :-

const App = () =>{
    const [value,setValue] = useState('');
//Some methods here
   const handleChange = () =>{
   //Logic here.......
   }

 return(
   <>
    <CustomTextField {...{label:'name',row:emp,handleChangeFun:handleChange}}/> //Custom Comps...
   </>
 ) 
}

So What happens on each input my component renders and the cursor jumps out off the text field so for the next value to input I have to click the text field again.

But when I use the normal text field , directly in the component it works fine , I understand it is because of the onChange Event and using text field in a custom component .

On each value change the parent compoenent re-renders .

So what will be the solution can anyone give me a solution ?

1 Answers

I'm not sure about your way of passing props. This should work:

const CustomTextField = (props) => {
  return (
    <TextField
      label={props.label}
      name={props.label}
      value={props.value}
      onChange={props.onChange}
    />
  );
};

export default function App() {
  const [value, setValue] = useState("");

  const handleChange = (e) => {
    setValue(e.target.value);
  };

  return (
    <>
      <CustomTextField label="name" value={value} onChange={handleChange} />
    </>
  );
}

Optionally you can create your component like this, without grouping props:

const CustomTextField = ({label, value, onChange}) => {
  return <TextField label={label} name={label} value={value} onChange={onChange}/>
};
Related