Achieving the functionality of making only one list item in the navbar bolded upon being clicked using React and Typescript logic

Currently, in my navigation bar, I am attempting to make only the active or clicked list item appear bold when clicked. At the moment, I can successfully achieve this effect; however, when I click on other list items, they also become bolded, while the originally clicked item does not revert back to its normal state. I am unsure of how to implement logic that would allow me to keep an item bolded only when it is clicked, and return it to its original state when not clicked. Are there any suggestions for checking the "false" condition or perhaps a better approach I could take?

Below is the code snippet for my Navlist component (which represents the list of list items):

export class Navitem extends React.Component<INavitem, IState> {

    constructor(props){
        super(props);
        this.state = {
            bolded: false
        };
      }

    makeBold = () => {
        this.setState({
            bolded: true
          })
    };

    render() {
      return (     
        <Link to={this.props.tolink} >
            <li className={this.state.bolded ? "bolded" : ""}onClick={this.makeBold}>{this.props.name}</li>
        </Link>

        );
    }
  }

And here is the code for my navbar:

const Navbar: React.FC<{}> = props => {
    return (
    <nav> 
      <div id='nav-name'>
        <h1>Matthew Fang</h1>
      </div>
      <div id='nav-space'>
        <Navitem name="Home" tolink="/" ></Navitem>
        <Navitem name="About Me" tolink="/about" ></Navitem>
        <Navitem name="Projects" tolink="/projects" ></Navitem>
        <Navitem name="Contact Me" tolink="/contact" ></Navitem>

      </div>

    </nav>

    );
}

Finally, here is the CSS style definition that applies the bold formatting to the clicked list item:

.bolded
{
font-weight: bolder;
}

Answer №1

In React, handling the active link case is already built-in. When a link is active, it automatically adds an 'active' class to it, so all you need to do is style this class with CSS.

I noticed that you are using the Link component, but the 'active' class feature is actually available for the NavLink component. You can test this out on this StackBlitz example by simply replacing Link with NavLink and checking the code :)

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

Steps to prevent submission of input field until all necessary fields and checkboxes are filled, disabled the submit button

Check out my basic web application on this sandbox link: codesandbox.io/s/eager-kalam-v1lpg I need assistance with how to prevent the submit button from being enabled until all required fields and checkboxes are filled in. I am fairly new to working with ...

Animation triggered by scrolling is not functioning/displaying div

I'm attempting to make a div fade up when it enters the viewport by using the library found at https://github.com/michalsnik/aos Unfortunately, all that seems to happen is that the div gets hidden. In the head section of my HTML file, I've refe ...

Get the data from the files in the request using request.files in Node.js

Is there a way to read the content of a file (either a txt or CSV file) that a user uploads without saving it to local storage? I know I can save the file in an upload directory and then read it from storage. However, I'm wondering if there is a way ...

Displaying the number of tasks completed compared to the total number of tasks within a JavaScript ToDo list

Currently, I'm in the process of creating a basic ToDo list using HTML, JS, and CSS. The last task on my list is to display to the user the total number of tasks and how many have been completed. For instance, if there are 3 completed tasks out of 7 i ...

jQuery Mobile panel buttons are functioning properly within a maximum width of 300 pixels

I have constructed a panel that adjusts its size based on the device's screen using responsive design techniques. The code for this panel is as follows: <div data-role="panel" data-position="right" data-display="overlay" data-theme="a" id="add-for ...

Personalizing File Selection

What is the process for customizing file uploads? <%= f.file_field :image, class: 'inputfile' %> <label for="image">Choose an image</label> I am looking to replace "choose an image" with "choose a file" ...

I'm sorry, but we were unable to locate the /bin/sh

After running a command using execSync that runs with sh, I observed the following: spawnSync /bin/sh ENOENT bin is now included in the PATH environment variable. Any ideas on this issue? ...

Is there a way to give a ReactJS button a pressed appearance when a key is pressed?

I recently developed a Drum Machine using ReactJS, but I'm facing an issue with making the buttons look like they've been clicked when I press the corresponding key. I came across a similar query on this site, however, I'm having trouble imp ...

Using JQuery to locate and substitute occurrences of HTML elements throughout my webpage

Looking for assistance with a JQuery search and replace task involving multiple instances of HTML within a specific DIV element on my webpage. Specifically, I need to change certain items in the textbox to a simpler display format. Here is a snippet of th ...

Failed to retrieve values from array following the addition of a new element

Does anyone have a solution for this problem? I recently added an element to my array using the push function, but when I tried to access the element at position 3, it wasn't defined properly processInput(inputValue: any): void { this.numOfIma ...

Issue with displaying Bootstrap 3 modal on Mozilla browser

Hello everyone, I've encountered an issue with my Bootstrap modal on Mozilla browser. Everything works perfectly on Chrome and Safari, but when I click the modal button in Mozilla, nothing happens. Here's a snippet of my code: <button type="b ...

How can we ensure that specific criteria are displayed once a selection is made?

Users have multiple options to choose from. When a user selects one option, I want to display additional options that are dependent on the initial selection. For example, if the user can select between 1 or 2 gates, upon choosing a number I will show all t ...

TRPC fails to respond to the passed configuration or variables (e.g., when enabled is set to false)

Recently started using trpc and I'm trying to grasp how to utilize useQuery (which I've previously worked with in react-query): const IndexPage = () => { const { isLoading, data, isIdle } = trpc.useQuery([ "subscriber.add", { email: ...

Using JavaScript to make an asynchronous call to the server via AJAX

Is it true that clients can block JavaScript in their browsers? If so, what impact does it have on AJAX calls - do they still function properly? ...

Instructions on extracting a random element from an array and continue removing elements from the array until it is completely empty

I am attempting to utilize either jquery or javascript to remove a random item from an array until it is empty. Each time I remove an item, I want to log it to the console. My goal is to create elements with random images from the specified array until all ...

Unlock the ability to retrieve atom values beyond RecoilRoot

In my project, I am utilizing "react-three/fiber" to contain all content within a "Canvas." Additionally, I am using Recoil's atom to store states and share them with other modules inside the "Canvas." While everything works great inside the RecoilRo ...

Creating dynamic navigation items in Next.js is a straightforward process

Seems like nextjs getStaticProps works fine in pages but not in components. However, I need to fetch API data for my components. Is there a way to achieve this? I've attempted to do this but the process is not satisfactory. const [data, setData]= ...

Is there a way to delete a field from a JSON object using JavaScript?

Searching for a way in Node.js to eliminate the date and operation fields from the database. Any suggestions on how to do this? Currently, all fields are being transferred to the FE. The collection pertains to MongoDB. collection.find({'recordType&ap ...

Typescript: searching for a specific type within an array of objects

The title may be a bit unclear, but I'm struggling to find a better way to explain it. I have a predefined set of classes from a third-party library that I cannot modify. The specific content of these classes is not relevant, as it's just for i ...

What steps can be taken to enable CORS on an existing server that was created with createServer function?

The following code snippet is what I currently have: var gqlServer =require('./server.js') var server=gqlServer() var port = process.env.PORT||5000 server.listen({port:port}, ()=> console.log(` ...