0

I am trying to achieve a behavior on click. What I want is to have the button show “Click to close” when clicked, and then once you click again - revert back to its initial state (showing ‘Easy Riddles’).

Here is a snippet of my code:

import React, { useState } from "react";
import { Accordion, Card, Button, Container, Row, Col } from "react-bootstrap";

const Riddles = (props) => {
  const levelStatus = {
    easy: "Easy Riddles",
    medium: "Intermediate Riddles",
    hard: "Hard Riddles",
  };

  const collapseButton = "Click to close";

  const [close, setClose] = useState({
    easy: false,
    medium: false,
    hard: false,
  });

  // Handle click
  const handleClick = (e) => {
    setClose({
      close.easy: true
    });
  };

  return (
    <>
      <div className="riddlesection">
        <Container>
          <Row>
            <Col className="riddlegrid" xs={12} sm={12} md={4}>
              <Accordion>
                <Card id="easy">
                  <Card.Header>
                    <Accordion.Toggle
                      id="easy"
                      onClick={handleClick}
                      value="Easy Riddles"
                      as={Button}
                      variant="link"
                      eventKey="0"
                    >
                      {close.easy ? levelStatus.easy : collapseButton}
                    </Accordion.Toggle>
                  </Card.Header>
                  <Accordion.Collapse eventKey="0">
                    <Card.Body>
                      <Row>
                        <Col xs={6} sm={6} md={6}>
                          Countdown
                        </Col>
                        <Col className="resetlink" xs={6} sm={6} md={6}>
                          Switch
                        </Col>
                      </Row>
                      <div>Hello! I'm the body</div>
                    </Card.Body>
                  </Accordion.Collapse>
                </Card>
              </Accordion>
            </Col>
          </Row>
        </Container>
      </div>
    </>
  );
};

What can I do to achieve differently the behavior that I want?

1

1 Answer 1

2

you need to update the state as below

const handleClick = (e) => {     
   setClose(prevCloseState => {
      ...prevCloseState,
       easy: true
    })    
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.