reactjsmaterial-uireact-propsreact-proptypes

How can I specify that a prop takes a ref in a custom React component?


I have a custom component in React that I'd like to be able to hold a ref (i.e., it should have ref as one of its props). (This is needed if we want to use it as a child of the ToolTip component.) We're using Material-UI for our components and PropTypes for prop validation, and our code is JavaScript. The component's code is much like the following:

import { FormControlLabel, Switch } from '@mui/material'

import PropTypes from 'prop-types'

function LabeledSwitch({ label, checked, onChange, required, ...otherProps }) {
  return (
    <FormControlLabel
      control={<Switch {...otherProps} />}
      label={label}
      checked={checked}
      onChange={onChange}
      required={required}
    />
  )
}

LabeledSwitch.propTypes = {
  label: PropTypes.string.isRequired,
  checked: PropTypes.bool,
  onChange: PropTypes.func,
  required: PropTypes.bool
}

LabeledSwitch.defaultProps = {
  checked: false,
  onChange: null,
  required: false
}

export default LabeledSwitch

I want to add ref into the component's props list with the FormControlLabel's control prop set to:

      control={<Switch {...otherProps} inputRef={ref} />}

and the ref's default being null. My problem is that I can't simply add

  ref: PropTypes.ref,

into the LabeledSwitch.propTypes list, as ref is not a type that PropTypes recognizes. How do I go about specifying that the ref prop is, in fact, a ref? Or, do I simply specify that it's an element (which, to me, doesn't sound right)?


Solution

  • Ref is an object with an attribute current in it. So that should be

    ref: PropTypes.object