Skip to content
Related Articles

Related Articles

How to toggle between sibiling in ReactJS?

View Discussion
Improve Article
Save Article
  • Last Updated : 18 Jan, 2021
View Discussion
Improve Article
Save Article

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.


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 = 
            <button onMouseOver={() => {
                this.setState({ index: i });
             onMouseLeave={() => {
                this.setState({ index: null });
             Turn the box green
           <div className={'box '+greenClass}>
      return ans
    render = () =>{
      const ans = this.fetchUI()
      return (
         <div style = {{margin:100}}>
  export default App

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


    border:1px solid rgb(194, 106, 106);
    cursor: pointer;


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!