'React rsuite reset select box value
I have rsuite SelectBox, I want to reset its value from outside. when I set it to null or undefined or empty string, it doesnt work.
I read the source code, I get the felling that it is by design, only when you use it as part of a form. but this complicate things.
Do you see any possible way to reset the combo value without creating a form?
https://codesandbox.io/s/select-picker-types-forked-ivjn8?file=/src/App.tsx:164-477
export default function App() {
const [value, setValue] = useState<string | undefined>();
return (
<>
<SelectPicker
data={[{ label: "test", value: "test" }]}
value={value}
onChange={setValue}
/>
<button onClick={() => setValue("")}>reset</button>
</>
);
}
Thanks
Solution 1:[1]
You can use the defaultValue prop to set the initial value of the SelectPicker.
<SelectPicker
data={[{ label: "test", value: "test" }]}
defaultValue={value}
onChange={setValue}
/>
However in my experience this will not update if defaultValue is changed externally. For that you will need to do as the other answer by MWO suggests and force the component to remount.
You can do this quite simply by just changing the key prop which forces React to create a new component instance. Set the key prop to your value and it will remount when it changes.
<SelectPicker
key={value}
data={[{ label: "test", value: "test" }]}
defaultValue={value}
onChange={setValue}
/>
Solution 2:[2]
I know it's not so sweet and I have no idea what props this one takes, but you could unmount/mount it completely on button click.
import { useState, useEffect } from "react";
import { SelectPicker, Button } from "rsuite";
import "./styles.css";
import "rsuite/dist/styles/rsuite-default.css";
export default function App() {
const [value, setValue] = useState<string | undefined>("");
const [down, setDown] = useState(false);
useEffect(() => {
setValue("");
console.log(down);
}, [down]);
return (
<>
{!down ? (
<SelectPicker
data={[{ label: "test", value: "test" }]}
value={value}
onChange={setValue}
/>
) : (
<SelectPicker value={""} />
)}
<br />
<br />
<button
onMouseUp={() => setDown(false)}
onMouseDown={() => setDown(true)}
>
reset
</button>
</>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | j0hnSta |
| Solution 2 |
