Reputation: 138
I'm trying to pass a decorated onClick function returned from the react-bootstrap useAccordionToggle function into a component so that I can hide the Accordion from an interaction on that component. Something goes wrong and the decorated function that is created is no longer able to correctly access the contexts that react-bootstrap sets up (it seems to choke on SelectableContext here). I'm fairly new to react, and just learned about contexts while looking into why this is not working, I wouldn't be surprised if that is where my confusion comes from. It seems to not be getting the correct context at the time of the method construction.
I have included a small test case Click Here for a fiddle:
import React from "react";
import ReactDOM from "react-dom";
import { Button, Accordion, Card, useAccordionToggle } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import "./styles.css";
const InternalComponent = props => {
console.log(props.onClick);
return (
<div>
<button onClick={() => props.onClick()}>here for seeing</button>
</div>
);
};
function App() {
const x = useAccordionToggle(0, () => {
/**/
});
return (
<div className="App">
<>
<Accordion>
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey="0">
create new group
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="0">
<Card.Body>
<InternalComponent onClick={x} />
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
</>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Upvotes: 3
Views: 7439
Reputation: 31
You need to use useRef
hook in order to perform a click
in the accordion toggle.
Just create a constant for the ref, apply it to the Accordion.Toggle
, and call it from the onClick
at the desired component (in this case,InternalComponent
).
import { useRef } from 'react';
function App() {
const accordionRef = useRef(null);
function toggleAccordion () {
accordionRef.current.click();
}
return (
<div className="App">
...
<Accordion.Toggle ref={accordionRef} as={Button} variant="link" eventKey="0">
...
<Card.Body>
<InternalComponent onClick={toggleAccordion} />
</Card.Body>
...
Upvotes: 1
Reputation: 11
I don't have a great answer to this, but what I did for this myself was to have the inside component do onclick={document.querySelector("yourtogglecomponent").click()}
to trigger my valid accordion.toggle outside the accordion.collapse. In theory you could have a hidden accordion.toggle somewhere and do the same.
Upvotes: 1