user10355996
user10355996

Reputation: 11

React: How to update an input box text when click a button?

In React, suppose have an input box in container1 and a button in container2. If type in the input box, need show the user's inputs. Currently, Container1\input box: has a local state to track its inputs Container2\button: string "Click Me" is saved in Redux store

Need implement: If click the button, show "Click Me" in the input box. How to implement this in React/Redux?

Upvotes: 0

Views: 929

Answers (1)

Drew Reese
Drew Reese

Reputation: 202608

Use some component state. The input is a controlled input with value set from state and updates state on onChange, and the button updates state on onClick.

I don't quite understand the latter half of your question though. The input doesn't need to know/understand what a button is or if it was clicked, and the button doesn't need to know it's updating a value of an input. They are completely independent of each other and the state of the component is the only thing that "links" them.

export default function App() {
  const [value, setValue] = useState('');
  return (
    <div className="App">
      <input type='text' value={value} onChange={e => setValue(e.target.value)} />
      <button type="button" onClick={() => setValue('Click Me')}>Click Me</button>
    </div>
  );
}

Edit boring-lovelace-t9yck

Upvotes: 2

Related Questions