简体   繁体   中英

getElementById() doesn't work when entering by react-router's <Link>

I created a simple react app with react-router(v5.) There are footers with current year in every page.

const footerYear = document.getElementById('footerThisYear');
if (footerYear) {
  footerYear.innerHTML = new Date().getFullYear();
}

The problem is the snippet above doesn't work in child pages entering through react-router's <Link> . It works when entering the complete urls.

Preview: https://stackblitz.com/edit/react-mqjws7?file=index.js

Child page example url: https://react-mqjws7.stackblitz.io/page/a

Question: How to get this work in every page?

Thank you!

If you want to get that to work on every page, you're going to have to put that if statement in the Footer.js file. The easiest way to explain this is that your routes are working like this:

URL -> index.js -> Router -> Page

When entering the page using the direct URL, this is the path it goes through since your Router component is located in index.js. When clicking on the Links on Home.js, since it originates from Home.js which is already in index.js, it's only going through

Router -> Page

As a result of this, the proper footer you want is not showing because the function to display it is located in index.js. To test this, you can place a console.log statement inside your if statement. It will not be called if you're navigating to your pages inside of Home.js.

Change Footer.js to a class and put the if statement in there and it should work correctly. Otherwise, you can also set the footer to conditionally render the year given a prop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM