Update default value in React component

3.2k Views Asked by At

I would like to set a default value on an Input from a value stored in redux.

I saw in this post that defaultValue is only for first rendering.

So I tried to use instead value then the problem is that I'm not getting able to change it's value.

import React, { useState } from "react";
import { Input } from "@fluentui/react-northstar";
const InputExample = () => {
  const [value, setValue] = useState("");
  const getText = () => {
    return setTimeout(() => setValue("blablabla"), 3000);
  };
  getText();

  return (
    <>
      <Input value={value} />
      <br />
      <br />
      <Input defaultValue={value} />
    </>
  );
};

export default InputExample;

Here's an example

1

There are 1 best solutions below

1
On

you need to add an onChange handler to handle changes made to the input

import React, { useState } from "react";
import { Input } from "@fluentui/react-northstar";

const InputExample = () => {
  const [value, setValue] = useState("");
  const getText = () => {
    return setTimeout(() => setValue("blablabla"), 3000);
  };
  getText();

  const handleChange = event => {
    setValue(event.target.value)
}

  return (
    <>
      <Input value={value} onChange={handleChange} />
      <br />
      <br />
      <Input defaultValue={value} />
    </>
  );
};

export default InputExample;