In React, I'm unable to navigate to a different page

My English may not be the best, but I am working on creating a Login Page. The issue I'm facing is that when I click the Login button, I want to navigate to the Home Page I designed using React. However, whenever I try to implement Link or Route commands for redirection, the screen turns completely white without any error messages. Interestingly, everything functions properly once I remove the code related to redirection.

import React from "react";

import 'bootstrap/dist/css/bootstrap.min.css';
import './App_login.css'
import logo from "./assets/resim.png"
import { BrowserRouter, Route, Routes, Link } from 'react-router-dom';
import Sifre from './App_sifre'
import Anasayfa from './App_anasayfa'
import Login from './App_login'


function App() { 
  return (    
    <body className="bg">   
      <div className="container" >
        <div className="card card-body mt-5 pb-5 shadow p-3 mb-5 bg-body rounded ">

        <BrowserRouter>
      <div>
        
        <Routes>
        <Route path='/' element= {<Login />} />
        <Route path='/sifre' element= {<Sifre />} />
        <Route path='/anasayfa' element= {<Anasayfa />} />
        </Routes>
      </div>
    </BrowserRouter>
         
          <h2 className="text-center text-info ">DMS Planlama Sistemi</h2>
          <div className="row mt-5 pb-5">
            <div className="col-lg-6 col-sm-12 mb-5">
              <img src={logo} alt="login" className="img-fluid" />
            </div>
            <div className="col-lg-6 col-sm-12">
              <form>
                <div className="form-group">
                  <label htmlFor="email">Kullanıcı Adı:</label>
                  <input type="email" className="form-control" placeholder="Kullanıcı adınız" id="email" />
                </div>
                <div className="form-group">
                  <label htmlFor="pwd" style={{marginTop: '15px'}}>Şifre:</label>
                  <input type="password" className="form-control" placeholder="şifreniz" id="pwd" />
                </div>
                <div className="form-group form-check">
                  <label className="form-check-label">
                    <input className="form-check-input" type="checkbox" /> Beni Hatırla
                    <label><a href="şifremi unuttum/şifre yenileme.html" to="/sifre" style={{marginLeft: '30px'}}>Şifremi unuttum</a></label>
                  </label>
                </div>
                <button type="submit" className="btn btn-primary" href="anasayfa/anasayfa.html">
                  <Link to="/anasayfa"> Login</Link>
                </button>
              </form>
            </div>
          </div> 
        </div>
      </div>
  </body> 
  );
}

export default App;

I've attempted to utilize Link and Route commands by importing the necessary files for routing purposes.

Answer №1

Avoid using the body tag as it already exists in the index.html file. The path and component pairing for routes may seem unusual, consider using "/" for the homepage and "/login" for the login component within the <App /> component :

import React from "react";

import 'bootstrap/dist/css/bootstrap.min.css';
import './App_login.css'
import logo from "./assets/resim.png"
import { BrowserRouter, Route, Routes, Link } from 'react-router-dom';
import Sifre from './App_sifre'
import Anasayfa from './App_anasayfa'
import Login from './App_login'


function App() { 
  return (    
     <>
       <BrowserRouter>
         <Routes>
          <Route path='/' element= {<HomePage />} />
          <Route path='/login' element= {<LoginPage />} />
          <Route path='/sifre' element= {<Sifre />} />
          <Route path='/anasayfa' element= {<Anasayfa />} />
         </Routes>
      </BrowserRouter>
     </>

Considering this appears to be a login form, it is recommended to create a "/login" route with the <LoginPage /> element. Additionally, avoid using the Link tag inside the form button as it deviates from standard practice. Forms are typically used for submission, not navigation. If you intend to navigate using Link, place it outside the form structure. Below is the content of the <LoginPage /> component:

export default function LoginPage () {
 return (
      <div className="container" >
        <div className="card card-body mt-5 pb-5 shadow p-3 mb-5 bg-body rounded ">
          <h2 className="text-center text-info ">DMS Planlama Sistemi</h2>
          <div className="row mt-5 pb-5">
            <div className="col-lg-6 col-sm-12 mb-5">
              <img src={logo} alt="login" className="img-fluid" />
            </div>
            <div className="col-lg-6 col-sm-12">
              <form>
                <div className="form-group">
                  <label htmlFor="email">Kullanıcı Adı:</label>
                  <input type="email" className="form-control" placeholder="Kullanıcı adınız" id="email" />
                </div>
                <div className="form-group">
                  <label htmlFor="pwd" style={{marginTop: '15px'}}>Şifre:</label>
                  <input type="password" className="form-control" placeholder="şifreniz" id="pwd" />
                </div>
                <div className="form-group form-check">
                  <label className="form-check-label">
                    <input className="form-check-input" type="checkbox" /> Beni Hatırla
                    <label><a href="şifremi unuttum/şifre yenileme.html" to="/sifre" style={{marginLeft: '30px'}}>Şifremi unuttum</a></label>
                  </label>
                </div>
                  <button type="submit" className="btn btn-primary">
                    submit
                  </button>
              </form>
            </div>
          </div> 
        </div>
      </div>
)
}

One possible issue could be with the import-export configuration of the components:

import Sifre from './App_sifre'
import Anasayfa from './App_anasayfa'
import Login from './App_login'

Review any errors that may appear in the Chrome console for further insight.

Answer №2

To start, modify your index.js by adding the following code snippet. Your code may vary slightly, but make sure to include the line

import { BrowserRouter } from "react-router-dom";
and wrap the <App /> component with
<BrowserRouter>  </BrowserRouter>
tags.

Your updated file should resemble something like this:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";

import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>
);

Next, update your App.js as follows: (1/ Removed the <BrowserRouter> section and moved it to index.js. 2/ Made adjustments to the button with the Link to=" ".)

import React from "react";
import 'bootstrap/dist/css/bootstrap.min.css';
import './App_login.css'
import logo from "./assets/resim.png"
import { Route, Routes, Link } from 'react-router-dom';
import Sifre from './App_sifre'
import Anasayfa from './App_anasayfa'
import Login from './App_login'

function App() { 
  return (    
    <body className="bg">   
      <div className="container" >
        <div className="card card-body mt-5 pb-5 shadow p-3 mb-5 bg-body rounded ">

         // Rest of the App.js code remains the same

<button type="button" className="btn btn-primary">
  <Link to="/anasayfa">Login</Link>
</button>

Please note that I replaced the previous button implementation with the above code to ensure proper navigation using the Link component. If you intended to navigate to / instead of /anasayfa, you can adjust the path in the Link component accordingly.

I also updated the button type attribute from type="submit" to type="button".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on accessing files saved in a one-to-many connection using Mongoose

I have multiple Schemas set up for Shops and Products. Each shop can have a variety of products, and I currently have 5 different shops with their own unique product listings. While I am able to save the products and find their corresponding IDs within eac ...

Error loading resource: The server returned a 404 status code indicating the requested resource was not found in the Node.js socket.io

My challenge involves setting up a server with Node.js and socket.io which starts perfectly fine. However, when I attempt to access my server's site through the browser, it shows "Cannot Get /" and in the console, an error appears saying "Failed to Lo ...

Sequencing asynchronous functions in Angular: Ensuring one function runs before another

When working with a save function that requires you to call another function to retrieve the revision number and make an API call, both of which are asynchronous in nature, how can you ensure one function waits for the other to execute? $scope.getRevision ...

An error of TypeError is being encountered in AngularJS

Hello, I am new to creating mobile apps with Ionic and Angular. Currently, I have a simple login form and a corresponding login button that triggers a controller. Here is the code snippet for the controller: angular.module('starter.controllers', ...

Is there a method in React Native to include the "share" icon in my drawer instead of a button?

How can I add a "share" icon to my drawer? I attempted to insert an icon using <Ionicons name="md-share" size={24} color="black" /> instead of a Button. However, when I do this, the icon is displayed without any title, unlike what I see in the sett ...

Request financial data from AlphaVantage using PHP

I'm currently working on utilizing the alphavantage API to retrieve currency exchange information. In order to obtain the desired data, I am using the following query URI: https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_cu ...

Enhancing the Value of BehaviorSubject with Object Assign in Angular using Typescript and RxJs

I have a user object stored as a BehaviorSubject which is being observed. I need help figuring out how to detect if a specific value within my user object has changed. I've noticed that my current implementation doesn't seem to work correctly, a ...

Is there a way to determine if a browser's network activity is inactive?

Within an angularJS application, a noticeable delay can be experienced between the user and the server (potentially due to limited bandwidth), resulting in a wait time of approximately 2-500ms when loading a new page. I am considering implementing a metho ...

JavaScript: Creating Custom IDs for Element Generation

I've been developing a jeopardy-style web application and I have a feature where users can create multiple teams with custom names. HTML <!--Score Boards--> <div id="teamBoards"> <div id="teams"> ...

The Angular @Input directive may be prone to receiving inaccurate model data

I am currently working on setting up @Input for my component using a model that resembles the following: interface Car { sail?: never tires: number weight: number } interface Boat { tires?: never sail: boolean weight: number } exp ...

AngularJS - Sending event to a specific controller

I am facing an issue with my page where a list of Leads each have specific actions that are represented by forms. These forms can be displayed multiple times on the same page. Each form has its own scope and controller instance. After submitting a form, an ...

Tips for accurately obtaining row counts from a dynamic table when the `<tr>` numbers are constantly fluctuating

One issue that I encountered as a tester involved verifying the total number of rows on a dynamic table. Despite having 50 rows in the table, the HTML only displayed a maximum of 22 <tr>. This discrepancy caused my automation code to return an incorr ...

Animating transitions on a dynamic Bootstrap navbar using jQuery

I have the code attached here, and I successfully changed the color of the navbar and logo when scrolling down. However, I am looking to add a transition effect when this change occurs. I experimented with various transition options in CSS, but unfortunat ...

Nested navigation in Bootstrap

I am currently working on creating a multilevel menu using Twitter Bootstrap. Check out the code here Below is the snippet of HTML code: <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> ...

Ways to Read JSON without Using jQuery

Exploring JSON Feed and Autocomplete As I delve into the realm of creating an autocomplete feature that fetches data from a JSON feed, I encounter a setback. Despite successfully parsing the JSON data using json2.js through JSON.parse, I am confronted wit ...

The function of jQuery .click() not triggering on elements within msDropDown

I'm having difficulty implementing jQuery on an Adobe Business Catalyst site. The HTML snippet below shows the structure: <div class="banner-main"> <div class="banner-top"> <section class="banner"> <div class="catProd ...

problem encountered while attempting to transmit data to multer in React

I was attempting to upload an image to the backend using Multer. I have reviewed the backend code multiple times and it appears to be correct. Could there be an issue with my front-end code? Here is a POST code snippet: const response = await fetch(' ...

Save the session ID in localStorage instead of a cookie

After successfully logging into my PhoneGap app, everything functions properly. I can send requests within the current session and am authenticated. However, if I completely close the app and reopen it, my session is lost. The cookie containing connect.sid ...

Change the background image when hovering over an element with vanilla JavaScript by utilizing data attributes

I would like to be able to change the background image of a <div> when hovering over a link. Initially, the <div> should not have a background image when the page loads for the first time. This is my current setup: <div class="background"& ...

Tips for modifying hover effects using jQuerystylesheet changes

I attempted running the following code snippet var buttonElement = $('<button>Button</button>'); $('body').append(buttonElement); buttonElement.hover().css('background-color', 'red'); Unfortunately, the ...