Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it an antipattern to set state based on URL?

I have 3 views: stream, playlist, and profile. Each view requires different buttons (minor differences), but the components do not care about the distinction overall. They continue to retrieve and present data normally.

There is not enough distinction to create different components, i just need a state variable to change the buttons.

Here's the problem: the only way to get the state variable is either a.) in window.location.pathname, or b.) in props passed by react router, which is then made available via the context api. Is one solution better than another? Are they both incorrect for a professional app?

like image 507
user7229669 Avatar asked Oct 29 '25 09:10

user7229669


1 Answers

There is nothing wrong with changing your single component depending on what is present in your url. This is a great use case for URL parameters.

Example

function MyComponent(props) {
  const { params } = props.match;
  const { pathParameter } = params;

  if (pathParameter === "home") {
    return <div> Welcome to my home page </div>;
  } else if (pathParameter === "about") {
    return <div> This is the about me page </div>;
  } else {
    return <div> This is a third option </div>;
  }
}

function App() {
  return (
    <Router>
      <div>
        <Link to="/home">Home</Link>
        <Link to="/about">About</Link>
        <Link to="/blog">Blog</Link>
        <Switch>
          <Route path="/:pathParameter" component={MyComponent} />
        </Switch>
      </div>
    </Router>
  );
}
like image 190
Tholle Avatar answered Oct 31 '25 23:10

Tholle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!