Reputation: 350
I'm trying to create a text component where first word of the sentence to be bold. Right now with my solution, when a user enter "Tips: favourite vacation", I get " Tips: favouritevacation", where rest of sentence becomes mess and no space is created after Tips:. This isn't elegant solution. I thought about creating another component like TextBold and use it like this < Text >< TextBold >Tips:< /TextBold > Your Vacation< /Text >, but this seems unnecessary. Is there a way to get this working within Text component alone? https://codesandbox.io/s/text-component-v2dbt?file=/src/App.tsx
import * as React from "react";
export interface TextProps {
children?: string;
}
export const Text: React.FunctionComponent<TextProps> = ({
children
}: TextProps) => {
return (
<>
<span style={{ fontWeight: "bold" }}>{children?.split(" ")[0]}</span>
<span>{children?.split(" ").slice(1)}</span>
</>
);
};
export default function App() {
return (
<div>
<Text>Tips: favourite vacation</Text>
</div>
);
}
Upvotes: 0
Views: 1160
Reputation: 14891
You could make use of first space char index and .substring
export const Text: React.FunctionComponent<TextProps> = ({
children = ""
}: TextProps) => {
const firstSpaceIndex = children.indexOf(" ");
return (
<>
<span style={{ fontWeight: "bold" }}>
{children.substring(0, firstSpaceIndex)}
</span>
<span>{children.substring(firstSpaceIndex)}</span>
</>
);
};
Upvotes: 2
Reputation: 87
Try
<span style={{ fontWeight: "bold" }}>{children?.shift()}</span>
<span>{children?.split("").slice(1)}</span>
Upvotes: 0