3

My web application manages backend routes with Next.js. The problem is that I want to use react-router-dom in one section. For example, working with Laravel and React, I set my route like this:

 Route::get('/reactPage/*' ...)

and then use client route with React. But I don't know how handle this with Next.js.

I want the user to click a link after seeing a page with a link. If the user clicks that link, react-router-dom should handle route and not send request to server.

2 Answers 2

1

I would recommend using the Next router. You do need to create a custom server in order to overload the default Next routing, but its a trivial task:

// server.js
const { createServer } = require('http');
const next = require('next');
const routes = require('./routes');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handler = routes.getRequestHandler(app);

app.prepare().then(() => {
    createServer(handler).listen(port, err => {
        if (err) {
            throw err;
        }
        console.log(`> Ready on http://localhost:${port}`);
    });
});

Then you can define routes, which I do in the routes.js file:

// routes.js
const nextRoutes = require('next-routes');
const routes = (module.exports = nextRoutes());

routes
    .add('landing', '/')
    .add('profile', '/profile', 'profile');

Sign up to request clarification or add additional context in comments.

1 Comment

Where exactly are these two files created?
-1
"use client"; // important in App Router, ensures client-side only

import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

function MyReactApp() {
  return (
    <BrowserRouter basename="/reactPage">
      <nav>
        <Link to="/">Home</Link> |{" "}
        <Link to="/about">About</Link>
      </nav>

      <Routes>
        <Route path="/" element={<h2>Home in React Router</h2>} />
        <Route path="/about" element={<h2>About in React Router</h2>} />
      </Routes>
    </BrowserRouter>
  );
}

export default function ReactPageWrapper() {
  return <MyReactApp />;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.