How to bold specific text in React.js

avatar

Borislav Hadzhiev

Tue Apr 19 20222 min read

Bold specific text in React.js #

Use inline styles to bold specific text in React.js, e.g. <span style={{fontWeight: 'bold'}}>world</span>. The bold font will only be applied to the element to which it was added and its children.

App.js
const App = () => { return ( <div> <p style={{fontSize: '2rem'}}> Hello <span style={{fontWeight: 'bold'}}>world</span> !!! </p> </div> ); }; export default App;

bold specific text react

We used inline styles to bold some text in an element.

Notice that multi-word properties are camelCased when specified as inline styles.

The first set of curly braces in the inline style marks the beginning of an expression, and the second set of curly braces is the object containing styles and values.

The bold font is only going to be applied to the span element.

If you need to do this often, you can extract the span element into a component which renders its children.

App.js
function BoldText({children}) { return <span style={{fontWeight: 'bold'}}>{children}</span>; } const App = () => { return ( <div> <p style={{fontSize: '2rem'}}> Hello <BoldText>world</BoldText> !!! </p> </div> ); }; export default App;

This code sample achieves the same result. Whatever we pass between the opening and closing tags of the BoldText component will have the bold style applied.

An alternative solution is to define a bold class in a global css file.

App.css
.bold { font-weight: bold; }

And here is how we would import the App.css file and use the bold class.

App.js
import './App.css'; const App = () => { return ( <div> <p style={{fontSize: '2rem'}}> Hello <span className="bold">world</span> !!! </p> </div> ); }; export default App;

This approach enables us to reuse commonly used styles by defining them in a global css file.

It's a best practice to import your global css files in your index.js file because then they wouldn't only get loaded when certain component is mounted.

Use the search field on my Home Page to filter through my more than 1,000 articles.