ReasonReact

ReasonReact

  • Docs
  • Try
  • Examples
  • Community
  • Blog
  • Languages icon한국어
    • 日本語
    • English
    • Español
    • Français
    • Português (Brasil)
    • Русский
    • 中文
    • 繁體中文
    • Help Translate
  • GitHub

›Code Snippets

Code Snippets

  • Simple
  • Counter
  • Use State and Use Effect
  • ReasonReact using ReactJS
  • ReactJS using ReasonReact
  • Example Projects
Translate

Use State and Use Effect

Here's a simple example of how to use React's useState with useEffects.

[@react.component]
let make = (~label, ~onSubmit) => {
  let (editing, setEditing) = React.useState(() => false);
  let (value, onChange) = React.useState(() => label);
  let onCancel = _evt => setEditing(_ => false);
  let onFocus = event => ReactEvent.Focus.target(event)##select();

  React.useEffect1(
    () => {
      onChange(_ => label);
      None
    },
    [|label|],
    );

  if (editing) {
    <form
      onSubmit={_ => {
        setEditing(_ => false);
        onSubmit(value);
      }}
      onBlur=onCancel>
      <input
        onBlur=onCancel
        onFocus
        onChange={event => onChange(ReactEvent.Form.target(event)##value)}
        value
      />
    </form>;
  } else {
    <span onDoubleClick={_evt => setEditing(_ => true)}>
      value->React.string
    </span>;
  };
};
← CounterReasonReact using ReactJS →