Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(Accordion): log error if incorrect activeIndex type #3199

Merged
25 changes: 25 additions & 0 deletions src/modules/Accordion/AccordionAccordion.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@ import {
} from '../../lib'
import AccordionPanel from './AccordionPanel'

const warnIfPropsAreInvalid = (props, state) => {
const { exclusive } = props
const { activeIndex } = state

/* eslint-disable no-console */
if (exclusive && typeof activeIndex !== 'number') {
console.error('`activeIndex` must be a number if `exclusive` is true')
} else if (!exclusive && !_.isArray(activeIndex)) {
console.error('`activeIndex` must be an array if `exclusive` is false')
}
/* eslint-enable no-console */
}

/**
* An Accordion can contain sub-accordions.
*/
Expand Down Expand Up @@ -72,6 +85,18 @@ export default class AccordionAccordion extends Component {
return { activeIndex: exclusive ? -1 : [] }
}

componentDidMount() {
if (process.env.NODE_ENV !== 'production') {
warnIfPropsAreInvalid(this.props, this.state)
}
}

componentDidUpdate() {
if (process.env.NODE_ENV !== 'production') {
warnIfPropsAreInvalid(this.props, this.state)
}
}

computeNewIndex = (index) => {
const { exclusive } = this.props
const { activeIndex } = this.state
Expand Down
20 changes: 19 additions & 1 deletion test/specs/modules/Accordion/AccordionAccordion-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import AccordionAccordion from 'src/modules/Accordion/AccordionAccordion'
import AccordionContent from 'src/modules/Accordion/AccordionContent'
import AccordionTitle from 'src/modules/Accordion/AccordionTitle'
import * as common from 'test/specs/commonTests'
import { sandbox } from 'test/utils'
import { consoleUtil, sandbox } from 'test/utils'

describe('AccordionAccordion', () => {
common.isConformant(AccordionAccordion)
Expand Down Expand Up @@ -135,6 +135,24 @@ describe('AccordionAccordion', () => {
.simulate('click')
wrapper.should.have.state('activeIndex').that.is.empty()
})

it('warns if is `exclusive` and is given an array', () => {
consoleUtil.disableOnce()

const consoleError = sandbox.spy(console, 'error')
mount(<AccordionAccordion exclusive activeIndex={[1]} />)

consoleError.should.have.been.calledOnce()
})

it('warns if not `exclusive` and is given a number', () => {
consoleUtil.disableOnce()

const consoleError = sandbox.spy(console, 'error')
mount(<AccordionAccordion exclusive={false} activeIndex={1} />)

consoleError.should.have.been.calledOnce()
})
})

describe('defaultActiveIndex', () => {
Expand Down