Utilizing React State to dynamically alter the look of a circle element upon clicking a button component

I'm having trouble adjusting the style of a circle component when it's selected by a button in another component. Both components need to change appearance upon selection, but I am facing issues with state management and feeling a bit overwhelmed. I've been attempting to use onClick functionality without much success. Any assistance would be greatly appreciated.

App.js

import "./App.css";
import CircleSelector from "./CircleSelector";
import Circles from "./Circles";

class App extends Component {
  constructor(props) {
    super();
    this.addActiveClass = this.addActiveClass.bind(this);
    this.state = {
      active: false
    };
  }

  toggleClass() {
    const currentState = this.state.active;
    this.setState({ active: !currentState });
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">test </header>
        <main>
          <CircleSelector
            className={this.state.active ? "selected" : null}
            onClick={this.toggleClass}
          />
          <Circles />
        </main>
      </div>
    );
  }
}

export default App;  

CircleSelector.js

import React from "react";

function CircleSelector(props) {
  return (
    <div className="CircleSelector">
      <button className="selected">Select Circle 1</button>
      <button>Select Circle 2</button>
      <button>Select Circle 3</button>
      <button>Select Circle 4</button>
    </div>
  );
}

// Must export the component's function (or class)
export default CircleSelector;  

Circles.js

import React from "react";

function Circles(props) {
  return (
    <div className="Circles">
      <div className="selected">1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
    </div>
  );
}

// Must export the component's function (or class)
export default Circles;

App.css

body,
* {
  box-sizing: border-box;
}

.App {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.App-header {
  width: 100%;
  padding: 20px;
  font-size: 24px;
  background-color: grey;
  color: white;
  text-align: center;
  letter-spacing: 3px;
}

.App main {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  flex: 1;
}

.CircleSelector {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  height: 200px;
  width: 150px;
  border: 4px solid purple;
  border-radius: 8px;
  margin-right: 20px;
}

Answer №1

It seems like the issue you're encountering might stem from the use of the toggleClass method. When the onClick function is triggered, it appears to be referencing this within the button's scope instead of the class scope.

To resolve this, consider binding the function in the following manner:

      <CircleSelector
        className={this.state.active ? "selected" : null}
        onClick={this.toggleClass.bind(this)}
      />

To explore more solutions and insights on handling this scope problem, check out this resource here

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

Having trouble getting `npm run start` to work properly with Tailwind in React

I've just begun my journey with Tailwind CSS. Following the installation steps provided on the official Tailwind website, I ran into an error after executing 'npm run start' on VSCode Terminal. Can someone provide guidance on how to trouble ...

Learn how to efficiently pre-load data using the prefetchQuery method in React-Query

Attempting to pre-fetch data using react-query with prefetchQuery. The network tab in browser DevTools shows the requested data coming from the back-end, but strangely, the data is not present in the react-query DevTools cache. Any ideas on what might be c ...

The CSS selector functions as expected when used in a web browser, however, it

While conducting test automation using Selenium, I typically rely on css selectors to find elements. However, I recently came across a peculiar issue. I observed that in certain cases, the css selector works perfectly when tested in the browser console. Fo ...

A feature of HTML5 and CSS3 is a modal window that automatically closes when the user

After following the steps outlined by Keenan Payne, I successfully created a modal window using HTML5 and CSS3. However, I am now seeking assistance with setting it up to close when users click on the darkened background outside of the modal window. Can an ...

Tips for creating a responsive graphic using Bootstrap CSS

I am currently trying to determine how to create individual graphics that can be directly loaded via CSS and made responsive. When I resize the screen, the graphics also adjust accordingly. However, on smaller displays such as mobile phones, the graphics ...

The Element should take up the entire page with the exception of a 20px margin

I am struggling to create an element that covers the entire page except for a 20px margin on all sides. I have tried implementing a solution using this code, which works in webkit browsers and Firefox but seems to have issues with Internet Explorer (10) an ...

What are the functionalities of display flex and block?

I am having trouble with my CSS setup. I have an outer container that wraps around an inner container, which in turn contains two divs. The inner container has a display property of flex, but for small screen sizes, I want the two divs to stack up and disp ...

Tips for creating a custom hook that is type safe:

When I use the custom function createUser, I've noticed that I can pass numbers instead of strings without receiving an error. Surprisingly, even if I forget to include an argument, no red squiggles appear. const [userState, createUser] = useCre ...

Expansive Offspring Division stretching to the Entire Vertical Length of its Guardian Division

I'm attempting to achieve full coverage of the parent div section by my child div section. Take a look at the Example URL (specifically where the Canadian Flag Stand Up Paddle Boarders are located) towards the bottom: Essentially, when I set the widt ...

String Representation of Mongoose Date Retrieval

Mongoose Model: const patientSchema = new mongoose.Schema({ firstName: String, middleName: String, lastName: String, addresses: [addressSubschema], dateOfBirth: Date, files: [{ type: mongoose.Schema.Types.ObjectId, ref: 'File&a ...

Positioning icon/image beside the input box

Currently, I have a form with two buttons in a row and an icon (paper clip) that I am attempting to align next to the buttons using UIKit. However, I am facing challenges in getting the alignment right without affecting the size of the elements. Below is a ...

The Bootstrap 4 grid appears to be malfunctioning as the columns are not displaying next to each other as expected

I've implemented the code below in an attempt to achieve the desired layout shown in the image, but instead, I'm getting a different outcome. Can someone help me figure out what I might be doing wrong with the Boostrap 4 grid system? I'm co ...

MUI Autocomplete featuring the primary selection of 'Create New Customer/Vendor.'

I am looking to develop an autocomplete feature that consistently shows the primary option 'Add New Customer/Vendor.' This option should be visible regardless of whether a search is performed, there are no search results, or before any search is ...

Ways to stop display: flex from eliminating white spaces within the text

span { background-color: red; } .only-whitespace { display: inline-flex; white-space: pre; } .trailing-whitespace { display: inline-flex; white-space: pre; } only whitespace: <span class="only-whitespace"> </span> <br/> trail ...

Incorrect positioning of dropdown menu when using Bootstrap 4 and translate3d() function

Having multiple bootstrap 4.4.1 dropdown menus, each within a column which is functioning correctly except for the position calculation. Example of HTML col: <div class="container"> <div class="row"> <div class="col"> <div ...

Removing accordion borders in Bootstrap and AngularJS can be achieved by customizing

Can anyone help me figure out how to hide the border in each accordion group that contains a panel and inner elements? I've tried using classes like .accordion and .inner but nothing seems to work. Any advice on where to find the specific class or ID ...

What is the best practice for updating server-side props on a Next.js page following a client-side mutation?

When working with Next.js, what is the recommended approach for updating data on a page using getServerSideProps after a client-side mutation? I know of one method where you can: const handleRefresh = () => { router.replace(router.asPath); }; ...

incorrect request body in axios post

I am currently facing an issue while connecting my react app to my node api. I have successfully retrieved data, however, the format of the body is incorrect when attempting to post data. I referred to the axios documentation for guidance. Below is a snip ...

Ways to prevent an element from displaying a hover border or outline

I need help with styling a group of 50% width elements that are displayed next to each other. I want to add a 20px white border around each element to create a separation between them. This is necessary because I have a responsive layout and always require ...

Tips on customizing the selected icon color in Material-UI's BottomNavigationAction styling

I'm facing an issue with Material-UI styled components and could use some assistance. My goal is to create a BottomNavigation bar in React using Material-UI v5 where the selected option's icon displays in red (#f00) while the unselected icons sho ...