Friday, January 30, 2026
HomeLanguagesHow to toggle between sibling in ReactJS?

How to toggle between sibling in ReactJS?

How can We make the sibling box appear green when the button hovers?

We can keep a state with a name index to keep the sequence number of a hovered button. When the user leaves the mouse from the button, the state will be null. And based on the value of the state, the box will have classes to make it green.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. folder name, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

App.js file: Now write the code in App.js. App is the default component.

Javascript




import {React , Component} from 'react';
import './App.css';
class App extends Component{
     
    state = {
        index: null
      };
        
      fetchUI  = ()=> {
  
        let ans = [];
      for(let i=0;i<5;i++){
        const greenClass = (this.state.index === i) ? 'green' : '';
    
        const data =
          <div>
            <button onMouseOver={() => {
                this.setState({ index: i });
             }}
             onMouseLeave={() => {
                this.setState({ index: null });
             }} 
            >
             Turn the box green
           </button>
           <div className={'box '+greenClass}>
           </div>
         </div>
          
         ans.push(data)
      }
      return ans
    }
  
  
  
    render = () =>{
        
      const ans = this.fetchUI()
      return (
         <div style = {{margin:100}}>
          {ans}
        </div>
      );
    }
  }
    
  export default App


App.css: Add the App.css file in the src folder to create the box and make them green.

CSS




.box{
    border:1px solid rgb(194, 106, 106);
    height:20px;
    width:20px;
  }
  .green{
    background:green;
    cursor: pointer;
  }


Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32478 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6849 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12065 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7222 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6917 POSTS0 COMMENTS