I'm trying to make a generic Input component with a clear button but I'm having trouble with clearing the state from within the component itself when the parent is holding the state.
Setting the ref value to '' doesn't trigger the onChange event.
Don't know how to call props.onChange in the Input component since I'm using typescript in my project and onChange expects event type.
Here is a recreation of my problem https://codesandbox.io/s/vigilant-voice-rwy2ms?file=/src/App.js
Type something in the input field. Press Clear. The input field sets to empty but the state in parent is not reset.
CodePudding user response:
Look at this sandbox. I wouldn't recommend using useRef
for this. Instead, pass the value and setter both down to the Input
component. Then, the clear button can set the value to and empty string.
Input.js
const Input = (props) => {
const handleChange = (e) => {
props.setText(e.target.value);
};
return (
<div>
<input value={props.text} onChange={handleChange} />
<button onClick={() => props.setText("")}>Clear</button>
</div>
);
};
export default Input;
App.js
import { useState } from "react";
import Input from "./Input";
import "./styles.css";
export default function App() {
const [text, setText] = useState("");
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Input text={text} setText={setText} />
<p>The current state is: {text}</p>
</div>
);
}
CodePudding user response:
The onChange props callback can be used to clear both,
import { useRef } from "react";
const Input = (props) => {
const ref = useRef(null);
const handleClear = (e) => {
props.onChange(e);
}
return (
<div>
<input ref={ref} {...props} />
<button
onClick={handleClear}
>
Clear
</button>
</div>
);
};
export default Input;
CodePudding user response:
Assuming you want your button to revert the text
state back to an empty string, you'll want the onClick trigger to call the setText()
function
<button type='button' onClick={() => setText('')}>Clear</button>
CodePudding user response:
You are just clearing the value of input in that component which will not affect the state in parent component.