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

A combination of Tor Browser, Selenium, and Javascript for

I have been attempting to use selenium with Tor, but unfortunately it is not functioning correctly. I have come across a library that allows for this functionality, however, it appears to only work with Python. Is there a way to accomplish this using Jav ...

Click on the input to add or remove a value

I have written a code where, on click, I insert an email address into a field. However, what I am trying to achieve is that upon the next click on the same field, it will remove the email if one already exists in the input. Below is my current code snippe ...

Tips on creating a responsive material-ui for reactjs applications

Can you recommend a tool to use for designing react components based on the material used? You might want to check out http://www.material-ui.com - it's great for reactjs, although it lacks a responsive grid feature You could also consider https://g ...

What is the process for uploading an image with redux toolkit query?

Below is the code snippet I am using: <input type="file" onchange={fileChange} accept="image/*" /> function fileChange({target: { files }}){ const file = files[0] uploadFile(file) }); const imgBB = createApi({ baseQuery: fetch ...

Having trouble with integrating @rneui or react-native-vector-icons in React Native projects? You're not alone - many users have reported errors and project breakages

I have recently delved into the world of react native, although I am well-versed in other programming languages. My projects seem to be plagued by an abundance of errors, especially when it comes to installing new packages. While I have managed to workarou ...

Unnecessary spacing found within the side navigation menu

Recently, I decided to practice my web development skills by creating a basic webpage using flexbox for the topnav and CSS Grid 12 column layout for the main content. Everything was going smoothly until I encountered some extra whitespace in the sidenav se ...

What is the process for obtaining the hashed password to store in my database?

Despite being able to run a test in Postman, I am facing difficulties with passing my hashed password into the DB correctly. const express = require("express"); // const helmet = require("helmet"); const { User } = require("./db/mo ...

Deciphering the LocalDate and nested object array in an AJAX response

Seeking assistance, looking for solutions to two problems. Firstly, how can I display LocalDate in an ajax response? And secondly, how do I iterate over a list of Custom objects received in the ajax response? I am passing a List of Custom Objects and Loca ...

Is there a quick way to use AJAX in Rails?

By using the remote:true attribute on a form and responding from the controller with :js, Rails is instructed to run a specific javascript file. For instance, when deleting a user, you would have the User controller with the Destroy action. Then, you woul ...

Thymeleaf causing Spring IO POST form to redirect to incorrect URL

One of the challenges I'm facing while coding a website is with a form for uploading files. Ideally, when accessing the URL http://localhost:8080/uploadRevision/{docId}, it should lead to http://localhost:8080/uploadRevisionLanding and then redirect b ...

Encountering an ETIMEDOUT error while sending out large (10k) post requests with axios.all in a Node

I have implemented axios.all to make simultaneous post calls. Below is the code snippet: let postUrls = []; data.forEach(item => { const itemData = { stream: stream_name, key: item.serialNumber, addr ...

Switch the application's theme dynamically by calling an API after a user clicks a button

Recently, I've been delving into the world of next.js and react, but I've encountered a roadblock that's been giving me some trouble. I need my application to dynamically change its theme after making an API call. The stack I'm working ...

Whenever the user hits the "Enter" key, a new element will be generated and added to the bottom of an existing element

I am in need of creating a new element at the end of another element. For instance, let's say I have this element: <div id="elmtobetrig">Element that should be followed by another element when the user hits enter after this text. <! ...

Steps to obtain an Element binding from a Svelte component

Is it possible to retrieve the bounding client rect of an anchor element? I typically mark this using the syntax bind:this={someVariable}. However, when I add this code to a Svelte component, I receive a different object that Svelte uses to represent a c ...

Using the async.waterfall function in an Express application

Query: I'm encountering an issue with my express.js code where, upon running in Node.js, an empty array (ganttresult) is initially displayed. Only after refreshing the browser do I obtain the desired result. To address this problem, I have attempted ...

Navigating events within the Material Design Light (MDL) mdl-menu component can be

I am utilizing Material Design Light with just PHP, jQuery, and MDL min CSS and JS, no other frameworks involved. Keeping it simple with a basic menu. <button id="lang-switcher" class="mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect"> ...

"Enhance your website with a sleek Bootstrap navigation system featuring dividers and

Need help with creating a Bootstrap nav menu similar to this design made in Photoshop? Wondering about the best way to position the logo and create dividers between menu items like shown in this image. Here's the HTML code currently being used: & ...

Using jQuery to slide in dynamically generated content

I am in the process of developing a straightforward content slider that has the capability to manage dynamically added content. Unfortunately, none of the supposedly "lightweight" plugins I came across offered this functionality or, if they did, it was not ...

What is the most effective method for incorporating social login, specifically "Sign in with Google", into an already established email/password application and database?

I am exploring the process of integrating Google sign-in into an existing app that already has account signup and login functionality. After following a tutorial on YouTube, I managed to successfully implement Google sign-in on my frontend. Upon logging i ...

Themes in Next.js with a splash of color

Is there a way to implement theming with color picking for elements? Check out the example here. I've explored using CSS variables and changing the document classname, but I'm uncertain if this is the best approach. @tailwind base; @tailwind com ...