Styling elements in a React component with CSS to give each item a unique look

My React component, called "Badge", returns text that has bold styling.

render() {
 return (
  <div>
   <Text weight={'bold'}>
    {this.props.label}
   </Text>
  </div>
)

Now, I am using the "Badge" component within another one named "Card".

Since all text in the Badge component is styled as bold, any sentence it renders will also be in bold:

return (
 <div>
  <Badge label={'This part of the sentence is ' + 'normal font style' + ' and the rest is bold.'}></Badge>
 </div>
)

I want to style specific parts of this element differently, so I attempted to remove the bold style from 'normal font style' - just for this segment. However, my current approach isn't working:

<Badge label={'This part of the sentence is ' + <span class=”normalText”>'normal font style'</span> + 'and the rest is bold.'}></Badge>

As a beginner, I find this issue quite frustrating. Any suggestions on how to tackle this problem?

Answer №1

If you need to include html tags in your text, make sure to pass the entire content with the html formatting. See the example code below.

import React, { Component } from 'react';
import ReactDOM,{ render } from 'react-dom';
import Badge from './Badge';
import './style.css';

class App extends React.Component {
  render() {
    return (
      <div>       
       <Badge label="test" /><br/>
       <Badge label={'This part of the sentence is ' + 'normal font style' + ' and the rest is bold.'} /><br/>
       <Badge label={<>
          <span>This part of the sentence is</span> <span className="normalText">'normal font style'</span> <span> and the rest is bold.</span> 
        </>}
       />
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

I've put together a small demo for you.
https://stackblitz.com/edit/react-rvuqv6

Hope this solution meets your needs! Enjoy coding. 😊

Answer №2

A more suitable approach would be to include the label value as children of the badge. To create the Badge component, use the following code snippet:

const Badge = props => {
    return (
       <div className={`badge-class`}>
          <Text weight={'bold'}>
              {props.children}
          </Text>
       </div>
    )
}

You can now utilize the component like this:

return (
   <div>
      <Badge>
          This section of text is in <span className={`normal-texts`}>normal font style</span> while the remainder is bold.
      </Badge>
   </div>
)

This way, you have the flexibility to pass various types of children to the Badge component such as text or images.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm looking to customize the React Material UI responsive drawer by removing the padding from the Toolbar

If I have the code found here: https://stackblitz.com/edit/react-nqkupy?file=demo.tsx which is based on the "Responsive drawer" section in the material UI documentation: https://mui.com/material-ui/react-drawer/#responsive-drawer but I customized it by ...

Error message "Attempting to utilize undefined or null as an object" appears while defining props such as "onGridReady" or "rowSelection" in React components

I followed the instructions on https://www.ag-grid.com/react-grid/ When coding like this: <AgGridReact rowSelection="multiple" .... or <AgGridReact onGridReady={ params => this.gridApi = params.api } ... An issue occurred: Uncaught Type ...

Utilize an asynchronous arrow function to render JSX components

Can someone please help me understand why this code isn't working as expected? When I use a regular arrow function to return JSX, everything works fine. However, when I try to use async/await with the same arrow function to fetch data and return JSX, ...

The image is failing to load - local resources are prohibited from rendering

I am facing a challenge while trying to render an image as it keeps showing the error "Not allowed to load local resource:" Here is the code snippet: fileUpload.js const multer = require("multer"); const path = require("path"); const ...

Using pixel values to define CSS gradient color stops from the end

Currently, I am working on a project involving HTML/CSS/JS where the application has a fixed size and requires precise positioning of elements according to the provided designs. Working with pixel dimensions in CSS is not a concern due to the fixed window ...

Executing an asynchronous action without linking promises to subsequent actions

Encountered a challenge while using componentWillReceiveProps with redux async action. Below is the code snippet along with an explanation: componentWillReceiveProps(nextProps) { if(nextProps.job.status === 'applied'){ this.showAppliedDial ...

Adjust vertical dimension using rich text editor tag

I am currently using JSF with RichFaces version v.3.3.1.GA. I am trying to decrease the height style of the rich:editor tag (using TinyMCE), but for some reason it does not seem to be changing. <rich:editor id="transactionResult" style="height: 10px;" ...

How come ng-class doesn't apply to a specific class name?

I recently wrote the following code: <style> .dotted { border:dotted; } </style> .... <p ng-style="mystyle" ng-class="dotted">{{ answer }}</p> My intention was to have the paragraph element enclosed within a ...

H1 and span elements experiencing abnormal size discrepancies

Check out this code snippet: <h1><a href="">Windows App Store<br /><span class="smallSubText">applications</span></a></h1> and here's the CSS styling: #windowsStoreApplications { float: right; width ...

When a website is deployed to an application, the process includes MVC bundling and managing relative CSS image paths

When trying to convert relative image paths to absolute paths, there are numerous queries on stackoverflow addressing this issue. For example, take a look at this thread: MVC4 StyleBundle not resolving images This question recommends using new CssRewrite ...

Could you walk me through the details of this React function?

Currently, I have a function in place that retrieves products from the database to display on the eCommerce website's product page. Now, I am working on creating a similar function for user sign-in. Could you lend me a hand with this? I'm still ...

css center arrow-aligned underline text

Trying to emphasize my text with an additional arrow centered on the line is proving to be a challenge. When attempting this, the text does not align in the center of the page. .souligne { line-height: 17px; padding-bottom: 15px; text-transform: u ...

The scss function is returning an invalid property value

In my Angular project, I have organized my scss files/folders in the following way: 1) Settings - containing color settings and functions for the project 2) Files and folders defining variables such as fonts, widths, etc. for components and pages 3) Fil ...

How can I align rectangles with different heights to display side by side using Javascript?

Currently, I am designing a press page for a website where the headlines/articles are displayed in rectangles. To achieve this layout, I am using the following CSS: .press-blocks{ column-count: 4; column-gap: 2em; padding-left: 10%; padding ...

Is there a way to move the cards to the next line within a wrapper when the screen size is reached?

My goal is to showcase multiple elements in cards, obtained from my routing system, much like how I'm setting up my sidebar (which is functioning correctly). I have all the titles and icons ready, and the linking works seamlessly. This is where I&apo ...

Creating a customized TextField look with styled-components and Material-UI's withStyles feature

Take a look at this customized TextField style with Material-UI's withStyles: export const StyledTextField = withStyles({ root: { background: 'white', '& label.Mui-focused': { color: 'white' }, ...

Changing the title of your document and app bar in React Router when navigating pages

I'm looking into implementing the react router in a TypeScript project. How can I dynamically update the document title (document.title) and the app bar title (<span className="appbartitle">Home</span>) in a single page application based o ...

What is preventing me from adding a margin to the div directly? Why must I apply a margin to the child in order to affect the div's margin

I've encountered a strange situation with 2 fixes that seem rather unusual to me. 1: By removing the #MARGIN-30 tag and deleting the #Nav-bar tag under margin-3, the issue resolves itself when I reapply those tags. 2: Another fix is achieved by addi ...

How can I switch the header bar button from "login" to "logout" in a React

I am currently working on a React and Next.js frontend template, specifically focusing on creating a dashboard with a header bar and login button. Once a user logs in, the login button should change to a logout button and the links in the header should als ...

Understanding the appropriate roles and attributes in HTML for a modal backdrop element in a TypeScript React project

Trying to create a Modal component using React and TypeScript with a feature that allows closing by clicking outside. This is being achieved by adding a backdrop element, a greyed out HTML div with an onClick event calling the onClose method. Encountering ...