When required prop is true, I want * at the end of children to be red colored. Current code below is printing out 'Label Component*'. Before the change, I had it {required ? `${children} * : children} and it worked except * was default black color. All I'm trying to do is turn it into red colored * and facing difficulties. What am I doing wrong? https://codesandbox.io/s/label-component-ts-zw392?file=/src/App.tsx:0-1356
import * as React from "react";
export interface ILabelProps {
weight?: "normal" | "bold";
htmlFor?: string;
children?: React.ReactNode;
testId?: string;
required?: boolean;
}
export const Label: React.FunctionComponent<ILabelProps> = ({
htmlFor,
weight = "normal",
testId,
required = false,
children
}: ILabelProps) => {
const dataRef = React.useRef(null);
const createTestId = (
ref: HTMLElement,
testId: string | undefined,
testIdName: string = "data-testid"
) => {
if (ref && testId) {
ref.setAttribute(testIdName, testId);
}
};
React.useEffect(() => {
if (dataRef.current) {
createTestId(dataRef.current, testId);
}
}, [dataRef, testId]);
const requiredAsterisk = `<span color="red">*</span>`;
return (
<label ref={dataRef} htmlFor={htmlFor} style={{ fontWeight: weight }}>
{required ? (
<span>
{children}
{requiredAsterisk}
</span>
) : (
children
)}
</label>
);
};
export const Content: React.FunctionComponent = () => {
return (
<div>
<input type="text"></input>
</div>
);
};
export default function App() {
return (
<Label
htmlFor="some-id"
testId="testing-label"
weight="normal"
required={true}
>
Label Component
</Label>
);
}
You can't set the color with a color prop. If you want to set it inline it needs to be inside a 'style' prop as mentioned above. So line 36 becomes
const requiredAsterisk = <span style={{ color: "red" }}>*</span>;