From 66636c3b5ae625b81972d810ff5563b4ac759ea4 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 24 Feb 2018 09:31:28 -0600 Subject: [PATCH] Add Read Only Input Elements as a react til --- README.md | 3 ++- react/read-only-input-elements.md | 31 +++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 react/read-only-input-elements.md diff --git a/README.md b/README.md index 2a7418f..bcf2768 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_625 TILs and counting..._ +_626 TILs and counting..._ --- @@ -440,6 +440,7 @@ _625 TILs and counting..._ - [Passing Props Down To React-Router Route](react/passing-props-down-to-react-router-route.md) - [Proxy To An API Server In Development With CRA](react/proxy-to-an-api-server-in-development-with-cra.md) - [Quickly Search For A Component With React DevTools](react/quickly-search-for-a-component-with-react-devtools.md) +- [Read Only Input Elements](react/read-only-input-elements.md) - [Rendering Multiple Nodes With Fragments](react/rendering-multiple-nodes-with-fragments.md) - [Use A Ref To Autofocus An Input](react/use-a-ref-to-autofocus-an-input.md) - [Visually Select A React Element For Inspection](react/visually-select-a-react-element-for-inspection.md) diff --git a/react/read-only-input-elements.md b/react/read-only-input-elements.md new file mode 100644 index 0000000..d368cb6 --- /dev/null +++ b/react/read-only-input-elements.md @@ -0,0 +1,31 @@ +# Read Only Input Elements + +Here is an input element with a `value` and no `onChange` handler. + +```javascript +const MyInput = ({ value }) => { + return ( + + ); +}; +``` + +React will raise a warning regarding the `input` element because it has a +`value` without an `onChange` handler leaving React to wonder if it is +intended to be a _controlled_ or _uncontrolled_ component. + +If our intention is to have the `value` set but not allow the user to +directly change it, we just need to let React know that. + +```javascript +const MyInput = ({ value }) => { + return ( + + ); +}; +``` + +The `readOnly` prop means we don't intend for the input to be modified by +user input. The React warning will now go away. + +h/t Dillon Hafer