React

Redirect to Another Page on Button Click in React - A Step-by-Step Guide

React

Redirect to Another Page on Button Click in React - A Step-by-Step Guide

Hello React enthusiasts! 🚀

Have you ever wondered how to implement a page redirection in React when a button is clicked? It's a common requirement in web development, and in this guide, we'll walk through the process with a simple and practical example.

1. Set Up a React App:

If you haven't already, create a new React app using Create React App. Open your terminal and run:

npx create-react-app my-react-app
cd my-react-app

2. Create a Button Component:

Inside the src folder, create a new file called ButtonComponent.js. In this file, define a simple button component:

// ButtonComponent.js
import React from 'react';

const ButtonComponent = ({ handleClick }) => {
  return (
    <button onClick={handleClick}>
      Click me to redirect
    </button>
  );
};

export default ButtonComponent;

3. Create a Redirection Component:

Now, create a new file called RedirectionComponent.js. This component will handle the redirection logic:

// RedirectionComponent.js
import React from 'react';
import { Redirect } from 'react-router-dom';

const RedirectionComponent = ({ redirect }) => {
  if (redirect) {
    return <Redirect to="/target-page" />;
  }
  return null;
};

export default RedirectionComponent;

4. Implement Page Component:

In your src folder, create a new file called TargetPage.js. This will be the page where you want to redirect:

// TargetPage.js
import React from 'react';

const TargetPage = () => {
  return (
    <div>
      <h1>Welcome to the Target Page!</h1>
      {/* Your content goes here */}
    </div>
  );
};

export default TargetPage;

5. Integrate Components in App.js:

Update your App.js file to integrate these components:

// App.js
import React, { useState } from 'react';
import ButtonComponent from './ButtonComponent';
import RedirectionComponent from './RedirectionComponent';
import TargetPage from './TargetPage';
import { BrowserRouter as Router, Route } from 'react-router-dom';

const App = () => {
  const [redirect, setRedirect] = useState(false);

  const handleButtonClick = () => {
    setRedirect(true);
  };

  return (
    <Router>
      <Route path="/target-page" component={TargetPage} />
      <ButtonComponent handleClick={handleButtonClick} />
      <RedirectionComponent redirect={redirect} />
    </Router>
  );
};

export default App;

6. Install React Router:

If you haven't installed React Router, do so by running:

npm install react-router-dom

7. Run Your React App:

Start your React app to see the magic in action:

npm start

Click the button, and you should be redirected to the "Target Page." 🎉

That's it! You've successfully implemented page redirection on button click in React. Feel free to customize the components and add more functionality based on your project requirements.