Home > OS >  React Js input is losing focus when I try typing in it but only when onChange is added
React Js input is losing focus when I try typing in it but only when onChange is added

Time:09-21

The problem I am facing is really annoying, when I try to edit the default value of my input text, the input field won't type my changes or it would lose focus only after typing the first character and it will return to it's default value. But please note that this only happens when I add the onChange event. If I remove it, the input works normally. What is happening

const AddMaker = () => {

    const [make, setMake] = useState();

    function ConditionalTableRow(props) {
        let { item, index  } = props;

        if ( index === editModeIndex)
            return (<TableRowWithSave item={item} index={index} />)
        else
            return (<TableRowWithEdit item={item} index={index} />)

    }

    function TableRowWithSave(props) {
        let { item } = props;
        return (
            <TableRow>
                <TableCell>
                    <input type="text"  defaultValue={item.make} onChange={e => setMake(e.target.value)} />
                </TableCell>

                <TableCell>
                    <button className="palletSaveButton" onClick={handleSaveClick}> Save </button>
                </TableCell>
            </TableRow>
        )
    }
    
    return (
        <TableBody>
        {
            records.map((item, index) => (
                <ConditionalTableRow key={index} item={item} index={index} />
            ))
        }
        </TableBody>
    );
}

CodePudding user response:

Try adding a value attribute to the input element.

<input type="text" value={make}  defaultValue={item.make} onChange={e => setMake(e.target.value)} />

CodePudding user response:

Move useState to TableRowWithSave and use value instead of defaultValue

function ConditionalTableRow(props) {
        let { item, index  } = props;
        if ( index === editModeIndex)
            return (<TableRowWithSave item={item} index={index} />)
        else
            return (<TableRowWithEdit item={item} index={index} />)
}

function TableRowWithSave(props) {
    let { item } = props;
    const [make, setMake] = useState(item.make);
    return (
        <TableRow>
            <TableCell>
                <input type="text" value={make} onChange={e => setMake(e.target.value)} />
            </TableCell>
            <TableCell>
                <button className="palletSaveButton" onClick={handleSaveClick}> Save </button>
            </TableCell>
        </TableRow>
    )
}

const AddMaker = () => {
    return (
        <TableBody>
        {
            records.map((item, index) => (
                <ConditionalTableRow key={index} item={item} index={index} />
            ))
        }
        </TableBody>
    );
}

EDIT: Also it's better to move ConditionalTableRow and TableRowWithSave outside AddMaker

  • Related