user2570135
user2570135

Reputation: 3009

Reactjs/Nextjs- how to redirect to another page using NextJS

I am using nextjs/reactjs and need some help on how to redirect to a page

Folder structure

-Pages

  -business

    -location.js

    -selectlocation.js

The URL =http://myhost/business/location?city=Pensacola&state=FL

When the argument is missing, I want to redirect to selectlocation

How do I route to the selectlocation page from the location page when the argument is empty

This is a snippet of my code for location.js

export default class extends Component {
    static getInitialProps({ query: { city, state } }) {
        return { city: city, state: state };
    }
    render() {
        return (
            <div>
                <Head>
                    <title>{title}</title>
                    <meta name="description" content={description} />
                </Head>

                <LayoutWithHeader
                    banner={false}
                    view="business"
                    link="location banner"
                    locationCity={this.props.city}
                    locationState={this.props.state}>
                    <Location />
                </LayoutWithHeader>
            </div>
        );

    }
}

Code for SelectLocation.JS

export default () => (
    <div>
        <Head>
            <title>Location</title>
        </Head>
        <LayoutWithHeader banner={true} title="Home / Business / Locations" >
            <SelectLocation />
        </LayoutWithHeader>
    </div>
);

Upvotes: 5

Views: 14614

Answers (2)

Aamjit Yanglem
Aamjit Yanglem

Reputation: 57

A bit too late for the answer but from my experience, as of current practice, I would lay my folder structure as follows:

- (routes)
    - business
        - location
            - page.js
        - selectlocation
            - page.js

Here in business/location/page.js, as client component, you can add as

"use client";
import { useSearchParams, useRouter } from 'next/navigation';

export default function Location() {
  const searchParams = useSearchParams();
  const router= useRouter();
 
  const search = searchParams.get('<query_name>'); // use 'getAll()' for all parameters
 
  // URL -> `.../business/location/?city=<city>&state=<state>`
  // `search` -> '{city: <city>, state: <state>}'

  return search? // or specifically, search?.city? {..components}: {handle route}
    <>
       {...components}
    </>
    : router.push("/business/selectlocation")
}

Upvotes: 0

Muhammad Ali
Muhammad Ali

Reputation: 2648

Sample routing code:

import { useRouter } from 'next/router'

function Home() {
  const router = useRouter()


  const handleClick = e => {
    e.preventDefault()
    router.push('/some-path')
  }

  return (
    <button type="button" onClick={handleClick}>
      Go Somewhere
    </button>
  )
}

Please see the docs for further details.

Upvotes: 10

Related Questions