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?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
  • 1
    Does this answer your question? [How to update nested state properties in React](https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react) – Emile Bergeron May 25 '21 at 17:16

1 Answers1

2

you need to update the state as below

const handleClick = (e) => {     
   setClose(prevCloseState => {
      ...prevCloseState,
       easy: true
    })    
};
Shyam
  • 5,292
  • 1
  • 10
  • 20