How to use Word Break Opportunity tags in ReactJS button text

61 Views Asked by At

I have a user-defined value such as 1234_this_is_a_very_long_button_name_hello_world_12345_this_is_long which is used as a button label and I need to have the button text wrap on the underscores.

I can insert a <wbr> after every underscore with simple string replace but then how can I set the text value as it escapes the <wbr> with &lt;wbr&gt;?

Is there an alternative way to do what I'm doing or is there a way to set a html fragment to the text value and have it not be escaped?

My button is defined as:

<ActionButton
id={desButtonId}
styles={descriptionBtnStyles}
text={button.description}
onClick={toggleIsDesCalloutVisible}
/>
1

There are 1 best solutions below

0
On

If ActionButton's text property can take JSX children, you can do that like this:

<ActionButton
    id={desButtonId}
    styles={descriptionBtnStyles}
    text={button.description
        .split('_')
        .map((x, i) => i ? ['_', <wbr />, x] : x)
    }
    onClick={toggleIsDesCalloutVisible}
/>

In React, arrays of elements are automatically flattened upon insertion, so you can return text and JSX elements together. In other words, ['a', ['_', <wbr />, 'b'], ...] will be flattened into something with the HTML equivalent a_<wbr>b....

If ActionButton's text property only accepts a string, however, you'll need to figure out another way (e.g. can it alternatively take a children property?) or write your own custom button component.