How to open a component in a new tab in React JS ?
Last Updated :
17 Dec, 2023
React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL. In this tutorial, you will understand how to open a new component in another tab while residing in the main application.
Prerequisites:
Approach to open component in new tab:
We will create two simple components, ‘FirstComponent‘ and ‘SecondComponent.’ In our main component, App.js, we’ll integrate two buttons linked to open the respective components. Subsequently, we’ll implement the mechanism to launch these components in new tabs using different routes.
Steps to create React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
 Step 3: Installing React Router package using the following command:
npm install react-router-dom
Project Structure:
Project Structure
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.17.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Example: Let’s understand the implementation through example. FirstComponent.js and SecondComponent.js are components designed to open in new tabs upon user clicks, featuring styled headings for enhanced presentation.
Javascript
import React from 'react'
import {
BrowserRouter, Routes,
Route, Link
} from 'react-router-dom'
import SecondComponent
from './SecondComponent'
import FirstComponent
from './FirstComponent'
function App() {
return (
<BrowserRouter>
{
}
<Routes>
<Route exact path= '/' element={<ul>
<br />
<li>
{
}
<Link to= 'geeks/first'
target= '_blank' >
Open First Component
</Link>
</li>
<br />
<li>
<Link to= 'geeks/second'
target= '_blank' >
Open Second Component
</Link>
</li>
</ul>}>
</Route>
<Route exact path= '/geeks/second'
element={<SecondComponent />}>
</Route>
<Route exact path= '/geeks/first'
element={<FirstComponent />}>
</Route>
</Routes>
</BrowserRouter>
)
}
export default App
|
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Your web application will be live on “http://localhost:3000”
Share your thoughts in the comments
Please Login to comment...