0

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!

Stefano
  • 85
  • 4
  • 10

1 Answers1

1

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>
Tung Pham
  • 537
  • 4
  • 10
  • Excellent, it works! So what caused the problem was conditionally rendering template JS strings instead of JSX. Thank You very very much! @Tung Pham – Stefano Jan 28 '23 at 16:04
  • No, what caused the problem was how CSS wrap your JS string when displaying. This has nothing to do with JSX and string template. You can basically change the style on your button like this answer https://stackoverflow.com/a/22896536/5972355. But since I am not an expert in CSS, br tag usually my go to. – Tung Pham Jan 28 '23 at 16:09
  • OK, thanks for pointing that out. I had had a look at that answer before posting my question, but I hadn't really understood it. It also seemed way too artificial to me. I like your solution best. Thanks. – Stefano Jan 29 '23 at 11:50