Skip to content
Related Articles

Related Articles

How to toggle between sibiling in ReactJS?
  • Last Updated : 18 Jan, 2021

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:

My Personal Notes arrow_drop_up
Recommended Articles
Page :