Accordion can be toggled via URL hash

This commit is contained in:
Philipp Stracker 2024-11-21 16:00:03 +01:00
parent 1b96b112c2
commit 10a3767e2f
No known key found for this signature in database
2 changed files with 27 additions and 4 deletions

View file

@ -1,3 +1,4 @@
import { useEffect } from '@wordpress/element';
import { Icon } from '@wordpress/components';
import { chevronDown, chevronUp } from '@wordpress/icons';
@ -5,11 +6,33 @@ import { useState } from 'react';
const Accordion = ( {
title,
initiallyOpen = false,
initiallyOpen = null,
className = '',
id = '',
children,
} ) => {
const [ isOpen, setIsOpen ] = useState( initiallyOpen );
const determineInitialState = () => {
if ( id && initiallyOpen === null ) {
return window.location.hash === `#${ id }`;
}
return !! initiallyOpen;
};
const [ isOpen, setIsOpen ] = useState( determineInitialState );
useEffect( () => {
const handleHashChange = () => {
if ( id && window.location.hash === `#${ id }` ) {
setIsOpen( true );
}
};
window.addEventListener( 'hashchange', handleHashChange );
return () => {
window.removeEventListener( 'hashchange', handleHashChange );
};
}, [ id ] );
const toggleOpen = ( ev ) => {
setIsOpen( ! isOpen );
@ -26,7 +49,7 @@ const Accordion = ( {
}
return (
<div className={ wrapperClasses.join( ' ' ) }>
<div className={ wrapperClasses.join( ' ' ) } id={ id }>
<button
onClick={ toggleOpen }
className="ppcp-r-accordion--title"

View file

@ -57,7 +57,7 @@ const StepWelcome = ( { setStep, currentStep, setCompleted } ) => {
'woocommerce-paypal-payments'
) }
className="onboarding-advanced-options"
initiallyOpen={ false }
id="advanced-options"
>
<AdvancedOptionsForm setCompleted={ setCompleted } />
</AccordionSection>