What is the process for adding and removing classes using CSS's "ClassName" property in React?

I've been diving into React recently and one thing I'm struggling with is how to seamlessly add and remove CSS classes. Take for example the component below:

import React from 'react';
import "../../styles/signInAndSignUp.css";
import login from "../../assets/img/log.svg";
import register from "../../assets/img/register.svg";

export const LoginScreen = () => {

    return (
        <>
        <div className="container-login">
      <div className="forms-container">
        <div className="signin-signup">
          <form action="#" className="sign-in-form">
            <h2 className="title">Sign in</h2>
            <div className="input-field">
              <i className="fas fa-user"></i>
              <input type="text" placeholder="Username" />
            </div>
            <div className="input-field">
              <i className="fas fa-lock"></i>
              <input type="password" placeholder="Password" />
            </div>
            <input type="submit" value="Login" className="btn solid" />
            <p className="social-text">Or Sign in with social platforms</p>
            <div className="social-media">
              <a href="#" className="social-icon">
                <i className="fab fa-facebook-f"></i>
              </a>
              <a href="#" className="social-icon">
                <i className="fab fa-twitter"></i>
              </a>
              <a href="#" className="social-icon">
                <i className="fab fa-google"></i>
              </a>
              <a href="#" className="social-icon">
                <i className="fab fa-linkedin-in"></i>
              </a>
            </div>
          </form>
          <form action="#" className="sign-up-form">
            <h2 className="title">Sign up</h2>
            <div className="input-field">
              <i className="fas fa-user"></i>
              <input type="text" placeholder="Username" />
            </div>
            <div className="input-field">
              <i className="fas fa-envelope"></i>
              <input type="email" placeholder="Email" />
            </div>
            <div className="input-field">
              <i className="fas fa-lock"></i>
              <input type="password" placeholder="Password" />
            </div>
            <input type="submit" className="btn" value="Sign up" />
            <p className="social-text">Or Sign up with social platforms</p>
            <div className="social-media">
              <a href="#" className="social-icon">
                <i className="fab fa-facebook-f"></i>
              </a>
              <a href="#" className="social-icon">
                <i className="fab fa-twitter"></i>
              </a>
              <a href="#" className="social-icon">
                <i className="fab fa-google"></i>
              </a>
              <a href="#" className="social-icon">
                <i className="fab fa-linkedin-in"></i>
              </a>
            </div>
          </form>
        </div>
      </div>

      <div className="panels-container">
        <div className="panel left-panel">
          <div className="content">
            <h3>New here ?</h3>
            <p>
              Lorem ipsum, dolor sit amet consectetur adipisicing elit. Debitis,
              ex ratione. Aliquid!
            </p>
            <button className="btn transparent" id="sign-up-btn">
              Sign up
            </button>
          </div>
          <img src={login} className="image" alt="" />
        </div>
        <div className="panel right-panel">
          <div className="content">
            <h3>One of us ?</h3>
            <p>
              Lorem ipsum dolor sit amet consectetur adipisicing elit. Nostrum
              laboriosam ad deleniti.
            </p>
            <button className="btn transparent" id="sign-in-btn">
              Sign in
            </button>
          </div>
          <img src={register} className="image" alt="" />
        </div>
      </div>
    </div>
    </>
}

In typical JavaScript fashion, you'd handle this scenario like so:

const sign_in_btn = document.querySelector("#sign-in-btn");
const sign_up_btn = document.querySelector("#sign-up-btn");
const container = document.querySelector(".container");

sign_up_btn.addEventListener("click", () => {
  container.classList.add("sign-up-mode");
});

sign_in_btn.addEventListener("click", () => {
  container.classList.remove("sign-up-mode");
});

Essentially, these classes dictate whether the user sees the sign in or sign up section based on their button selection.

Any help on this matter would be greatly appreciated!

Answer №1

Charlietfl pointed out that the vanilla js code you provided would not function correctly as they would conflict with each other.

Regarding your react issue: I recommend starting by grasping the concept of state, as Robin also suggested. For instance, if you had two states:

const [addedClass, setAddedClass] = useState(false);
const [class, setClass] = useState('container');

You now have a boolean value to utilize in an onClick event to conditionally apply the 'container' class.

const handleClick = () => {
 setAddedClass(prev => !prev)
}

So, if you wanted to add the 'container' className to a div element based on some condition, you can use state to achieve this:

const [addedClass, setAddedClass] = useState(false);
const [className, setClassName] = useState('container');
  
  const handleClick = () => {
    setAddedClass(prev => !prev)
  }
  
  // console.log(addedClass) to see if the state is changing
  
  return (
    <div className={addedClass ? className : null}>
      <button onClick={handleClick}>Toggle Class name</button>
    </div>
  )
}

Whenever the button is clicked, the handleClick function will toggle the addedClass state between true and false. With the ternary operator in the className attribute, the div will be assigned the className stored in the class state (which I named 'container') depending on the addedClass state. This lays a foundation for utilizing state in a react application. Explore further and delve into the useState hook and other hooks available in the documentation!

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

Can asynchronous programming lead to memory leakage?

I'm wondering about the potential for memory leaks in asynchronous operations, specifically within Javascript used on both frontend and backend (node.js). When the execute operation is initiated, a delegate named IResponder is instantiated. This dele ...

Exploring the potentials of VivagraphJS alongside WebGL and the magic of event listeners

After coming across Vivagraph JS on GitHub, I was absolutely enthralled. However, I've encountered an issue that seems to be related to WebGL. My current objective is to: var graph = Viva.Graph.graph(); var layout = Viva.Graph.Layout.forceDirec ...

Developing unit tests for a module responsible for generating Json REST services

Just completed working on https://github.com/mercmobily/JsonRestStores. Feeling a bit nervous since I haven't written any unit tests yet. This module is quite complex to test: it enables the creation of Json REST stores and direct interaction with th ...

You are unable to select the element in IE if there is an image in the background

Apologies for coming back with the same question, as I realize now that I was not clear in my explanation yesterday. You can find the codepen here (please note that it may not open in IE8). My issue is with dragging the 'move-obj' element in IE b ...

The functionality of the date picker is hindered when a dropdown with multiple selections is activated, and conversely, the multi-selection feature of

I am working on an application where I need to implement a drop-down with multi-selection functionality, as well as a date picker for text boxes. For the drop-down with multi-selection feature, I referred to the code in the following link: . Additionally, ...

jQuery may not function properly in a dynamic content environment

I'm encountering an issue with my web application. I've developed a chat feature using Ajax, and I want it to load when a button is clicked. The functionality works, but the dynamic data loaded doesn't seem to be compatible with jQuery. Aft ...

What is the best way to display HTML in this particular situation?

This is the function I am working on: public static monthDay(month: number): string { let day = new Date().getDay(); let year = new Date().getFullYear(); return day + ", " + year; } I am trying to add <span></span> tags around ...

Help needed with React Native image loading issue - why won't the image load when passing a URI?

I am encountering an issue while trying to display an image on a screen in a react-native application. The image uri is being passed as props to the screen. Despite my efforts, the image is not loading and I am unsure of the reason. I have checked various ...

The challenge of mapping React Select

I have implemented react-select in my project and I am using it within a map function like this: renderItems() { this.props.items.map(item => ( <Select id="options" value={this.state.optionSelected} onChange={this.onChangeOpt ...

Dealing with a throw er; uncaught 'err' event while configuring a server with nodemon

I am currently in the process of setting up my local server using node.js and nodemon. Initially, everything runs smoothly on localhost, but as soon as I refresh the page or navigate to another page, the server crashes with an 'unhandled error event&a ...

When dynamically adding input fields in Bootstrap, there is a smaller gap between inline inputs

When adding a new list item dynamically in a modal using jQuery append, the spacing in the first li element seems to have a larger gap between the input fields compared to the rest that are added later. Even after checking the developer tools and confirmin ...

When using React, the page loads and triggers all onClick events simultaneously, but when clicking on a button, no action is taken

I have a strong foundation in HTML and CSS/SASS but I'm just getting started with React. Recently, I encountered an issue that has me stumped. I am trying to highlight a button on the navigation bar based on the current page the user is on. I attemp ...

How can I retrieve the data passed in a post request using Azure Functions and JavaScript?

I have a JavaScript Azure function that takes a context and request as parameters: function(context, req) It's easy to retrieve data from a GET request using the req object. For example, if I pass name=test in the URL, I can retrieve it in my code l ...

What is the best way to customize the woocommerce.css file in the parent theme?

Currently, I have incorporated an ecommerce-friendly wordpress theme for my website in conjunction with woocommerce. To customize the design, I created a child theme and transferred the woocommerce.css file from the plugin into the css of the child theme, ...

Encountering issues while trying to install create-react-app globally using npm

Encountering Issues I am currently facing errors when trying to run npm install -g create-react-app. The app I am working on is called robofriend. Thank you for your assistance in advance. ...

css - design your layout with floating div elements

I used to design layouts using tables, but now I'm trying it out with divs. However, I'm still struggling to get the layout right. It's not as straightforward as using tables. For instance, my code looks like this: var html_output = "< ...

Issue in React Native: Undefined value is being referred to as an object when evaluating 'Object.keys(dataBlob[sectionID])'

As I work on my React Native application, I encountered a challenge when trying to display Facebook page status using the Facebook API in a ListView. Thankfully, this tutorial provided me with valuable insight and allowed me to successfully display the lat ...

Designing a UML Class Diagram to facilitate password verification

My task is to design a UML Class Diagram for the following scenario: A user is required to input a 9-digit password. The system then checks this password against a database to verify its correctness. If the password matches, the system displays a message s ...

Is there an issue with CSS rendering? Safari displays page headers and colors properly, but Firefox and Chrome are not showing the

I've been grappling with this problem for more than a week, but so far I can't seem to figure it out. It seems to be a CSS issue, but I can't pinpoint where I've gone wrong. Being self-taught, I would really appreciate any assistance. ...

Simplifying complex JSON structures by un-nesting arrays

Within my Formik form, I have 3 fields: MemberMemberID, EventEventID, and event_date. This form represents an event (such as a Tuesday club) taking place on a specific date and attended by various members. Formik stores the data in key-value pairs within ...