Search code examples
reactjscomponentsstyling

style react component on click


so i have this simple divs of names:

i just want to press on one of them and get a background color of green and when pressing on another one the first one will be canceled so just one will be colored at a time. what i simply need is inline style or i don't know i'm stuck.

first.js:

import React from 'react';

function SidebarComponents({name,title,selected,onSelect}) {

    const style={
        cursor: "pointer"
    };

    const classes = {
        selected: {
          backgroundColor: '#00ff00'
        }
      }

    return (
        <div 
            name={name}
            title = {title}
            style={style}
        >
           {name}
        </div>
    )

}
export default SidebarComponents;

second.js:

import React, { useEffect, useState } from "react";
import SidebarComponents from "../SidebarComponents/SidebarComponents";
import 'bootstrap/dist/css/bootstrap.min.css';
import '../Sidebar1/Sidebar.css';

function Sidebar({ onChange }) {
  const [selectedComponent, setSelectedComponent] = useState({
    componentsName: [
      { name: "John Smith", title: "John Smith" },
      { name: "Male, 26 years old", title: "Gender and age" },
      { name: "john", title: "Alerts" },
      { name: "claude", title: "Recent" },
      { name: "edward", title: "Blood pressure" },
      { name: "mira", title: "Body weight" },
      { name: "alex", title: "Glucose" },
      { name: "zac", title: "SPO2" }
    ]
  });

  return (
    <div>
      {selectedComponent.componentsName.map(component => {
        return (
            <div className="row align-items-start sidebar-components">
                <div className="col">
                    <SidebarComponents 
                    name={component.name} 
                    title={component.title} 
                    />
                </div>
          </div>
        );
      })}
    </div>
  );
}

export default Sidebar;

Solution

  • on Sidebar:

    const [selectedName, setSelectedName] = useState(null);
    //...
    <SidebarComponents 
      name={component.name} 
      title={component.title}
      selected={component.name === selectedName}
      onSelect={setSelectedName}
    />
    

    on SidebarComponents:

    const selectedClassName = selected ? 'selected' : '';
    
    //...
    
    <div 
      name={name}
      title={title}
      style={style}
      className={`sidebar ${selectedClassName}`} //you must add sidebar and selected classes to your styles
      onClick={() => onSelect(name)}
    >
      {name}
    </div>