简体   繁体   中英

ReactJS: Link to go to next page dynamically

I have this App.jsx that has the routing and I have a component NextPage.jsx that is a simple Link that should point to the next page. My issue is:how can I tell to the link in NextPage component to point to the next page? so if I am in Homepage the link should let me go to Portfolio, if on Portfolio I should be able to go to Skills and so on.

This is my App.jsx

const App = () => (
  <div className="main-container">
    <Menu/>
    <NextPage/>
    <AnimatedSwitch
      atEnter={{ offset: 100}}
      atLeave={{ offset: -100}}
      atActive={{offset: 0}}
      mapStyles={(style) => ({
        transform: `translateX(${style.offset}%)`,
      })}
    >
      <Route exact path="/" component={Homepage} />
      <Route path="/portfolio" component={Portfolio} />
      <Route path="/skills" component={Skills} />
      <Route path="/contacts" component={Contacts} />
      <Route path='*' component={NotFound} />
    </AnimatedSwitch>
  </div>  
);

export default App;

This is my NextPage.jsx

const NextPage = () => (
        <div className="next-arrow">
          <Link to='#HEREGOESTHENEXTPAGELINK#'><i className="fa fa-angle-right" aria-hidden="true"></i></Link>
        </div>
    );

export default NextPage;

Your approach to implementing this seems a bit odd in my opinion, but I digress.

The first thing you'd need to do is to somehow store all the links as well as their order of appearance. The biggest question I'd say is where you're going to store this; you could store it in a database, create a global variable, store it in a stage-management library (if you use one), etc etc.

It is unclear which of these you use and which you'd prefer, so I'll leave that to you and just present the concept below.


In your root React Component define an array of all the links. You could do this in the constructor:

class MyApp extends React.Component {
  constructor() {
    super();
    window.links = ["/", "/portfolio", "/skills", "/contacts"];
  }

  render() ...
}

This will make window.links accessible in all components. This means you compare the active url, look it up in the array, and make the link direct you to the next one.

const NextPage = (props) => {
  let idx = window.links.indexOf(props.route.path) + 1;
  let link = (idx == window.links.length) ? window.links[0] : window.links[idx];
  return (
    <div className="next-arrow">
      <Link to={link}><i className="fa fa-angle-right" aria-hidden="true"></i></Link>
    </div>
  );
}

export default NextPage;

Note that if the current link is not one of the ones defined in window.links , the link will take you to the first one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM