Properties of `MemoryRouter`
- `initialEntries`
The `initialEntries` property in `MemoryRouter` allows you to specify an array of initial URL paths when the router is first rendered. Each path in this array represents a location within the virtual memory history of the router. By default, if `initialEntries` is not provided, it defaults to [“/”] (a single entry at the root URL` /`).
<MemoryRouter initialEntries={['/', '/about', '/contact']} initialIndex={0}>
{/* Routes */}
</MemoryRouter>
- `initialIndex`
The `initialIndex` property in `MemoryRouter` specifies the index of the active entry (URL path) within the `initialEntries` array when the router is first rendered. If `initialIndex` is not provided, it defaults to the last index of `initialEntries`.
<MemoryRouter initialEntries={['/', '/about', '/contact']} initialIndex={1}>
{/* Routes */}
</MemoryRouter>
Example 2: Below example demonstrates the usage of different properties in MemoryRouter.
// src/App.js
import React from 'react';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
const Step1 = ({ nextStep }) => {
const handleNext = () => {
nextStep('/step2');
};
return (
<div>
<h2>Step 1: Personal Information</h2>
<button onClick={handleNext}>Next</button>
</div>
);
};
const Step2 = ({ prevStep, nextStep }) => {
const handlePrev = () => {
prevStep('/step1');
};
const handleNext = () => {
nextStep('/step3');
};
return (
<div>
<h2>Step 2: Address Information</h2>
<button onClick={handlePrev}>Previous</button>
<button onClick={handleNext}>Next</button>
</div>
);
};
const Step3 = ({ prevStep }) => {
const handlePrev = () => {
prevStep('/step2');
};
const handleSubmit = () => {
alert('Form submitted successfully!');
};
return (
<div>
<h2>Step 3: Review and Submit</h2>
<button onClick={handlePrev}>Previous</button>
<button onClick={handleSubmit}>Submit</button>
</div>
);
};
const App = () => {
const nextStep = (path) => {
window.location.href = path;
};
const prevStep = (path) => {
window.location.href = path;
};
return (
<MemoryRouter initialEntries={['/step1']} initialIndex={0}>
<div>
<Routes>
<Route path="/step1" element={<Step1 nextStep={nextStep} />} />
<Route path="/step2" element={<Step2 prevStep={prevStep} nextStep={nextStep} />} />
<Route path="/step3" element={<Step3 prevStep={prevStep} />} />
</Routes>
</div>
</MemoryRouter>
);
};
export default App;
Output:
Explain MemoryRouter in concept of React Router
In React applications, routing is a crucial aspect that enables navigation between different components based on the URL. React Router is a popular library used for managing routing in React applications. One of the components provided by React Router is `MemoryRouter`, which offers a unique way to handle routing without manipulating the browser’s URL.
Prerequisites: