In React, when an element is clicked, it will add a class to that element while removing

My goal here is similar to what is demonstrated in this Stack Overflow thread about transitioning flex-grow of items in a flexbox

I'm curious how this can be achieved with React. Consider the following code:

class MyComponent extends React.Component {
constructor(props) {
    super(props);

    this.state = {
        classNameToUse: ''
    };

    this.onElementClicked = this.onElementClicked.bind(this);
}

onElementClicked() {
    this.setState({ classNameToUse : 'big-size'})
}

render() {

    return (
        <div>
            <div className={this.state.classNameToUse} onClick={this.onElementClicked} >
              something
            </div>
            <div className={this.state.classNameToUse onClick={this.onElementClicked} >
               something else
            </div>
        </div>
       );
    }
}

In this setup, adding the className affects both elements. However, I aim to make one grow big with animation while the other collapses, regardless of the number of elements present.

Answer №1

To change the active index when clicked, follow these steps:

// Define state
this.state = {
  activeIndex: null
};
// Click event handler
onElementClicked(e) {
  this.setState({ activeIndex: e.target.index })
}
// Apply class based on active index
className={this.index === this.state.activeIndex ? 'big-size' : ''}

Answer №2

const { useState, useEffect } = React;

const App = () => {
  const [cards,] = useState(['red', 'yellow', 'purple']);
  const [selected, setSelected] = useState(null);
  
  const onClick = (id) => {
    setSelected(id);
  }
  
  return <div className="container">
    {cards.map(card => <div key={card} style={{background: card}} className={`box ${card === selected ? 'selected' : ''}`} onClick={() => onClick(card)}></div>)}
  </div>
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );
.container {
  display: flex;
  height: 200px;
}

.box {
  flex: 1;
  cursor: pointer;
  transition: all .3s ease-in;
}

.selected {
  flex: 2;
}
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f323e2b3a2d363e33722a3672333e3d722a323b1f6b716f716f723e332f373e716c6d">[email protected]</a>/material-ui-lab.development.js"></script>
<div id="root"></div>

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

Creating Event Handlers for corresponding elements in HTML with the help of JQuery and JavaScript

Struggling with HTML and debugging an issue in my ASP.NET Core App. The problem lies in a CSHTML view that functions as a timeclock system for tracking user input against job numbers. The current Index.cshtml is operational, verifying JobNumbers against t ...

Issue with disabled state in radio button container not functioning

I am facing an issue with a radio button div that I need to disable when the condition yAxisEditorCtrl.forceCombinedYAxis is true. Here is the original code: <div class="y-axis-editor"> <div class="vis-config-option display-size-normal form- ...

Sharing information with client-side JavaScript can be done without relying on a view engine or cookies

Introduction to the Issue To set the stage: I am faced with the challenge of transferring data from the server to the client without displaying it on the client side. Instead, this data is utilized by the client socket to access the appropriate room. Let& ...

Personalized Input Field using Material Design UI

Looking to personalize the TextField component in React Material UI, particularly focusing on the following CSS class? root: { '& .MuiOutlinedInput-inputMarginDense': { paddingBottom: 'none !important', }, }, &l ...

Retrieve the corresponding element from a deeply nested array of objects

In my dataset, I have information grouped by scheduledOn dates as shown below: [{ scheduledOn: "2020-02-05T00:00:00" matches: {id: 1, homeTeamName: "BLUE", homeTeamId: 1, homeScore: 1, awayTeamName: "Red", awayTeamId: 2, …} ...

Communication between nodes using serial ports in Node.js fails to receive a response from the connected Arduino board

I've been attempting to establish communication between a computer and an Arduino board using node.js. Despite having a simple program, it just doesn't seem to work as expected. The Arduino program (which seems to be working fine) is as follows: ...

Why isn't this basic CSS animation executing properly?

I have encountered an issue and I have created a JSFiddle to demonstrate it. http://jsfiddle.net/sqMT6/1/ Basically, when you click on a paragraph, the 'hidden' class is supposed to be set, triggering a webkit animation that makes the paragraph ...

Is the Paypal button causing issues with the navigation bar?

I recently encountered an issue while trying to integrate the Paypal smart button into my first project. Whenever the Debit or Credit card button is clicked, the text above it overlaps with the navbar. I attempted to add extra space to the background image ...

Issues arise when attempting to call a panel on multiple pages within jQuery Mobile

I am encountering an issue with my HTML document that has multiple pages utilizing jQuery Mobile's data-role="page". Specifically, I am attempting to trigger a panel on the second page and running into the following error: Error: cannot read proper ...

Encountered an expression when expecting a function call or assignment - React

The error mentioned in the title is occurring on "Line 29:21". Can anyone provide insights on what could be causing this issue? https://i.sstatic.net/id9AD.png ...

I am having trouble getting my console.log function to work properly on my HTML page

As a beginner in JavaScript, I am facing an issue with my console.log not working at all. When I type a console.log message, nothing shows up on my HTML page. I have tried to debug it, but being a newbie, I lack the necessary knowledge. All I can do is see ...

How can I use absolute positioning and scrolling with an Iframe?

One of the key elements of this website is the implementation of iframes, with only one displayed at a time. However, my current issue revolves around the inability to scroll within these iframes due to their absolute positioning. I have attempted variou ...

Altering the way in which URL parameters are attached to links depending on the destination

Our company utilizes Unbounce to create PPC landing pages on a subdomain, which then direct users back to our main website. We have implemented code that appends the AdWords gclid variable to outgoing links: $(document).ready(function() {var params = win ...

Permanent header that clicks into place below the primary fixed header

I've been collaborating with fellow developers on this platform to tackle a persistent issue related to a fixed header. Here is the updated fiddle for reference: http://jsfiddle.net/f95sW/ The Challenge 1) As you scroll down the page, the yellow bl ...

How can the default scrolling feature be disabled for all NextJS <Link>s?

Currently, I am in the process of creating a website using NextJS and incorporating a fade-in and fade-out page transition. In order to maintain a smooth user experience, I have implemented a manual scroll to the top of the page between these transitions t ...

What is the correct method for configuring access permissions?

I'm in the process of developing a user management system, but I keep finding myself having to check the user type for each router. router.get('/admin/settings', (req, res) => { if(admin) { //Proceed. } } router.get(&apo ...

Carousel indicators are not aligned correctly

I have implemented a code snippet to generate a basic carousel slider with 4 items. While navigating to the next slides, everything works smoothly. However, when I try to go back to the first slide using the carousel indicators, the position of the indicat ...

The functionality of mouse hover in multimaterial three.js appears to be not functioning

I'm facing an issue where I want to create a mouse hover effect on an object with multiple materials. See an example here function update() { // Finding intersections // Creating a Ray with the origin at the mouse position // and dire ...

Headers can't be set after they have been sent. This issue arises when calling create(data,cb) function

I am a beginner in Node.js and I am attempting to create a model in MongoDB. However, when I make a call to localhost:3000/a, I notice that the request is being sent twice in the console and I am encountering an error stating "Can't set headers after ...

What is the method to assign a placeholder value using CSS?

Is there a way to assign a placeholder value to an input box using CSS only, without relying on JavaScript or jQuery? If so, how could this be achieved? ...