Preventing Icon Wrapping in React Using Non-Breaking Spaces
Problem
When rendering inline text with an optional info icon, the icon would sometimes wrap onto the next line by itself. This created an awkward UI issue where the icon appeared "orphaned" from the sentence it belonged to.
Expected vs. Actual Behavior
Expected: The final word of the sentence and the info icon should always stay together on the same line.
Actual: The icon wraps onto the next line independently.
Solution
JSX
<>
{bulletText}
{showInfoIcon && (
<span className="nbspAndSvg">
{'\u00a0'}
<InfoSvgIcon />
</span>
)}
</>
CSS
.nbspAndSvg {
white-space: nowrap;
}
Why This Works
This solution uses a non-breaking space (\u00a0) combined with white-space: nowrap to bind the icon to the preceding word. As a result, the browser treats the final word and the icon as a single unit during line wrapping.
This approach avoids additional layout complexity and works consistently across different screen sizes and text lengths.
Outcome
This implementation provided a simple and reliable fix after earlier approaches proved too complex or failed to handle all edge cases. It preserved separation of concerns by avoiding changes to business logic, translations, or component structure.
The final result improved UI consistency while keeping the code easy to read and maintain.
Extra Note
This mini blog is built with Next.js, TypeScript, React, and remark-prism for syntax highlighting.
