'How can I navigate to my html file from App.js file in same tab?
I am working on react project. I want to navigate to my HTML file from App.js without opening a new tab.ie it should open on same tab of browser
My HTML file (map.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Opens New tab</title>
</head>
<body>
<p>You came here</p>
</body>
</html>
App.js
import logo from "./logo.svg";
import "./App.css";
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<a target="_blank" href={process.env.PUBLIC_URL + "map.html"}>
{" "}
Map
</a>
</header>
</div>
);
}
export default App;
Now I am navigating by doing this in App.js
<a target="_blank" href={process.env.PUBLIC_URL + "map.html"} > Map</a>
I want to navigate to my HTML page without opening the new tab and also would like a way to know how can I navigate back to previous page without clicking back button of browser.
Solution 1:[1]
You need to remove target="_blank" attribute from the <a> element.
import logo from "./logo.svg";
import "./App.css";
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<a href={process.env.PUBLIC_URL + "map.html"}>
{" "}
Map
</a>
</header>
</div>
);
}
export default App;
Solution 2:[2]
if you are trying to route to map.html onclick then you are doing in wrong way you can use react-router-dom
instead of creating map.html you should create map.js in src folder and import it to App.js
for routing in react recommended way is react routing
map.js (instead of map.html)
import React from "react";
const Map = () =>{
return <p>You came here</p>
}
export default Map;
you don't have to write head tags and other everywhere
now in App.js
import React from "react";
import Map from "./map"; //this is map.js
const App = () =>{
return <Map/>
}
export default App;
this is without routing... now with routing in App.js
import React from "react";
import Map from "./map"; //this is map.js
import {
BrowserRouter as Router,
Route,
Switch,
Link
} from "react-router-dom";
const App = () =>{
return(
<>
<Link to="/map">Map</Link>
<Router>
<Switch>
<Route path="/map" component={<Map>}/>
</Switch>
</Router>
</>
)
}
export default App;
when you will click on map it we show content of map.js page in same tab
Note: react-router-dom used here is version 5 latest is version 6. read reactjs official documentation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Posandu |
| Solution 2 | sarfaraj shah |
