Home > Enterprise >  Inserting \n to break line in JavaScript template string conditionally rendered in React Bootstrap
Inserting \n to break line in JavaScript template string conditionally rendered in React Bootstrap

Time:01-29

Part of a React component of mine is made of a React Bootstrap Button component. Within this one, I render a string conditionally depending on its toggled state, as per the following code:

<Button 
                size="sm"
                className={!toggleBoolean ? 'clickable block' : 'cancel clickable block'}
                onClick={()=>setToggleBoolean(!toggleBoolean)}
            >
                {!toggleBoolean ? `[${publicCommunication.date}]\n《${publicCommunication.title}》`: '关'}
            </Button>

As you can see, I included the \n because I want to put date and title on separate lines in the button, which I also display as a block (instead of the default inline-block) for this purpose. The application runs without errors, and the style is applied. However, the conditionally rendered string still appears on a consecutive line, as in the screenshot below: The newline should start after the closed square bracket. Nothing happens instead.

What can I do to solve this problem? (Neither inserting
nor html entities - even by enabling them on the button - is of any help). As dependencies, I am using "bootstrap": "^5.2.3" and "react-bootstrap": "^2.7.0".

Thanks for your help!

CodePudding user response:

This is the issue with how CSS wrap your text. But if you just want to break line, you can use the <br/> html tag. You can reference the below code:

<Button 
                size="sm"
                className={!toggleBoolean ? 'clickable block' : 'cancel clickable block'}
                onClick={()=>setToggleBoolean(!toggleBoolean)}
            >
                {!toggleBoolean ? <>`[${publicCommunication.date}]`<br/>`《${publicCommunication.title}》`</>: '关'}
            </Button>

  • Related