Search code examples
reactjsreact-nativenext.jsreactstrap

How to enable reactstrap collapse to show first dropdown active by default on first load


Here's a working code for the dropdown.. but I'm having trouble on enabling the first dropdown to be active on first load.. the first dropdown should be showing on initial load and then when user click on the other dropdown, the previous will collapse and the new one will open..

please help.. here's the reference sandbox link if needed

import * as React from "react";
import { Button, Card, CardBody, Collapse } from "reactstrap";
import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";

export default function App() {
  const [state, setState] = React.useState({});
  const { article, moreInfoOpen } = state;

  const handleArticleOpen = (article) => {
    setState((prevState) => ({
      ...prevState,
      article
    }));
  };

  return (
    <div className="app">
    
        <Card className="card">
          <CardBody className="card-body">
            <div className="section section-articles">
              <div className="articles-buttons">
                <Button
                  className="article2-button"
                  color="primary"
                  onClick={() => handleArticleOpen("2")}
                >
                  <h3>Article 2</h3>
                </Button>
                <Button
                  className="article1-button"
                  color="primary"
                  onClick={() => handleArticleOpen("1")}
                >
                  <h3>Article 1</h3>
                </Button>
              </div>

              <Collapse isOpen={article === "2"}>
                <Card className="card">
                  <CardBody className="card-body">
                    <div>Article 2</div>
                  </CardBody>
                </Card>
              </Collapse>
              <Collapse isOpen={article === "1"}>
                <Card className="card">
                  <CardBody className="card-body">
                    <div>Article 1</div>
                  </CardBody>
                </Card>
              </Collapse>
            </div>
          </CardBody>
        </Card>
    </div>
  );
}

enter image description here


Solution

  • useEffect will do the work, set moreInfoOpen to true on load, and call handleArticleOpen("2") if you want to open first option also

     export default function App() {
         ...
    
        //this
         React.useEffect(() => {
            setState((prevState) => ({
              moreInfoOpen: true
            }));
            handleArticleOpen("2");
          }, []);
    
       return (
          ...
       );
    }