joshxfi
joshxfi

Reputation: 312

Remove readOnly on input when button is clicked on React

How do I remove the readOnly when I click the button? I tried setting false to readOnly but does not work.

function Form({ username }) {
    return (
      <div>
        <input type="text" readOnly onInput={e => setValue(e)} value={username}/>
        <button>Edit</button>
      </div>
    )
}

Upvotes: 1

Views: 3898

Answers (2)

You could use the UseRef hook

import React from "react";

export default function Form({ username = "name" }) {
  const input = React.useRef();
  const [value, setValue] = React.useState(username);

  const removeReadOnly = () => {
    input.current.readOnly = false;
  };

  return (
    <div>
      <input
        ref={input}
        type="text"
        readOnly
        onInput={(e) => setValue(e.target.value)}
        value={value}
      />
      <button onClick={removeReadOnly}>Edit</button>
    </div>
  );
}

Keep an eye at the value passed to setValue you need to use e.target.value intead only e.

Upvotes: 0

Sean
Sean

Reputation: 975

When you click the button you can toggle a state that is true or false and set the readOnly attribute to that value.

const [isReadonly, setIsReadonly] = useState(true);
<div>
    <input type="text" readOnly={isReadonly} onInput={e => setValue(e)} value={username}/>
    <button onClick={()=> setIsReadonly(prevState => !prevState)}
</div>

setIsReadonly(prevState => !prevState)} is just taking the current state before clicking and toggling that so we always have the correct current state.

Upvotes: 2

Related Questions