Skip to content

Latest commit

 

History

History
39 lines (27 loc) · 910 Bytes

getting_url.md

File metadata and controls

39 lines (27 loc) · 910 Bytes

Getting the current URL in React

const url = typeof window !== 'undefined' ? window.location.href : '';

This will allow you to store the current url of the page. This is handy if you want to style certain objects with ternary operators. Like so

class Sidebar extends React.Component {
  ...
  render() {
    const url = typeof window !== 'undefined' ? window.location.href : '';

    return (

       <span className={`font-bold text-xl md:text-2xl ${ url === 'http://localhost:8000/' ? 'text-gray-100' : 'text-gray-900'} tracking-wider hover:underline`}>
           Menu
       </span>

React Functional Component

const Header = () => {
  const url = typeof window !== 'undefined' ? window.location.href : '';

  return (
  ...

Ternary Operator

{url === 'http://localhost:8000/' ?  'condition 1' : 'condition 2'}