Skip to content

Base: React with Typescript

Melvyn M edited this page Feb 3, 2021 · 2 revisions

Exemple of basic component with type.

// App.tsx

// exemple of Exemple using
function App() {
  return (
    <div>
      <Exemple
        size="small"
        onClick={text => console.log(text)}
        displaySecondButton={true}>
        <p>Je suis le `children`</p>
      </Exemple>
    </div>
  );
}

// src/components/Exemple.tsx

type ExempleProps = {
  // size can now only be a string "small" or "big"
  size: 'small' | 'big';
  children: React.ReactElement; // can be a string, a component...
  onClick: (text: string) => void;
  displaySecondButton: boolean;
  // the `?` is for say the lists in not required
  lists?: Array<string>;
};

export default function Exemple({
  size,
  children,
  onClick,
  displaySecondButton,
  lists,
}: ExempleProps) {
  // a component state
  const [input, setInput] = React.useState<string>('');

  return (
    <div>
      <input value={input} onChange={event => setInput(event.target.value)} />
      <button
        // typescript know now size can be only small or big
        style={{ height: size === 'small' ? 14 : 20 }}
        //            input is a string, so it's works
        onClick={() => onClick(input)}>
        Click me
      </button>
      {/* conditional rendering */}
      {displaySecondButton && <button>Second button</button>}
      {/* show the children */}
      <div>{children}</div>
      {/* list rendering */}
      <ul>
        {/* list is not required, so I check if exist, else I display a message */}
        {lists ? (
          lists.map(e => <li>Element: {e}</li>)
        ) : (
          <p>no list provided</p>
        )}
      </ul>
    </div>
  );
}
Clone this wiki locally