From ce716a6ccc70ce04e970eb2a8af3808ec2f34d8b Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Wed, 21 Aug 2019 13:09:10 +0300 Subject: [PATCH] Add ControlledInput component Showcases both useState and useEffect very nicely --- snippets/ControlledInput.md | 50 +++++++++++++++++++ .../{ClickInside.md => useClickInside.md} | 2 +- .../{ClickOutside.md => useClickOutside.md} | 2 +- 3 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 snippets/ControlledInput.md rename snippets/{ClickInside.md => useClickInside.md} (98%) rename snippets/{ClickOutside.md => useClickOutside.md} (98%) diff --git a/snippets/ControlledInput.md b/snippets/ControlledInput.md new file mode 100644 index 000000000..5e33c7ac0 --- /dev/null +++ b/snippets/ControlledInput.md @@ -0,0 +1,50 @@ +--- +title: ControlledInput +tags: input,state,effect,intermediate +--- + +Renders an `` 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 `` 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 `` 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 ( + setValue(value)} + /> + ); +} +``` + +```jsx +ReactDOM.render( + console.log(val)} + />, + document.getElementById('root') +); +``` diff --git a/snippets/ClickInside.md b/snippets/useClickInside.md similarity index 98% rename from snippets/ClickInside.md rename to snippets/useClickInside.md index dd39454b9..06ce7cb7c 100644 --- a/snippets/ClickInside.md +++ b/snippets/useClickInside.md @@ -1,5 +1,5 @@ --- -title: ClickInside +title: useClickInside tags: hooks,effect,event,intermediate --- diff --git a/snippets/ClickOutside.md b/snippets/useClickOutside.md similarity index 98% rename from snippets/ClickOutside.md rename to snippets/useClickOutside.md index 05b5bc65e..c807a3f17 100644 --- a/snippets/ClickOutside.md +++ b/snippets/useClickOutside.md @@ -1,5 +1,5 @@ --- -title: ClickOutside +title: useClickOutside tags: hooks,effect,event,intermediate ---