0

Есть несоколько кнопок из material-ui и роутинг. Внутри Button находится NavLink - по нажатию на кнопку происходит изменение url, один компонент скрывается, новый появляется - тут все нормально.

Но мне хотелось бы добавить кнопкам "активные" стили, изменить цвет или атрибут (например variant) у Button если мы находимся на странице на которую ведет Link. В теории это не должно быть сложно, но не доходит. Набросал небольшой пример на jsfiddle.net.

const options = [
    {
        name: 'Приход',
        link: '/income'
    },
    {
        name: 'Расход',
        link: '/spend'
    },
    {
        name: 'Статистика',
        link: '/statistic'
    }
];

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    
    this.Router = window.ReactRouterDOM.BrowserRouter
    this.Button = window['material-ui'].Button;
    this.NavLink = window.ReactRouterDOM.NavLink;
    this.Route = window.ReactRouterDOM.Route;
  }
  
  render() {
    return (
            < this.Router >
              <div>
                              {
                    options.map((opt, i) => (
                    //Если ссылка активна, то заменить [variant="contained"] на [variant="outlined"]
                        <this.Button key={i} variant="contained" color="primary">
                            <this.NavLink to={opt.link} >{opt.name}</this.NavLink>
                        </this.Button>
                    ))
                }
                        <hr />

        <this.Route exact path="/income" component={Income} />
        <this.Route path="/spend" component={Spend} />
        <this.Route path="/statistic" component={Statistic} />
              </div>
            </ this.Router>
    )
  }
}

function Income() {
  return (
		<div>
      <h2>Income</h2>
    </div>
  );
}

function Spend() {
  return (
    <div>
      <h2>Spend</h2>
    </div>
  );
}

function Statistic() {
  return (
    <div>
      <h2>Statistic</h2>
    </div>
  );
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))

1 ответ 1

2

Я решил сделать это таким способом:

import React, { Component } from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import { NavLink } from "react-router-dom";
import Button from "@material-ui/core/Button";

const packageJSON = [
  {
    name: "Home",
    path: "/"
  },
  {
    name: "About",
    path: "/about"
  },
  {
    name: "Contacts",
    path: "/contacts"
  }
];

const styles = theme => ({});

class App extends Component {
  render() {
    const location = window.location.pathname;
    return (
      <>
        <div>
          {packageJSON.map((item, index) => (
            <Button variant={item.path === location ? "outlined" : "contained"} key={index} component={NavLink} exact={item.name === 'Home' ? true : false} to={item.path}>{item.name}</Button>
          ))}
        </div>
      </>
    );
  }
}

App.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(App);

P.S. если удобнее, то посмотрите на CodeSandBox

UPD. После комментариев

Бодался с главной старницей, т.к. у неё path = /, но ничего не вышло, переделал path главной страницы на /home и вот что из этого вышло:

import React, { Component } from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import { NavLink, Switch, Route } from "react-router-dom";
import Button from "@material-ui/core/Button";
import Home from "./Home";
import About from "./About";
import Contacts from "./Contacts";
import Test from "./Test";

const packageJSON = [
  {
    name: "Home",
    path: "/home"
  },
  {
    name: "About",
    path: "/about"
  },
  {
    name: "Contacts",
    path: "/contacts"
  }
];

const styles = theme => ({
  button: {
    "&:not(:last-child)": { marginRight: 30 }
  }
});

class App extends Component {
  render() {
    const { classes } = this.props;
    const location = window.location.href;
    console.log(location);

    return (
      <>
        <div>
          {packageJSON.map((item, index) => (
            <Button
              variant={
                location.indexOf(item.path) !== -1 ? "outlined" : "contained"
              }
              key={index}
              component={NavLink}
              exact={item.name === "Home" ? true : false}
              to={item.path}
              className={classes.button}
              color="secondary"
            >
              {item.name}
            </Button>
          ))}
        </div>
        <div>
          <Switch>
            <Route exact path="/home" component={Home} />
            <Route exact path="/about" component={About} />
            <Route exact path="/contacts" component={Contacts} />
            <Route exact path="/contacts/:id" component={Test} />
          </Switch>
        </div>
      </>
    );
  }
}

App.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(App);

Если перейти, допустим, на /contacts/12, то кнопка Contacts будет со стилем outlined, т.е. так, как нужно. (Соответственно, вместо 12 может быть любое число/буква/слово и т.д.)

P.S. CodeSandBox всё ещё по старой ссылке.

5
  • У меня тоже вышел вариант вроде этого, но что в моем, что здесь есть нюанс. Например, на странице /contacts можно будет перейти еще на один уровень ниже /contacts/:manager-id и тогда выделение с кнопки пропадат, ведь тут строгое сравнение по url. Может через регулярное выражение или вообще иной вариант можно решить? 23 янв 2019 в 20:18
  • @Dantessss, ещё как вариант можно узнавать, есть ли class active на элементе и менять variant
    – meine
    23 янв 2019 в 20:23
  • Была такая идея, но как реализовать это в react'e я не понял. Поможете? 23 янв 2019 в 20:28
  • @Dantessss, щас попробуем разобраться.
    – meine
    23 янв 2019 в 20:30
  • @Dantessss, обновил, если не критично, чтобы главная была по пути /, то можете использовать этот вариант, ну или, может, придумаете решение с /.
    – meine
    23 янв 2019 в 21:59

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.