I'm triyng to remove an object property using spread syntax rendering a React component. I wonder if there is a way to achieve without adding to much extra code. I'm using {reset,...inputName}
I have a custom hook (useField) for every input in my form. useField also has a reset function for my reset button. But I want to remove the reset property only for the inputs element.
custom hook useField
export const useField = (type) => {
const [value, setValue] = useState('')
const onChange = (event) => {
setValue(event.target.value)
}
const reset = () => {
setValue('')
}
return {
type,
value,
onChange,
reset
}
}
react form
const MyForm = (props) => {
const content = useField('text')
const author = useField('text')
const info = useField('text')
const handleClick = () => {
content.reset()
author.reset()
info.reset()
}
return (
<div>
<h2>create a new anecdote</h2>
<form onSubmit={handleSubmit}>
<div>
content
<input {reset,...content} />
</div>
<div>
author
<input {reset,...author} />
</div>
<div>
url for more info
<input {reset,...info} />
</div>
<button>create</button>
<input type="reset" value='reset' onClick={handleClick} />
</form>
</div>
)
}
const obj = {'a': 10, 'b': 20, 'c': 30, 'd': 40};and we need to 'remove' prop'a'using...spread - it can be done like this:const {a, ...rest} = obj; const newObj = {...rest};. Now,newObjwill not have the propa. If you replaceconstwithlet, then instead ofnewObj, you can sayobjitself. So, effectively,'a'is removed fromobj.const content = useField('text')toconst {reset: resetContent, ...content} = useField('text'). I am hoping thatresetwill no longer be withincontent. Then, you may useresetContentin yourhandleClickwhile usingcontentfor JSX.