I’m migrating my class components to functional components and cannot quite understand how should be used default components in a functional component.
Cannot use FuncComp.defaultProps = { /* smth */ }
since it will be deprecated and there are errors in console if using it.
Here is how default props are looking in my BaseButton component:
import { useState } from 'react';
import PropTypes from 'prop-types';
const BaseButton = ({ tooltip, className = "", loading = false, showTooltipDelay = 150, onClick = () => {}, children }) => {
/* ommited code */
return (
<> /* ommited code */ </>
);
};
BaseButton.propTypes = {
tooltip: Tooltip.propTypes.text,
className: PropTypes.string,
loading: PropTypes.bool,
showTooltipDelay: PropTypes.number,
onClick: PropTypes.func,
};
export default BaseButton;
Then, there is Button component, which should in way “extend” the BaseButton.
But I cannot see how this can be done
In class component Button looks like this:
import React, { Component } from 'react';
import BaseButton from './BaseButton';
class Button extends Component {
static propTypes = {
...BaseButton.propTypes,
};
static defaultProps = {
...BaseButton.defaultProps,
};
render() {
return (
<>
/* ommited code */
</>
);
}
}
Any ideas on how can be solved?
My initial idea was to try to define the defaultProps as object in BaseButton and exporting it.
This can be used in component to have default values in props, but it does not help with check of PropTypes
const Button = (props) => {
const { tooltip, className, loading, showTooltipDelay, onClick, children } = {
...defaultProps,
...props,
};
return <></>
}
Mefodii is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.