New Sep 18, 2024

Set element width based on a string that is not in the element

Libraries, Frameworks, etc. All from Newest questions tagged reactjs - Stack Overflow View Set element width based on a string that is not in the element on stackoverflow.com

I have a React component that can render one string or another.

const MyComponent = (props: {
    readonly textA: string;
    readonly textB: string;
    readonly renderB: boolean;
}) => {
    return <>{props.renderB ? props.textB : props.textA}</>;
};

The problem is when I use this and I toggle renderB on and off, the width of the component can change based on which string is rendered. I want the component width to fit the longer of the two strings.

How can I take the max length of textA and textB and use that to determine the width of my component?

For example, it could look something like this:

const MyComponent = (props: {
    readonly textA: string;
    readonly textB: string;
    readonly renderB: boolean;
}) => {
    const widthA = /* compute the width of props.textA */;
    const widthB = /* compute the width of props.textB */;

return ( <div style={{ width: ${Math.max(widthA, widthB)}px }}> {props.renderB ? props.textB : props.textA} </div> ); };

Scroll to top