Skip to main content

Controlled Components

Controlled components allows React to manage component state for you via props or state solutions like Redux or Flux. PCR exposes state hooks for convenience, but you're welcome to use different tools as well.

Hooks#

To greatly simplify state-based components, PCR exports two hooks for use:

  • useCheckboxState
  • useRadioState

Both hooks have standard options:

NameDescription
stateThe state object of the control
onChangeYour custom callback to call

Both hooks return a standard interface:

NameDescription
stateThe state object of the control
setStateThe React dispatch function
onChangeThe change handler to be called by the input control when a change event fires. This calls setState for you

Confused? Don't be! Hooks are just functions that return stuff we'll spread to the PCR component. Like this!

Live Editor
Result
SyntaxError: Unexpected token (1:8)
1 : return ()
            ^

Say whhaaatttt?! ๐Ÿคฏ If it seems too good to be true, it's not ๐Ÿ˜‰. It really is that easy.

Customizing onChange#

Using the PCR hooks you sacrifice some control the hook, but you are free to pass in your own change handler. This will be called after the hook's onChange handler has executed.

Live Editor
Result
SyntaxError: Unexpected token (1:8)
1 : return ()
            ^

Grouping State#

Interrelated controls don't require a new hook for each control. PCR supports state arrays to keep the component footprint tiny! Check it out ๐Ÿ‘

tip

Something acting funky? Make sue you're passing a unique value control on the Checkbox ๐Ÿ™‚

Live Editor
Result
SyntaxError: Unexpected token (1:8)
1 : return ()
            ^

Managing State without Hooks#

Not sold on the PCR's super awesome hooks? That's okay ๐Ÿ˜ข. Because our hooks have a standard interface, this means you can easily mirror that interface using your own state hooks, class component, or something else.

React useState#

note

Passing setState while optional, is recommended since PCR internally handles different types of state. For full control use the checked prop.

Live Editor
Result
SyntaxError: Unexpected token (1:8)
1 : return ()
            ^

Class Components#

Not on the hooks gravy train yet ๐Ÿš‚? No worries. PCR works well with class components too (but remember that React 16.9+ is required).

Live Editor
Result
SyntaxError: Unexpected token (1:8)
1 : return ()
            ^

Using checked#

For ultra fine-grained control you can use the checked prop to completely control the input:

Live Editor
Result
SyntaxError: Unexpected token (1:8)
1 : return ()
            ^