React/Material-UIでタブとreact-route-domによるルーティング


タブの実装

./src/components/ui/Header.js
import React, { useState } from "react";
import { AppBar, Tabs, Toolbar, Tab } from "@material-ui/core";

const Header = () => {
  const [value, setValue] = useState(0);

  const handleChange = (event, value) => {
    setValue(value);
  };
  console.log(value);

  return (
    <AppBar position="static">
      <Toolbar>
        <Tabs value={value} onChange={handleChange}>
          <Tab label="AAA" />
          <Tab label="BBB" />
          <Tab label="CCC" />
        </Tabs>
      </Toolbar>
    </AppBar>
  );
};

export default Header;

ルーティングの実装

react-route-domを使うと便利。

./src/App.js
import logo from "./logo.svg";
import "./App.css";
import Header from "./components/ui/Header";
import { BrowserRouter, Route, Switch } from "react-router-dom";

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <Header />
        <Switch>
          <Route exact path="/" component={() => <div>AAA</div>} />
          <Route exact path="/bbb" component={() => <div>BBB</div>} />
          <Route exact path="/ccc" component={() => <div>CCC</div>} />
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;
./src/components/ui/Header.js
import React, { useState } from "react";
import { AppBar, Tabs, Toolbar, Tab } from "@material-ui/core";
import { Link } from "react-router-dom";

const Header = () => {
  const [value, setValue] = useState(0);

  const handleChange = (event, value) => {
    setValue(value);
  };
  console.log(value);

  return (
    <AppBar position="static">
      <Toolbar>
        <Tabs value={value} onChange={handleChange}>
          <Tab label="AAA" component={Link} to="/" />
          <Tab label="BBB" component={Link} to="/bbb" />
          <Tab label="CCC" component={Link} to="/ccc" />
        </Tabs>
      </Toolbar>
    </AppBar>
  );
};

export default Header;