fwojciec / simple-i18n-example

Simple example of a multilingual site in Next.js using dynamic routing.
161 stars 34 forks source link

Redirect subpath to locale subpath #4

Open billzhong opened 4 years ago

billzhong commented 4 years ago

Hi,

Is there any chance to redirect people to locale subpath when they try to access sub page directly? Currently, 404 is returned. For example, https://simple-i18n-example.fwojciec.now.sh/artist will redirect to https://simple-i18n-example.fwojciec.now.sh/{lang}/artist.

cgaspart commented 4 years ago

Hi,

In your pages folder create a new one artist with subdirectory [lang] inside. C opy past your code inside [lang].

// /pages/artist/index.tsx

import React from 'react'
import { getInitialLocale } from '../../translations/getInitialLocale'

const Index: React.FC = () => {
  React.useEffect(() => {
    window.location.replace(`/artist/${getInitialLocale()}`)
  })
  return (
    <>
    </>
  )
}

export default Index

It's not the best way to do i guess but it's works

billzhong commented 4 years ago

Hi,

I figure out a solution. Go to hocs/withLocale.tsx file, before return <Error statusCode={404} /> add following code:

const router = useRouter();
React.useEffect(() => {
  window.location.replace(`/${getInitialLocale()}${router.asPath}`);
});

At the top of this file, add import {useRouter} from 'next/router' I am not sure if this is the best way, but it works for me at this moment.