Skip to content

03 Structure

JP Barbosa edited this page Oct 15, 2022 · 4 revisions

Basic Structure

Components

Components

Create Page Context

code ./src/contexts/Page.tsx
import { createContext, useContext, useState } from 'react';

export enum Page {
  Articles = 'Articles',
  Authors = 'Authors',
}

type ContextType = {
  page: Page;
  setPage: (page: Page) => void;
};

const Context = createContext<ContextType>({
  page: Page.Articles,
  setPage: (page) => console.warn('no page provider'),
});

export const usePage = () => useContext(Context);

type PageStoreProps = {
  children: React.ReactNode;
};

export const PageStore: React.FC<PageStoreProps> = ({ children }) => {
  const [page, setPage] = useState(Page.Articles);
  return (
    <Context.Provider value={{ page, setPage }}>{children}</Context.Provider>
  );
};

Add Page Store to index

code ./src/index.tsx
...
import { PageStore } from './contexts/Page';

ReactDOM.render(
  <React.StrictMode>
    <PageStore>
      <App />
    </PageStore>
  </React.StrictMode>,
  document.getElementById('root')
);

Add renderSwitch and Header to App

code ./src/App.tsx
import { Header } from './components/Header';
import { Page, usePage } from './contexts/Page';

const App: React.FC = () => {
  const { page } = usePage();

  const renderSwitch = () => {
    switch (page) {
      case Page.Articles:
        return <div>Articles</div>;
      case Page.Authors:
        return <div>Authors</div>;
      default:
        return '';
    }
  };

  return (
    <div className="App">
      <Header />
      {renderSwitch()}
    </div>
  );
};

export default App;

Create Header

code ./src/components/Header.tsx
import { usePage, Page } from '../contexts/Page';

export const Header: React.FC = () => {
  const { page, setPage } = usePage();

  const pageButton = (pageName: Page) => {
    return (
      <button
        className={pageName === page ? 'active' : ''}
        onClick={() => setPage(pageName)}
      >
        {pageName}
      </button>
    );
  };

  return (
    <header>
      <h1>
        <div className="title">TypeScript CRUD</div>
        <div className="subtitle">With React and TypeORM</div>
      </h1>
      <div className="navigation">
        <div className="internal">
          {pageButton(Page.Articles)}
          {pageButton(Page.Authors)}
        </div>
        <div className="external">
          <a
            href="https://github.com/jp7internet/typescript-crud"
            target="_blank"
            rel="noreferrer"
            className="button"
          >
            GitHub
          </a>
        </div>
      </div>
    </header>
  );
};

Result

Result

Commit

git add .
git commit -m "Structure"

Next step: Interfaces

Clone this wiki locally