-1

I'm trying to edit an input value in a child component and send to the parent : https://codesandbox.io/s/sleepy-rain-skoss?file=/src/Editlabel.js:0-389

Parent:

import "./styles.css";
import EditLabel from "./Editlabel";
import { useEffect, useState } from "react";

export default function App() {
  const [newName, setNewName] = useState();

  useEffect(() => {
    console.log("newName", newName);
  }, [newName]);

  return (
    <div className="App">
      <EditLabel
        value={"hello"}
        click={(changedName) => {
          setNewName(changedName);
        }}
      />
    </div>
  );
}

Child:

import React, { useState } from "react";

const EditLabel = ({ value, click }) => {
  const [name, setName] = useState(value);

  return (
    <>
      <input type={"text"} placeholder={name}></input>
      <button
        onClick={(e) => {
          setName(e.target.value);
          click(name);
        }}
      >
        Edit
      </button>
    </>
  );
};

export default EditLabel;

However, the console logs "hello" and then it just logs empty strings. How can I make it work?

João Pedro
  • 794
  • 2
  • 12
  • 28

2 Answers2

1

Change EditLabel to use a ref to capture the input value:

const EditLabel = ({ value, click }) => {
  const inputRef = useRef(null);
  return (
    <>
      <input ref={inputRef} type={"text"} placeholder={value}></input>
      <button
        onClick={() => {
          click(inputRef.current.value);
        }}
      >
        Edit
      </button>
    </>
  );
};

Update App to use the values it gets via the click callback:

export default function App() {
  const [newName, setNewName] = useState("hello");

  useEffect(() => {
    console.log("newName", newName);
  }, [newName]);

  return (
    <div className="App">
      <EditLabel
        value={newName}
        click={(changedName) => {
          setNewName(changedName);
        }}
      />
    </div>
  );
}

Edit epic-johnson-tewd3

thedude
  • 9,388
  • 1
  • 29
  • 30
1

try this on your child's input box

<input type={"text"} placeholder={name} onChange={(e) => setName(e.target.value)}>
Bhumit 070
  • 416
  • 4
  • 12