Add ControlledInput component
Showcases both useState and useEffect very nicely
This commit is contained in:
50
snippets/ControlledInput.md
Normal file
50
snippets/ControlledInput.md
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
---
|
||||||
|
title: ControlledInput
|
||||||
|
tags: input,state,effect,intermediate
|
||||||
|
---
|
||||||
|
|
||||||
|
Renders an `<input>` element with internal state, that uses a callback function to pass its value to the parent component.
|
||||||
|
|
||||||
|
- Use object destructuring to set defaults for certain attributes of the `<input>` element.
|
||||||
|
- Use the `React.setState()` hook to create the `value` state variable and give it a value of equal to the `defaultValue` prop.
|
||||||
|
- Use the `React.useEffect()` hook with a second parameter set to the `value` state variable to call the `callback` function every time `value` is updated.
|
||||||
|
- Render an `<input>` element with the appropriate attributes and use the the `onChange` event to upda the `value` state variable.
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
function ControlledInput({
|
||||||
|
callback,
|
||||||
|
type = 'text',
|
||||||
|
disabled = false,
|
||||||
|
readOnly = false,
|
||||||
|
defaultValue,
|
||||||
|
placeholder = ''
|
||||||
|
}) {
|
||||||
|
const [value, setValue] = React.useState(defaultValue);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
callback(value);
|
||||||
|
}, [value]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
defaultValue={defaultValue}
|
||||||
|
type={type}
|
||||||
|
disabled={disabled}
|
||||||
|
readOnly={readOnly}
|
||||||
|
placeholder={placeholder}
|
||||||
|
onChange={({ target: { value } }) => setValue(value)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
ReactDOM.render(
|
||||||
|
<ControlledInput
|
||||||
|
type="text"
|
||||||
|
placeholder="Insert some text here..."
|
||||||
|
callback={val => console.log(val)}
|
||||||
|
/>,
|
||||||
|
document.getElementById('root')
|
||||||
|
);
|
||||||
|
```
|
||||||
@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
title: ClickInside
|
title: useClickInside
|
||||||
tags: hooks,effect,event,intermediate
|
tags: hooks,effect,event,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
title: ClickOutside
|
title: useClickOutside
|
||||||
tags: hooks,effect,event,intermediate
|
tags: hooks,effect,event,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Reference in New Issue
Block a user