I am having trouble getting React to properly render my components when using the router

As a newcomer to React, I am currently working on my first website. Despite researching online for solutions, I have not been able to find an exact answer to my particular issue.

The layout of my components is in a scroll-down style (portfolio), but when I try to navigate, for example, to my contact component, it does not render unless I refresh the page. Additionally, instead of smoothly scrolling down to the component, it abruptly pops up at the top. (I hope this description is clear).

App Function:

import { useState } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import './App.css';
import Contact from './Components/Contact/Contact';
import Form from './Components/FormArea/Form/form';
import Introdoction from './Components/Introdoction/Introdoction';
import NavBar from './Components/NavBar/NavBar';
import NavigationBar from './Components/NavigationBarHeader/NavigationBar/NavigationBar';
import Portfolio from './Components/Portfolio/Portfolio';
import Routing from './Components/Routing/Routing';
import Skills from './Components/Skills/Skills';

function App() {
 
  return (
    <BrowserRouter>
    <Switch>
    <div className="App">
      
      <NavigationBar/>
     
      <section className="section">
      
        <Route path="/contact" component={Contact} exact/>
        <Introdoction/>
        <Portfolio/>
        <Skills/>
        {/* <Contact/> */}
        <Form/>
      </section>
    </div>
    </Switch>
  </BrowserRouter>
  );
  
}

export default App;

I am focusing on configuring the "Contact" component for this specific example.

Menu/Navbar Component:

import { Component, MouseEventHandler } from "react";
import {MenuItems} from "../MenuItems/MenuItems";
import "./NavigationBar.css";
import icon from '../../../Assets/icon.png'
import  {Button}  from "../Button/Button";
import { NavLink, Redirect, Route, Switch, useHistory } from "react-router-dom";
import Contact from "../../Contact/Contact";

class NavigationBar extends Component {
    state = {clicked : false}

    handleClick = () => {
        this.setState ( { clicked: !this.state.clicked } );
      };

    public render(): JSX.Element {
        return (
          
            <nav className="NavbarItems ">
                <img className="navbar-logo"src={icon } />
                <div className="menu-icon" onClick={this.handleClick}>
                    <i className={this.state.clicked ? 'fas fa-times' : 'fas times'}></i>

                </div>

                <ul className={this.state.clicked ? 'nav-menu active' : 'nav-menu'}>

                    {MenuItems.map((item,index) => {
                        return (

                            <li key={index}>

                        <NavLink to={item.url} className={item.cName} >{item.title} </NavLink>
                        
                            </li>
                        )
                    })}

                    
                </ul>
                <Button>Sign up</Button>
               
            </nav>
        );
    }
}

export default NavigationBar;

ItemMenu Component:

import { NavLink } from "react-router-dom";
import "./MenuItems.css";

export const MenuItems = [
    {
        title: 'Home',
        url: '/Home',
        cName: 'nav-links'
    },
    {
        title: 'Introduction',
        url: '/introduction',
        cName: 'nav-links'
    },
    {
        title: 'Skills',
        url: '/skills',
        cName: 'nav-links'
    },
    {
        title: 'Projects',
        url: '/projects',
        cName: 'nav-links'
    },
    {
        title: 'Contact',
        url: '/contact',
        cName: 'nav-links'
    },
];

If more information is necessary, feel free to ask. Hopefully, I have clearly explained my problem.

Thank you.

Answer №1

It seems like you're looking to have a single page layout where all the content is stacked vertically and clicking on a link will smoothly scroll you down to that section. In this scenario, you can achieve this effect by using the following code snippet:

<a href="#contact"></a>
<Contact id="contact" />

Using react-router may not be necessary since it creates new sub pages which might not align with your desired layout (if I understood your requirements correctly).

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

Utilizing Environment Variables to Retrieve Value in Your React Application

My React application is utilizing npm for building. I am currently attempting to retrieve the CURRENT_ENV value that has been injected via a configMap in the AKS cluster. To accomplish this, I have created a run.sh script which serves as the ENTRYPOINT i ...

What can be done to ensure that two separate react-native Picker components do not interfere with each other's

Encountering an issue with two Pickers in a react-native View. Whenever I select a value in one Picker, it causes the other Picker to revert back to its initial item in the list. It seems like the onValueChange function is being triggered for both Pickers ...

Leveraging the power of Framer Motion in combination with Typescript

While utilizing Framer Motion with TypeScript, I found myself pondering if there is a method to ensure that variants are typesafe for improved autocomplete and reduced mistakes. Additionally, I was exploring the custom prop for handling custom data and des ...

Utilizing material-ui with Autocomplete featuring various value and option types

In my code, I am looking to store only an option's ID in a value For autocomplete functionality, the value's type and the option's type need to be the same My solution was to change the value in onChange, which worked successfully However ...

"Clicking on a hash link will refresh the current page

I have a snippet of code embedded on external websites that loads HTML, CSS, and JavaScript using a <script> tag. Within the code is a JavaScript function that triggers when a specific link is clicked: <a href="#">?</a> If there are Ja ...

Rearranging components in React does not automatically prompt a re-render of the page

I'm currently working on a project to display the update status of my Heroku apps. The issue I encountered was that the parent component (Herokus) was determining the order, but I wanted them sorted based on their update dates starting from the most r ...

Using a single jQuery script, implement multiple modals on a webpage that are responsive on both desktop and mobile devices

My Modal is functioning well on desktop, but I'm facing an issue on mobile where the screen doesn't close when clicking outside the modal area. Is there a way to solve this for mobile without adding the 'X' button to close it? I attem ...

Achieving Perfect Alignment for Absolutely Positioned Divs in

I'm currently facing an issue where the image I'm trying to center horizontally also moves the parent div downward when I try to vertically center it using top-margin. This is not the desired outcome. If you'd like to see what I mean, I&apo ...

The onClick function for a button is not functioning properly when using the useToggle hook

When the button is clicked, it toggles a value. Depending on this value, the button will display one icon or another. Here is the code snippet: export const useToggle = (initialState = false) => { const [state, setState] = useState(initialState); c ...

Propagating Exceptions in React Native

Check out this function geolocate() that asynchronously calls a geolocation service in React Native. The issue at hand is that when an error occurs within the geolocationError() function, it doesn't get passed up to the parent geolocate(), resulting ...

Adding a background color to the body of your PHP and HTML email template is a simple way to enhance

I am currently using a confirmation email template with a white background, but I want to change it to gray. However, I'm unsure how to update the PHP file containing the email function below: $headers = "From: " . stripslashes_deep( html_entity_deco ...

Installing material-ui using npm does not always result in getting the most up-to-date version

I'm currently facing a dilemma with an abandoned project that serves as the admin tool for my current project. The Material-UI version used in this project is 0.19.4. However, when I remove the dependency from my package.json file and execute npm inst ...

Arranging navigation links around a centrally positioned navigation brand using Bootstrap

Struggling to create a Navbar using bootstrap right now. The issue I'm facing is with centering the nav-links on both sides of the nav-brand. Here's my HTML code: <nav class="navbar navbar-expand-sm navbar-light "> <button class="na ...

A straightforward guide on utilizing data-attributes to achieve a linear-gradient background

considering the following input .prettyRange { -webkit-appereance: none; } .prettyRange::-webkit-slider-runnable-track { background: -webkit-linear-gradient(right, #fff 0%, green 50%, #fff 0%); } <input class="prettyRange" type="range" name="cap ...

Break the line after every space in words within an element

I have a table/grid view with two words in the <td> like "C2 Sunday". I need a line break after C2 so that it appears as: C2 Sunday Is there a way to achieve this? Please assist me with this issue. Currently, it is showing as "C2 Sunday" and I wou ...

Website Responsiveness - inquiries for all needs

My first responsive website project has hit a roadblock, as I struggle to understand how to implement media queries effectively. Here's a snippet of my code... <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/x ...

Generating an HTML table using data from a specified URL source

As a beginner, I am working on creating a dashboard for my smart home using OpenHab2.0. One of the key features I want to include is a widget that displays the next 5 tram departures from my local stop. The table structure for this information looks like: ...

Using AngularJS to retrieve DOM elements within a directive's controller

Currently, I am in the process of creating a custom image carousel directive using only AngularJS and no additional libraries. simpleCarousel.$inject = []; function simpleCarousel() { var directive = { restrict: 'E', templat ...

MUI TablePagination does not support the onRowsPerPageChange event

The MuiTable code provided below functions correctly for the most part. It displays the table content with the proper column headers, paginates every 5 rows, and enables navigation through pages using 'Previous' (<) and 'Next' (>) ...

What are the best methods for personalizing content within material-table in React?

Is there a way to include an icon in front of each item based on its data from a specific column? Currently, I am using a JavaScript array to display the static information, but I am unable to personalize it. This is what I am currently utilizing: <Ma ...