I new in React and I looking for any way (the best correct) how to open new page. I html it's like <a href="/about"></a>
but I read article and that was say don't use it. When I try use Link
from React I got very more errors.
Thanks
CodePudding user response:
Welcome to the React realm :) . If you use "a" tag this will make the page to refresh and that is against the concept of SPA. So you need to use a routing library to be able to navigate between pages. Link is a component in the React-Routing library so you need to install it first. Here you can learn more: https://reactrouter.com/en/main/start/tutorial
CodePudding user response:
We must first look into the difference between an anchor tag and a Link tag
Anchor tag
- Default HTML tag
- Refreshes the page
- Resets useStates
Link tag
- Is added with packages
- Doesn't trigger page refresh
- Doesn't reset useStates
From this we conclude that Link tags are preferable to anchor tags, therefore you should use link tag instead of anchor tag. In order to have such added, you need to install a package like react-router and set up routing.
Check these two pages, they contain very elaborate tutorial on how to do routing:
CodePudding user response:
In my react projects, I usually use libraries such as react-router-dom. https://www.npmjs.com/package/react-router-dom . What's more, it is very useful for you to learn some routing libraries if you want to improve your react skills.
CodePudding user response:
As the other answer stated, you will need a router, because in React, everything lives inside of index.html
, so we need to navigate without actually leaving the page. react-router
is a good option, React Location is also a great option, but I would stick to react-router
if you're just starting out. Another option would be using Next.js. It has a built-in file based routing solution, so it should feel more like writing traditional html websites, where every file in your pages directory is a separate page. (And indeed that is what's happening behind the scenes.) Again, this is a bit more advanced and might be out of the question's scope but is definitely worth checking out.