Using a function in React defaultprops is returning an object

Viewed 26

Im having issues when reading defaultprops of where I use a translation function to read a value mapped to a labelkey. In this case it's a variable called 'greeting_component_title'.

const GreetingComponent = ({ title, id, className }) => {

    console.log('id');

    return (
        <section id={id} className={className}>
            <p> {title} </p>
        </section>
    )
};

GreetingComponent.propTypes = {
  title: PropTypes.string,
};

GreetingComponent.defaultProps = {
  title: translate('greeting_component_title'),
};

export default GreetingComponent;

Title in this case is an object of arrays when the translate function returns a string, however if i instead write default props like this

GreetingComponent.defaultProps = {
  title: 'greeting_component_title',
};

and then use it in my p as such

{translate(title)}

it works perfectly. This was working a few months ago and I've just returned to it. I also tried using an arrow function in the defaultProps and it didn't work.

I cant find anything that tells me if something has changed regarding defaultprops not allowing for functions to run, am I missing something here?

1 Answers

I found this: https://github.com/jsx-eslint/eslint-plugin-react/issues/2396#issuecomment-539184761

Which confirmed my thoughts regarding defaultProps and it seems the syntax has changed. So instead of the code you see in my question, this was the answer

const GreetingComponent = ({ 
    title = translate('greeting_component_title'),
    id,
    className
}) => {

    console.log('id');

    return (
        <section id={id} className={className}>
            <p> {title} </p>
        </section>
    )
};

GreetingComponent.propTypes = {
  title: PropTypes.string,
};

export default GreetingComponent;
Related