Search code examples
reactjsobjectinputonchange

making pre-populated text inputs editable


I have a component that has text input fields that are pre-populated. I want to make these pre-populated text input fields editable, to be able to set/control a const object called smurfEdit through an onChange handler. I tried to accomplish this with the code readonly="false. However, this did not work. The text that I've pre-populated the input field with still won't let me edit it. Can someone help me resolve this issue?

Here is the code for the input fields in question:

<input value={smurfEdit.name} onChange={handleChanges} readonly="false" />
<input value={smurfEdit.age} onChange={handleChanges} readonly="false" />
<input value={smurfEdit.height} onChange={handleChanges} readonly="false" />

Here is the code for the entire component:

import React, { useState } from "react";
import { connect } from "react-redux";

import { deleteSmurf } from "../actions/actions";

const Smurf = props => {
    const [editMode, setEditMode] = useState(false);
    const [smurfEdit, setSmurfEdit] = useState({
        name: props.smurf.name,
        age: props.smurf.age,
        height: props.smurf.height
    })

    const toggleEditMode = e => {
        e.preventDefault();
        setEditMode(!editMode);
    }

    const handleChanges = e => setSmurfEdit({
        ...smurfEdit,
        [e.target.name]: e.target.value
    })

    return (
        <div className="smurfs">
            {/* section renders smurf name, age and height */}
            <section>
                <h3>{props.smurf.name}</h3>
                <p>age: {props.smurf.age}</p>
                <p>height: {props.smurf.height}</p>
            </section>

            {editMode && 
            <div>
                <input value={smurfEdit.name} onChange={handleChanges} readonly="false" />
                <input value={smurfEdit.age} onChange={handleChanges} readonly="false" />
                <input value={smurfEdit.height} onChange={handleChanges} readonly="false" />
            </div>
            }


            <button onClick={e => props.deleteSmurf(e, props.smurf.id)}>X</button>
            <button onClick={toggleEditMode}>Edit</button>
        </div>
    )
}


export default connect(null, { deleteSmurf })(Smurf);

Solution

  • You are using e.target.name and not even providing name attribute to input.