Target Active Link when the route is active in Next.js












0














How to target the active Link in Next.js like they way we do it in React-Router-4?
Meaning, give the active link a class when its route is active?










share|improve this question



























    0














    How to target the active Link in Next.js like they way we do it in React-Router-4?
    Meaning, give the active link a class when its route is active?










    share|improve this question

























      0












      0








      0


      1





      How to target the active Link in Next.js like they way we do it in React-Router-4?
      Meaning, give the active link a class when its route is active?










      share|improve this question













      How to target the active Link in Next.js like they way we do it in React-Router-4?
      Meaning, give the active link a class when its route is active?







      reactjs react-router next.js






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 at 12:31









      Ruby

      315221




      315221
























          1 Answer
          1






          active

          oldest

          votes


















          2














          First, you need to have a component called Link, with temporary attribute activeClassName



          import { withRouter } from 'next/router'
          import Link from 'next/link'
          import React, { Children } from 'react'

          const ActiveLink = ({ router, children, ...props }) => {
          const child = Children.only(children)

          let className = child.props.className || null
          if (router.pathname === props.href && props.activeClassName) {
          className = `${className !== null ? className : ''} ${props.activeClassName}`.trim()
          }

          delete props.activeClassName

          return <Link {...props}>{React.cloneElement(child, { className })}</Link>
          }

          export default withRouter(ActiveLink)


          Then have a navigation bar with created component Link and css selector :active to differentiate between active and inactive link.



          import Link from './Link'

          export default () => (
          <nav>
          <style jsx>{`
          .active:after {
          content: ' (current page)';
          }
          .nav-link {
          text-decoration: none;
          padding: 10px;
          display: block;
          }
          `}</style>

          <ul>
          <li>
          <Link activeClassName='active' href='/'>
          <a className='nav-link home-link'>Home</a>
          </Link>
          </li>
          <li>
          <Link activeClassName='active' href='/about'>
          <a className='nav-link'>About</a>
          </Link>
          </li>
          </ul>
          </nav>
          )


          After that, you can implement the navigation bar to your page:



          import Nav from '../components/Nav'

          export default () => (
          <div>
          <Nav />
          <p>Hello, I'm the home page</p>
          </div>
          )


          The key of how does this work is located inside component Link, we compare the value of router.pathname with attribute href from the Link, if the value match the other then put specific className to make the link looks activated.



          Reference: here






          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53262263%2ftarget-active-link-when-the-route-is-active-in-next-js%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            First, you need to have a component called Link, with temporary attribute activeClassName



            import { withRouter } from 'next/router'
            import Link from 'next/link'
            import React, { Children } from 'react'

            const ActiveLink = ({ router, children, ...props }) => {
            const child = Children.only(children)

            let className = child.props.className || null
            if (router.pathname === props.href && props.activeClassName) {
            className = `${className !== null ? className : ''} ${props.activeClassName}`.trim()
            }

            delete props.activeClassName

            return <Link {...props}>{React.cloneElement(child, { className })}</Link>
            }

            export default withRouter(ActiveLink)


            Then have a navigation bar with created component Link and css selector :active to differentiate between active and inactive link.



            import Link from './Link'

            export default () => (
            <nav>
            <style jsx>{`
            .active:after {
            content: ' (current page)';
            }
            .nav-link {
            text-decoration: none;
            padding: 10px;
            display: block;
            }
            `}</style>

            <ul>
            <li>
            <Link activeClassName='active' href='/'>
            <a className='nav-link home-link'>Home</a>
            </Link>
            </li>
            <li>
            <Link activeClassName='active' href='/about'>
            <a className='nav-link'>About</a>
            </Link>
            </li>
            </ul>
            </nav>
            )


            After that, you can implement the navigation bar to your page:



            import Nav from '../components/Nav'

            export default () => (
            <div>
            <Nav />
            <p>Hello, I'm the home page</p>
            </div>
            )


            The key of how does this work is located inside component Link, we compare the value of router.pathname with attribute href from the Link, if the value match the other then put specific className to make the link looks activated.



            Reference: here






            share|improve this answer


























              2














              First, you need to have a component called Link, with temporary attribute activeClassName



              import { withRouter } from 'next/router'
              import Link from 'next/link'
              import React, { Children } from 'react'

              const ActiveLink = ({ router, children, ...props }) => {
              const child = Children.only(children)

              let className = child.props.className || null
              if (router.pathname === props.href && props.activeClassName) {
              className = `${className !== null ? className : ''} ${props.activeClassName}`.trim()
              }

              delete props.activeClassName

              return <Link {...props}>{React.cloneElement(child, { className })}</Link>
              }

              export default withRouter(ActiveLink)


              Then have a navigation bar with created component Link and css selector :active to differentiate between active and inactive link.



              import Link from './Link'

              export default () => (
              <nav>
              <style jsx>{`
              .active:after {
              content: ' (current page)';
              }
              .nav-link {
              text-decoration: none;
              padding: 10px;
              display: block;
              }
              `}</style>

              <ul>
              <li>
              <Link activeClassName='active' href='/'>
              <a className='nav-link home-link'>Home</a>
              </Link>
              </li>
              <li>
              <Link activeClassName='active' href='/about'>
              <a className='nav-link'>About</a>
              </Link>
              </li>
              </ul>
              </nav>
              )


              After that, you can implement the navigation bar to your page:



              import Nav from '../components/Nav'

              export default () => (
              <div>
              <Nav />
              <p>Hello, I'm the home page</p>
              </div>
              )


              The key of how does this work is located inside component Link, we compare the value of router.pathname with attribute href from the Link, if the value match the other then put specific className to make the link looks activated.



              Reference: here






              share|improve this answer
























                2












                2








                2






                First, you need to have a component called Link, with temporary attribute activeClassName



                import { withRouter } from 'next/router'
                import Link from 'next/link'
                import React, { Children } from 'react'

                const ActiveLink = ({ router, children, ...props }) => {
                const child = Children.only(children)

                let className = child.props.className || null
                if (router.pathname === props.href && props.activeClassName) {
                className = `${className !== null ? className : ''} ${props.activeClassName}`.trim()
                }

                delete props.activeClassName

                return <Link {...props}>{React.cloneElement(child, { className })}</Link>
                }

                export default withRouter(ActiveLink)


                Then have a navigation bar with created component Link and css selector :active to differentiate between active and inactive link.



                import Link from './Link'

                export default () => (
                <nav>
                <style jsx>{`
                .active:after {
                content: ' (current page)';
                }
                .nav-link {
                text-decoration: none;
                padding: 10px;
                display: block;
                }
                `}</style>

                <ul>
                <li>
                <Link activeClassName='active' href='/'>
                <a className='nav-link home-link'>Home</a>
                </Link>
                </li>
                <li>
                <Link activeClassName='active' href='/about'>
                <a className='nav-link'>About</a>
                </Link>
                </li>
                </ul>
                </nav>
                )


                After that, you can implement the navigation bar to your page:



                import Nav from '../components/Nav'

                export default () => (
                <div>
                <Nav />
                <p>Hello, I'm the home page</p>
                </div>
                )


                The key of how does this work is located inside component Link, we compare the value of router.pathname with attribute href from the Link, if the value match the other then put specific className to make the link looks activated.



                Reference: here






                share|improve this answer












                First, you need to have a component called Link, with temporary attribute activeClassName



                import { withRouter } from 'next/router'
                import Link from 'next/link'
                import React, { Children } from 'react'

                const ActiveLink = ({ router, children, ...props }) => {
                const child = Children.only(children)

                let className = child.props.className || null
                if (router.pathname === props.href && props.activeClassName) {
                className = `${className !== null ? className : ''} ${props.activeClassName}`.trim()
                }

                delete props.activeClassName

                return <Link {...props}>{React.cloneElement(child, { className })}</Link>
                }

                export default withRouter(ActiveLink)


                Then have a navigation bar with created component Link and css selector :active to differentiate between active and inactive link.



                import Link from './Link'

                export default () => (
                <nav>
                <style jsx>{`
                .active:after {
                content: ' (current page)';
                }
                .nav-link {
                text-decoration: none;
                padding: 10px;
                display: block;
                }
                `}</style>

                <ul>
                <li>
                <Link activeClassName='active' href='/'>
                <a className='nav-link home-link'>Home</a>
                </Link>
                </li>
                <li>
                <Link activeClassName='active' href='/about'>
                <a className='nav-link'>About</a>
                </Link>
                </li>
                </ul>
                </nav>
                )


                After that, you can implement the navigation bar to your page:



                import Nav from '../components/Nav'

                export default () => (
                <div>
                <Nav />
                <p>Hello, I'm the home page</p>
                </div>
                )


                The key of how does this work is located inside component Link, we compare the value of router.pathname with attribute href from the Link, if the value match the other then put specific className to make the link looks activated.



                Reference: here







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 12 at 16:14









                Darryl R. Norbert

                512315




                512315






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53262263%2ftarget-active-link-when-the-route-is-active-in-next-js%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Xamarin.iOS Cant Deploy on Iphone

                    Glorious Revolution

                    Dulmage-Mendelsohn matrix decomposition in Python