Can I use href tag in reactjs?
I want to redirect a page in reactjs and for that I want to use href tag can I do that?
Here is the code for reference:
import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
// import DoctorImg from './doctor.jpg';
class App extends Component {
render() {
return (
<Router>
<Link to = 'https://google.com/'><button>GO GOOGLE</button></Link>
</Router>
);
}
}
export default App;
You can use the Link tag available in React, internally every Link tag is converted to a anchor tag
import { Link } from 'react-router-dom';
<Link to="/Path" > Contact us </Link>
You can use a simple href if you want a simple link:
<a href={'http://google.com'}>Google</a>
If you want to link to a webpage outside of your React app, a HTML anchor tag will work great:
<a href="https://google.com" target="_blank" rel="noopener noreferrer">Click here</a>
target="_blank"
will open the webpage in a new tab. rel="noopener noreferrer"
prevents security risks, more detail here
If you want to link to a page within your React app you probably DON'T want to use the tag because this will cause your whole app to be reloaded, losing the app's current state and causing a delay for the user.
In this case you may want to use a package like react-router which can move users around your app without reloading it. See Rijul's answer for that solution.