Nextjs Router.push vs href - javascript

For Routing to some page on click, I can achieve it in two ways
import Router from 'next/router'
<button onClick={() => Router.push('/about')}>
<a>Go to About</a>
</button>
And
<button>
Go to About
</button>
Which one is the best practice in Nextjs?

a tag inside button is not allowed in semantic html, both of them are interactive elements.
For links, Next provides Link component that accepts a tag as a child.
For buttons, use <button onClick={() => Router.push('/about')}>text</button> without a.

The best way to create links between pages is to use your nextjs package.
import Link from "next/link";
Then use it like that
<Link href={'/'} params={'id': 1}>
<a>link</a>
</.Link>
if useing node js router href linked by name route

For the best user experience I would suggest a third option / best practice:
import Link from "next/link";
<Link href={"/within/your/page"} passHref>
<button>go</button> // or any other element
</Link>
pre NextJS 10 if your path had dynamic segments you would need to pass "as" also like:
import Link from "next/link";
<Link href={"/review/[id]"} as={"/review/12"} passHref>
<button>go</button> // or any other element
</Link>
The Link Component / the router.push enables client side navigation. This makes navigating your website a lot faster.
you can read more on this here:
https://nextjs.org/docs/api-reference/next/link
https://nextjs.org/docs/api-reference/next/router

Related

DOM disappearing when replacing anchor tags with React Link components

I am new to working on the frontend. I'm learning how to use React and react-router-dom library. The program renders without a problem normally. The problem lies when I try to add a Link component from the React library. When I do this, the DOM is no longer displayed.
import React from "react"
import {Routes, Route, Link} from "react-router-dom"
import Mflix from "./components/mflix.js"
function App(){
return (
<div className="App">
<nav className="navbar navbar-expand navbar-dark bg-dark">
<a href="/mflix" className="navbar-brand"> {/*href links to "/mflix" route */}
Mflix Reviews
</a>
<div className="navbar-nav mr-auto">
<li className="nav-item">
<Link to={"/mflix"} className="nav-link">
Movies
</Link>
</li>
</div>
</nav>
</div>
)
}
This SO forum has a similar problem, except they created a class for their app, and I'm trying to keep it as a function for now.
If I replace the code:
<Link to={"/mflix"} className="nav-link">
Movies
</Link>
with
<a href="/mflix"m className="nav-link">
Movies
</a>
The DOM renders fine, buT I want to use Link because it doesn't force my page to refresh every time.
Edit: I read that instead of passing a JS expression to the to <Link to{"/mflix"}/> I should pass a string <Link to"/mflix"/>. However, the documentation says that if the link uses a path name, then it should be passed to to= as an object, and not a string. IN any case, I tried the suggestion, but the code still returns a blank page.
Edit: This is what the web console has to say about the component:
he above error occurred in the <Link> component:
LinkWithRef#http://localhost:3000/static/js/bundle.js:37314:9
li
div
nav
div
App#http://localhost:3000/static/js/bundle.js:40:72
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
Whenever the DOM disappears, there is an issue in your code. I'm guessing it has to do with this "Mflix" import. Bring up the console and see what it says.

How do I make an inpage link with React?

I want to make a React website and want it to use inpage links. I know that in normal html you can just use:
<a href='#someheader'>link</a>
<h1 id='someheader'>This is an example</h1>
In react though, I am using multiple separate files for each part of the website. So for the navigation bar I have a file and for the body I have a file etc.
I have tried the above technique, but it doesn't seem to work.
Is it because of the link and the place I want the link to go to are in different pages, or is it because of something else?
For this route:
<Route path="/about" component={AboutPage} />
## Link to anchor on same page
<!-- AboutPage.js -->
<a href='#someheader'>Jump to someheader</a>
Go to anchor someheader on the current page (Not related to React-Router - this is simple HTML behavior). a element docs
## Link to anchor on another page (Tricky)
Jump to someheader point on about page.
This code will work (But you do not get the "power/features" of React-Router):
<!-- HomePage.js -->
<!-- Simple href to anchor -->
<a href='about#someheader'>
Go to about page and jump to someheader
</a>
But when using the <Link> component to navigate - the scroll to #hash will not work/scroll.
Related github issue: https://github.com/ReactTraining/react-router/issues/394
<!-- HomePage.js -->
<!-- anchor not working -->
<Link to='about#someheader'>
Go to About page without jumping to #someheader section
</Link >
How to solve this (True to Sep 20)?
Use this package: https://www.npmjs.com/package/react-router-hash-link
More ideas (Related/duplicate stackoverflow Q): Using anchor tags in react-router 4 // How to use normal anchor links with react-router
Check out react-router which should solve your problem.
https://reactrouter.com/web/guides/quick-start

React: why my links that are inside React components are not working as used to work in pure HTML page?

Basically I'm trying to remake some simple web page that I have initially created with HTML and CSS to be working rather on React. I managed to redo the page to correctly display when it was moved into React, however I don't really understand why the navigation links that I have on top do not take me to the corresponding section on the same page anymore as well as why the external links to the project sites also stopped working.
Here is the project link code:
import React from "react";
export default function ProjectTile(props) {
return (
<div className="project-tile" id={props.id}>
<a href={props.href} target="_blank" id={props.link_id}>
<img
className="project_screenshot"
src={props.img_src}
alt={props.img_alt}
/>
<p className="project_name">
<span className="brackets"><</span> {props.title}{" "}
<span className="brackets">/></span>
</p>
</a>
</div>
);
}
All props are getting mapped and loaded from the array with corresponding data where each object looks like this:
{
id: "tribute_page",
link_id: "https://codepen.io/konstantinkrumin/full/PooYQbG",
img_src: "https://i.imgur.com/ynRuzOQ.png",
img_alt: "tribute_page_screenshot",
title: "Tribute Page"
}
The navigation links used are the following:
import React from "react";
export default function Navbar() {
return (
<nav id="navbar">
<a className="nav-link" href="#welcome-section">
About
</a>
<a className="nav-link" href="#projects">
Projects
</a>
<a className="nav-link" href="#contact">
Contact
</a>
</nav>
);
}
And each section they refer to have an id corresponding to the href indicated above.
Here if the link to this project on codesandbox
P.S. Everything used to work correctly when it was on HTML.
Also the contact links that seem to be set in similar way as project links are working.
Here are two things I think I found out:
In the ProjectTile.js file, replace href = {props.href} by href={props.link_id and now project opens in codepen.
About the jump link you have made in nav-bar, I think it's because of problem of codesandbox.
If you manage to make your url to https://op6gq.csb.app#projects instead of https://op6gq.csb.app/#projects. That's gonna work.
Or directly visiting https://op6gq.csb.app/#welcome-section jump link too works well.
It looks like there's no href prop. Sounds like what you want is something like
href={`#${props.id}`}
which would evaluate to href="#tribute_page" in this example.
You Have to try that your page url become:
https://op6gq.csb.app#welcome-section
Not:
https://op6gq.csb.app/#welcome-section
please attend to that / in address bar!

Not able to add a state prop in a <a> tag

I am trying to add dynamically an id into tag
<a href="/profile?id="{this.state.userInfo.id}>
it's not working. VS code keep saying that I have to add ...
Any idea ? Sorry I am newby in JavaScript and React.
Thanks
If you try to render link like /profile?id=123, where 123 is userId, then you should use template strings to insert variable value to your string.
<a href={`/profile?id=${this.state.userInfo.id}`}>
Now expression in braces would be interpreted and transformed into string with variable value.
But, if you need to make working link with react-router, you need to use Link from react-router-dom. You can find examples here
You need to use string template literal.
<a href={`/profile?id=${this.state.userInfo.id}`}>
In react we dont user the tag for routing insted we use a package/library called react-router-dom for handling routing. You can go throught the documentaion as ther are may ways for dynamic routing in React. Hope this helps. As the tag refreshes the page a may have an unlikely behavior.
you could use <Link> instead of <a> using react-router-dom
this sample is from their website
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
</nav>
</Router>```

How to create a conditional rendering of Gatsby's Link component and <a> tag for links?

From Gatsby's official docs regarding Gatsby's Link component, it states that the Link component is used only for internal links, whereas for external links, one has to use the tag.
I'm building a Button component that has inbuilt props for links. The problem is right now I have to create 2 separate Button components for internal and external links due to the limitation.
My goal is to use one freeLink component that can be used as both internal and external links
I've tried creating a subcomponent (Button) for the button, but I'm unsure of the parent component (freeLink) which requires conditional rendering. The subcomponent is as of follows:
const Button = props => (
<button className={props.btnType}>
<span>{props.text}</span>
</button>
)
This is the visual logic to what I want to achieve:
For Internal links
<freeLink intLink="/about" btnType="btn-cta" text="Read about us">
</freeLink>
...which will render...
<Link to="/about">
<button className="btn-cta">
<span>Read about us</span>
</button>
</Link>
It is relatively similar for external links
<freeLink extLink="https://google.com" btnType="btn-cta" text="Visit Our Partner">
</freeLink>
...which will render...
<a href="https://google.com">
<button className="btn-cta">
<span>Visit Our Partner</span>
</button>
</a>
I'm quite new to Javascript, Gatsby and React so I'm unsure to how to apply a conditional rendering based on props applied.
Any advice, suggestion, or direction to how to code up the freeLink component is greatly appreciated.
P.S: I've seen Conditionally Use Gatsby Link in React Compoment but the chosen answer is too complicated for me to understand, and I don't have enough points to comment to ask for further elaboration.
You could try something simple like this:
const MyLink = (href, text, ...props) => {
if (href.startsWith("http") {
return <a href={href} {...props}>{text}</a>
} else {
return <Link href={href} {...props}>{text}</Link>
}
}
Your component could return different stuff based on weather you pass it a to or a href prop:
import { Link } from "gatsby"
const freeLink = props => {
if (props.to) return <Link {...props} />
return <a {...props} />
}`

Categories

Resources