Let me start off by saying that I am brand new to React, with that I was given a problem to solve which consists of clearing the inputs from multiple input fields that are contained in a separate text input component. My path toward a possible solution has been attempting to set the values of said input fields to an empty string using an onClick event in the App.js component. So far I have been able to clear the text field that stores the user inputs, however I cannot seem to figure out how to also clear the input fields as well. Thanks in advance to those taking time to lend their knowledge.
Here is the App.js code:
import { useEffect, useRef, useState } from 'react';
import './App.css';
import LabeledTextInput from './components/LabeledTextInput';
function App() {
const data = useRef(document.getElementById('FIELD_555'));
const [ state, setState ] = useState({});
const handleUpdate = (key, value) => {
setState(prevState => ({
...prevState,
[key]: value
}));
};
useEffect(() => {
data.current.value = JSON.stringify(state);
}, [state]);
return (
<div>
<LabeledTextInput label='Name' handleUpdate={handleUpdate} />
<LabeledTextInput label='Title' handleUpdate={handleUpdate} />
<LabeledTextInput label='Company' handleUpdate={handleUpdate} />
<button onClick={() => setState('')}>Clear Inputs</button>
</div>
);
}
export default App;
And then the LabeledTextInput.js component:
import { useState } from 'react';
const LabeledTextInput = ({ label, handleUpdate }) => {
const [ state, setState ] = useState('');
return (
<div>
<label>{label}</label>
<input
type='text'
name={label.toLowerCase()}
value={state}
onChange={e => setState(e.target.value)}
onBlur={e => handleUpdate(e.target.name, e.target.value)} />
</div>
);
};
export default LabeledTextInput;