I'm working on creating a design system in ReactJS using TypeScript, and I'm encountering an issue where I'm unable to correctly pass and return types for my components. Here's what I've done so far:
However, I'm still facing difficulties in making it work as expected. Specifically, I want my component to return one of the defined components, but I seem to be unable to pass the types correctly.
Here's a completed version of my code:
import React from "react";
import './title.css'
export type TitleProps = {
linguage: 'pt-BR' | 'es-CL' | 'en-US'
}
export const Title = ({ linguage }: TitleProps) => {
return (
<h1 className="storybook-title-portugues" >
Gerenciamos sua TI com excelência
</h1>
);
}
const getTitlePt = () => {
return (
<h1 className="storybook-title-portugues" {...{ linguage: 'pt-BR' }}>
Gerenciamos sua TI com excelência
</h1>
);
}
const getTitleEn = () => {
return (
<h1 className="storybook-title--english"{...{ linguage: 'pt-BR' }}>
We manage your IT with excellence
</h1>
);
}
const getTitleEs = () => {
return (
<h1 className="storybook-title--espanol"{...{ linguage: '' }}>
Gestionamos tu TI con excelencia
</h1>
);
}
const getTilte = () => {
if (linguage === 'pt-BR') {
return getTitlePt
} else if (linguage === 'en-US') {
return getTitleEn
} else {
return getTitleEs
}
return getTilte
}
I tried going through PROPS and THIS but it doesn't work
Let's fix the typo first of all: getTilte should be getTitle
Another problem is that you're trying to access linguage (it may be a typo ?), but it's not available because you didn't pass it as a parameter or from a higher scope. As you will see that linguage is only reachable by Title functional component and getTitle is out of this functional component.
Your props spreading approach is a bit unusual. It would be cleaner to just directly set them on the component.
Let me refactor your code:
import React from 'react';
import './title.css';
export type TitleProps = {
linguage: 'pt-BR' | 'es-CL' | 'en-US';
};
export const Title: React.FC<TitleProps> = ({ linguage }) => {
const getTitle = () => {
if (linguage === 'pt-BR') {
return 'Gerenciamos sua TI com excelência';
} else if (linguage === 'en-US') {
return 'We manage your IT with excellence';
} else {
return 'Gestionamos tu TI con excelencia';
}
};
const className = () => {
if (linguage === 'pt-BR') {
return 'storybook-title-portugues';
} else if (linguage === 'en-US') {
return 'storybook-title--english';
} else {
return 'storybook-title--espanol';
}
};
return <h1 className={className()}>{getTitle()}</h1>;
};
That will fix your problem but I strongly advice you to use a package like i18next or similar libraries to deal with internationalization (i18n) in your projects. Here you can find a i18n sample on codesandbox (not mine): https://codesandbox.io/s/react-i18next-v9cq3