AsianTemptation
AsianTemptation

Reputation: 123

Toggle CSS style in a function React component

Every post or tutorial on how to toggle css in React assumes that I'm using a class component. However, I'm using a function component and don't have access to this and state. Can somebody tell me how to toggle a CSS style for a JSX element in a React function component?

import React from 'react';
import { Row, Container, Col } from 'react-bootstrap';

const FilterBar = ( {eventFilters, setEventFilters} ) => {
  

  const someFunction = () => {
      // code in here
  }  

  return(
    <div className="row-fluid" >
      <Container fluid >
        <Row className="justify-content-md-center mb-2 mt-2">
          <Col onClick={someFunction}> <button value="ALL"> All </button> </Col>   
          <Col onClick={someFunction}> <button value="WORKSHOP"> Workshop </button> </Col>        
          <Col onClick={someFunction}> <button value="MINIEVENT"> Minievent </button> </Col>        
        </Row>
        <Row className="justify-content-md-center mb-2">  
          <Col onClick={someFunction}> <button value="SPEAKER"> Speaker </button></Col>
          <Col onClick={someFunction}> <button value="MEAL"> Meal </button> </Col>
          <Col onClick={someFunction}> <button value="OTHER"> Other </button> </Col>     
        </Row>
      </Container>
    </div>
  );
}

export default FilterBar; 

Upvotes: 1

Views: 1632

Answers (1)

Drew Reese
Drew Reese

Reputation: 202751

Toggling some style via click event object. You can use the event target style property to change the current textDecoration property to "line-through" or nothing ("").

const toggleStrikethrough = (e) => {
  e.target.style.textDecoration =
    e.target.style.textDecoration === "line-through" ? "" : "line-through";
};

Edit toggle-css-style-in-a-functional-react-component

function App() {
  const toggleStrikethrough = (e) => {
    e.target.style.textDecoration =
      e.target.style.textDecoration === "line-through" ? "" : "line-through";
  };

  return (
    <div className="App">
      <div onClick={toggleStrikethrough}>ALL</div>
      <div onClick={toggleStrikethrough}>WORKSHOP</div>
      <div onClick={toggleStrikethrough}>MINIEVENT</div>
      <div onClick={toggleStrikethrough}>SPEAKER</div>
      <div onClick={toggleStrikethrough}>MEAL</div>
      <div onClick={toggleStrikethrough}>OTHER</div>
    </div>
  );
}

Note: This is generally frowned upon though and considered an anti-pattern as you are directly manipulating the DOM. The better and more react way is to maintain a toggled "state" in local component state for each element you want to toggle style (or anything really) of.

Upvotes: 2

Related Questions