What is the reason for adding CSS styles to a JavaScript file without importing them?

/Navbar.js/

import './navbar.scss';
import {FaBars, FaSearch} from "react-icons/fa";
import { useState } from 'react';

function Navbar(){
    const [hide,sethide] = useState(true);
    const barIcon = document.querySelectorAll(".link-hide");
    const showIcon = () => {    
        sethide(!hide);
        if(!hide){
            console.log("hello");
            barIcon.forEach(baricon => {
                baricon.style.display = "block";
            })
        }
        else{
            console.log("hi");
            barIcon.forEach(baricon => {
                baricon.style.display = "none";
            })
        }
    }
    return (
        <div className='navbar'>
            <ul className='link-group'>
                <li className='hello'>Home</li>
                <li className='link-hide'>Band</li>
                <li className='link-hide'>Tour</li>
                <li className='link-hide'>Contact</li>
                <li className='link-hide'>More</li>
            </ul>
            <div className='align-icon'>  
                <FaSearch className='search-icon'/>
                <FaBars className='bar-icon' onClick={showIcon}/>
            </div>
            
            
        </div>
    );
}
export default Navbar;

===========================================

/Navbar.scss/

@import url('https://fonts.googleapis.com/css2?family=Freehand&family=Josefin+Sans:wght@200;300;400&family=Montserrat:wght@200;300;400;600&family=Silkscreen&display=swap');

*{
    padding : 0px; 
    margin : 0px;
    box-sizing: border-box;
    text-align: left;
    text-decoration: none;
    list-style-type: none;
    font-family: 'Montserrat', sans-serif;
    font-weight: 600;
    color : white;
}
.navbar{
    background : black;
    display: flex !important;
    position: relative;
    grid-template-columns: 50% 50%;
    position: fixed;
    width: 100%;
    ul{
        
        li{
            padding: 20px 25px;
        }
        li:hover{
            background-color: gray  ;
        }
    }
    .align-icon{
        align-self: center;
        position: absolute;
        right: 0px;
        padding: 21px 25px;
    }
    .align-icon:hover{
        
        background-color: gray;
    }
}

@media (max-width: 570px){
    .search-icon{
        display: none;
    }
    .align-icon{
        align-self: flex-start !important;
        
    }
    .bar-icon{
        display: block;
    
    }
    
    .link-group{
        display: block;
        width: 100%;
        
        .link-hide{
            display: none;
        }
        li:nth-child(1){
            display:inline-block;
        }
        
    }

}
@media (min-width: 571px){
    ul{
        display: flex;
    }
    .search-icon{
        display: block;
    }
    .bar-icon{
        display:none;
    }
    .link-hide{
        display: block !important;
    }
}

============================================

/Home.scss/

@import url('https://fonts.googleapis.com/css2?family=Freehand&family=Josefin+Sans:wght@200;300;400&family=Montserrat:wght@200;300;400;600&family=Silkscreen&display=swap');

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    color:white;
    font-family: 'Montserrat', sans-serif;

}
.show-image{
    position: relative;
    .pos-absolute{
        width: 100%;
        position: absolute;
        bottom: 10%;
        h1,p{
            display: flex;
            justify-content: center;
        }
    }
}
.head-text{
    font-size: 20px;

}

I am currently developing a React-based website and encountered an issue when trying to implement the .show-image class in Home.scss. It seems that this class is causing my Navbar component to disappear from the webpage. When I remove the .show-image class, the Navbar reappears as expected. Seeking guidance from experienced developers on how to resolve this issue. Thank you for your assistance.

Answer №1

One key thing to note about the DOM in react is that it is not fully-loaded when the component is initially rendered. This means you cannot use document.querySelectorAll; instead, utilize a Hook called "useRef." Here's the code snippet with the necessary fix:

import React, { useRef } from 'react';
import './navbar.scss';
import {FaBars, FaSearch} from "react-icons/fa";
import { useState } from 'react';

function Navbar() {
  const [hide, setHide] = useState(true);
  const linkHideElements = useRef(null);

  const showIcon = () => {
    setHide(!hide);
    if (!hide) {
      linkHideElements.current.forEach(element => {
        element.style.display = 'block';
      });
    } else {
      linkHideElements.current.forEach(element => {
        element.style.display = 'none';
      });
    }
  };

  return (
    <div className="navbar">
      <ul className="link-group">
        <li className="hello">Home</li>
        <li className="link-hide" ref={linkHideElements}>Band</li>
        <li className="link-hide" ref={linkHideElements}>Tour</li>
        <li className="link-hide" ref={linkHideElements}>Contact</li>
        <li className="link-hide" ref={linkHideElements}>More</li>
      </ul>
      <div className="align-icon">
        <FaSearch className="search-icon" />
        <FaBars className="bar-icon" onClick={showIcon} />
      </div>
    </div>
  );
}

export default Navbar;

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

Ways to extract information from a table cell located next to a table cell with colspan

As a beginner in web scraping, I am gradually making progress. However, I'm facing a tough challenge with this particular task. My goal is to extract data from the ESPN NBA boxscore website: I aim to scrape the names of players labeled as "DNP" (Did ...

Blending images together can obscure surrounding elements

Is there a way to make two images crossfade on hover without hiding the text underneath? I need the text to show below the image, not behind it. Any suggestions on how to solve this issue? #center { text-align: center; } #under { text-align: cente ...

Sorting elements in an array using jQuery is a common task that can be easily accomplished

Query: I am faced with a challenge in handling a table where rows are dynamically added upon button clicks. To allow users to rearrange the rows, I have incorporated the jquery-ui sortable() function for sorting purposes. Consider the following scenario: ...

Generate a new entity using a previously imported model with A-Frame

I have successfully imported a house model in .gltf format. I am now trying to extract the floor object from this model and turn it into its own individual a-frame entity for future reference. This is necessary so that I can designate the floor as the coll ...

Using WebRTC on a shared hosting environment (with SSH access) without the need for nodejs, ideally implemented in PHP

As I was exploring ways to integrate webRTC into a website that I am creating on shared hosting, I stumbled upon this GitHub repository by nielsbaloe. It has been incredibly helpful in establishing a basic connection. This particular code snippet appears ...

Passing API Json list to navigation component in NextJS is proving to be quite tricky

I am currently facing a challenge in creating a dynamic navigation component. I need to fetch navigation items from a REST API generated by the backend, which in my case is Django. The API endpoint correctly displays the list of entries, as shown below. H ...

What is the best way to manage Page Refresh using Angular.js?

I recently followed the tutorial at http://scotch.io/bar-talk/setting-up-a-mean-stack-single-page-application This guide went over controllers and services using angular.js for a single-page application. However, when I try to directly access /pageName o ...

Tips for maintaining the default arrow icon for HTML select elements

While styling a drop down in Firefox on Mac OS X, I noticed that the arrow changes from the standard look to an unattractive downward arrow. How can I maintain the standard form element with the appealing up and down arrows, instead of the unsightly downwa ...

Bootstrap 4.0. When it comes to buttons, they seem to have trouble cooperating with other DIV elements

Today is my first time seeking help on StackOverflow: I'm encountering an issue with my website where the floating arrow at the bottom of the page is obstructing my ability to click on buttons. Whether it's a Bootstrap button or HTML button, non ...

React.js: The function useDef has not been defined

Attempting to create a React.js calculator application, my initial step was to delete the entire src folder and replace it with a new one containing the necessary elements for the web app. Here is the content of the index.js file: import React,{ useEffect, ...

Having trouble sending state values through react_router4

I am a newcomer to react JS and struggling with passing values through the this.props.history.push() method in react router. Here are my react files: App.js import React, { Component } from 'react'; import logo from './logo.svg'; impo ...

Creating manageable CSS styles for a wide variety of themes

I need to add themes to a web application that allows users to switch between them seamlessly. The designers want a variety of font colors and background colors, around 20 in total. Is there a way to achieve this without creating multiple .css files, which ...

Adjusting the width of a DIV element within a table cell

In my ASP.NET application, I am facing an issue with table column widths not rendering as expected in the browser. Despite setting the column width to 100px, it appears as either 96px or 108px. The problem seems to be related to having a div inside the th ...

Upon the initial hover, the data added to the title tag following an Ajax call is not appearing

I am currently working on an ajax request that retrieves information such as username, email, and user_id. Once the ajax call is successful, I use jQuery to append this data to the title tag. The main issue I am facing is that the data is only displayed af ...

Deploying a node application and a Java JAR to Heroku

Currently in the process of developing a node.js app, with plans to host it on Heroku. The only complication is that the app depends on a jar file that needs to be executed. Can Heroku support running Java for this purpose? ...

Steps to remove information from a database using PHP, AJAX, and vanilla JavaScript (without jQuery)

I am facing an issue with deleting data from my database. Whenever I click on the delete button, it deletes the first row instead of the intended row. Below is my PHP code: <?php $connect = mysqli_connect("localhost","root","","abu"); if($conne ...

Do you need to finish the Subject when implementing the takeUntil approach to unsubscribing from Observables?

In order to prevent memory leaks in my Angular application, I make sure to unsubscribe from Observables using the following established pattern: unsubscribe = new Subject(); ngOnInit() { this.myService.getStuff() .pipe(takeUntil(this.unsubscr ...

chart for visualizing two rows with matching IDs and dates

I have been attempting to accomplish the following two scenarios: 1) When both ID and dates are the same in the chart, but the descriptions differ, I want to display them on separate lines. 2) If there is not enough room to show the row label, I would li ...

Is it possible for an object to receive notifications when a component object undergoes changes in Angular 2/4?

When working with Angular components, it's possible to pass a variable or object as @Input(). The component will be notified whenever the value of this input changes, which is pretty cool... I'm currently developing an application that features ...

How can I use Angular to toggle a submenu based on a data-target attribute when clicked?

Struggling to implement a functionality using ng-click to retrieve the data-target attribute of a clicked angular material md-button, in order to display the submenu when a topic is clicked on the sidenav. The navigation structure consists of md-list with ...