Home > Mobile >  How to get main url of project in reactjs
How to get main url of project in reactjs

Time:07-08

I am working with reactjs and i want to get fullpath/hostname/baseurl of my project (inside component file),How can i do this ?I tried with following code,but not working,giving me following error

"Unexpected token `{`. Expected * for generator"

I tried with following code

import absoluteUrl from 'next-absolute-url';
class Header extends Component {
const { origin } = absoluteUrl(req)
const apiURL = ${origin}
render() 
    {
        ...//my code
    }   
}

CodePudding user response:

How about using the window object.

Note: when using window, do wrap it inside the below if condition, else it will error out when you're using SSR.

import '../styles/globals.css';

function MyApp({ Component, pageProps }) {
  let fullPath = '';
  if (typeof window !== undefined) {
    fullPath = window.location.hostname;
  }
  console.log(fullPath);
  return <Component {...pageProps} className={fullPath === 'insert your path here' ? 'insert class to apply if true' : 'insert class to apply if false'}/>;
}

export default MyApp;

stackblitz

CodePudding user response:

So firstly, remember your code runs on client and server so any access to window needs to be wrapped in a check.

  if (typeof window !== 'undefined') {
    var path = location.protocol   '//'   location.host   '/someting'; // (or whatever)
  } else {
    // work out what you want to do server-side...
  }
  • Related