Home > Software engineering >  React input onChange not rerendering state when useState has default value
React input onChange not rerendering state when useState has default value

Time:07-03

So this is working, input changes when I type.

const [editfield, setEdit_field] = React.useState();

    function updateField(event) {
        setEdit_field(event.target.value);
    }

    function editPost() {
        setPostbody(<div><input onChange={updateField} value={editfield}></input></div>)
    }

But when a put a default value in the useState it doesnt work anymore

const [editfield, setEdit_field] = React.useState(post.body);

    function updateField(event) {
        setEdit_field(event.target.value);
    }

    function editPost() {
        setPostbody(<div><input onChange={updateField} value={editfield}></input></div>)
    }

Access code here: https://codesandbox.io/s/brt7ok

CodePudding user response:

You were setting JSX inside the state, that might be the issue, I have created a codesandbox demo which will help you in conditional Rendering DEMO

CodePudding user response:

You are rendering that function so when state will updated it re-run that function and resetting the value.

You can use below approach. Take one state which represents the field is editable or not. And add condition with input component that it should only render when field is editable.

For example,

const [isEditable, setIsEditable] = useState(false);

<button onClick={() => setIsEditable(!isEditable)}>edit</button>

isEditable && (
    <div>
        <input onChange={updateField} value={editfield} />    
    </div>
)

For more idea, just put console before return. You will get idea.

Hope this helps :)

CodePudding user response:

import React, { useState } from "react";

export default function App() {
let body = "hello";

const [editfield, setEditfield] = useState(body);
const [visible, setVisible] = useState(false);

function updateField(event) {
setEditfield(event.target.value);
}

function editPost() {
 setVisible(true);
}
return (
 <div>
  <div>{visible?<div>
    <input onChange={updateField} value={editfield}/>
  </div>:body}</div>
  <div>
    <button onClick={editPost}>edit</button>
  </div>
 </div>
);
}
  • Related