Chapter 9. Example 1

← Back to Chapter 9 examples

import { ChangeEvent, useEffect, useRef, useState } from 'react';

import './styles.scss';
import { Button } from './components/button';

const FormWithState = () => {
  const [value, setValue] = useState<string>();

  useEffect(() => {
    console.log('re-render FormWithState');
  });
  const onChange = (e: ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value);
  };
  const submit = () => {
    // send to the backend here
    console.log(value);
  };

  return (
    <div className="column">
      <h3>Form with state</h3>
      <input type="text" onChange={onChange} />
      <Button onClick={submit}>submit</Button>
    </div>
  );
};

const FormWithRef = () => {
  const ref = useRef('');

  useEffect(() => {
    console.log('re-render FormWithRef');
  });

  const onChange = (e: ChangeEvent<HTMLInputElement>) => {
    ref.current = e.target.value;
  };
  const submit = () => {
    // send to the backend here
    console.log(ref.current);
  };

  return (
    <div className="column">
      <h3>Form with ref</h3>
      <input type="text" onChange={onChange} />
      <Button onClick={submit}>submit</Button>
    </div>
  );
};
export default function App() {
  return (
    <div className="App">
      <h1>Refs for storing values: Form component</h1>

      <div className="container">
        <FormWithState />
        <FormWithRef />
      </div>
    </div>
  );
}