Search code examples
javascriptreactjssvgsemantic-ui

ReactJS How to change an icon (SVG) onClick?


I am using Semantic UI's Accordion. I replaced the default arrow button with my own SVG. I have two SVGs, one upper arrow (^) when the modal is collapsed and one down arrow (∨) when it is open. When the ^ is clicked I would like to change it to ∨. How can I achieve this?

 <Accordion.Title active={this.state.activeIndex === idx} index={idx} onClick={this.clic}>
 <div className="fleche">
      <FlecheBasSVG // Down arrow
      onClick={<FlecheBasSVG />}/> {/* Up arrow */}
      Version {idx + 1} - {elem.etat ? t(`flot.split.etat.${elem.etat}`) : "flot.split.etat.INCONNU"}
</div>
</Accordion.Title>


Solution

  • React handles things in a little bit different way than what you're trying to do. If you want to show and hide elements you can do this with a state variable. I have given an example below.

     state = {
         arrow: true;
     }
    
     const handleClick = () => {
         this.setState({arrow: !this.state.arrow})
     }
    
    
     <Accordion.Title active={this.state.activeIndex === idx} index={idx} onClick={this.clic}>
     <div className="fleche">
        // assuming the svg component has something to link an image (I am using an SRC prop, that probably wont work but is an example)
          {this.state.arrow ? <FlecheBasSVG onClick={this.handleClick} src="/path/to/up/image"/> : <FlecheBasSVG onClick={<this.handleClick} src="/path/to/up/image"/>}
          Version {idx + 1} - {elem.etat ? t(`flot.split.etat.${elem.etat}`) : "flot.split.etat.INCONNU"}
    </div>
    </Accordion.Title>