Home > front end >  How to make the icon changed in react?
How to make the icon changed in react?

Time:01-04

I have accordion componennt that changes the state by clicking on the title. I would like to add to it a funcionality that when I click on it icon gets changed only on the ,,title" div. I have added inactiveIcon and activeIcon props, but have no idea how to make it changed only within this tile div and when the component gets expanded. I know the styling is poor so far, but I would like to finish functionality first. ALso, for this reason, I am attaching photos from storybook.

The basic idea is that after clicking and when the ,,Link to" gets expanded the icon in the title should change.

Appreciate your help.

import { string, node, oneOf } from "prop-types"
import * as Styled from "./Container.styled"
import Icon from "design-system/components/icon"
import React, { useState } from 'react';


const Container = ({ size, children, as, inactiveIcon, activeIcon, text, }) =>  {
  const [isActive, setIsActive] = useState(false);
  return (
  <Styled.Container size={size} as={as}>
    <Styled.Title onClick={() => setIsActive(!isActive)}>
    {text}
    {activeIcon && (
        <Icon name={activeIcon}/>
    )}
    </Styled.Title>
    {isActive &&
    <Styled.Content >
    {children} 
    </Styled.Content>}
  </Styled.Container>
);
}

Container.propTypes = {
  text: string.isRequired,
  size: oneOf(["small", "medium", "large"]),
  children: node.isRequired,
  as: oneOf(["section", "article", "div"]),
  activeIcon: string,
  inactiveIcon: string,
  name: string,
}

Container.defaultProps = {
  size: "large",
  as: "div",
  activeIcon: null,
  inactiveIcon: string,
  name: null,
}

export default Container

Before Click After Click

CodePudding user response:

You can render icons conditionally, depending on the isActive state:

{ isActive && <Icon name={activeIcon} /> }

{ !isActive && <Icon name={inactiveIcon} /> }

or at once:

{ isActive ? <Icon name={activeIcon} /> : <Icon name={inactiveIcon} /> }
  • Related