T
T
TheSnegok2021-08-24 15:23:09
React
TheSnegok, 2021-08-24 15:23:09

How to call useState in child component and change state from above?

I need that when clicking on a letter, it is added to the value in the input in the component above:
base:

function App() {
  const [value, setValue] = useState('');
  return (
    <div className="App">
      <main>
        <div className="gliph">
          <div className="gliphArea">
            <h1>Gliphs</h1>
            <input className="inputLine" value={value} readOnly />
            <div className="gliphAlphabet">
              <Gliph value={value} set={() => setValue()} />
            </div>
          </div>
        </div>
      </main>
      <div className="history">
        <input type="text" className="inputLine" readOnly />
      </div>
    </div>
  );
}

Child component:
const alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

const Gliph = ({ value, set }) => {
    const handleClick = (letter) => {
        set(value + letter);
    }
    return (
        <>
            {alphabet.map(l => <div key={l} className="gliphMine" onClick={() => handleClick(l)}>{l}</div>)}
        </>
    )
}

Error code:
A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.
When does he become out of control?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor Zhivagin, 2021-08-24
@TheSnegok

Replace with
set={() => setValue()}
With
set={setValue}
Otherwise, you always call the setValue function without arguments
And in general, try not to make anonymous functions when passing props, this is a blow to optimization

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question