Include the className attribute on the contents received from dangerouslySetInnerHTML

What is the best way to define the className attribute for a div that contains 'hello world'?

<div dangerouslySetInnerHTML={{__html: '<div>hello world</div>'}} />

One option is to set it on the outer div like this:

<div dangerouslySetInnerHTML={{__html: '<div>hello world</div>'}} className='class-name'/>

and then style the child in CSS:

.class-name div {
  (add your CSS styles here)
}

However, my goal is to directly set the className on the div containing 'hello world'


EDIT: Adding a class name to the injected HTML does not resolve the issue. For example:

let content = '<div class="class-name">hello world</div>'
<div dangerouslySetInnerHTML={{__html: content}}

This approach does not work well when the same content is used multiple times and can lead to CSS collisions (especially when using style-loader with CSS modules)

Answer №1

It has been two years since I stumbled upon this question, seeking to achieve the same results. While the answers provided were not quite accurate, a solution was found thanks to @jash8506 and their insightful response to this particular query.

The key to solving this lies in utilizing two essential react hooks.

  1. useRef
  2. useLayoutEffect

As per the documentation, useRef is used for accessing DOM elements in React, while useLayoutEffect serves to read layout from the DOM and trigger a synchronous re-render.

By targeting the firstChildElement within the container div and applying classes to its classList, the desired outcome can be achieved.

Below is an example of the completed code:

const containerRef = useRef();

useLayoutEffect(()=>{
  if (containerRef.current){
    containerRef.current.firstElementChild.classList.add('class-name');
  }
});

return (
  <div ref={elRef} dangerouslySetInnerHTML={{__html: '<div>hello world</div>'}} />
)

Answer №2

<div className="post-content" dangerouslySetInnerHTML={{ __html: post.content}}/>

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

Is there a way to print the full page including scroll tab content?

https://i.sstatic.net/FJt7P.png I am facing an issue where I want to print the entire page including the scrollable content within a tab. Currently, only the visible screen content is being printed. ...

axios POST request in react app receives an empty response, while the Rails server displays a 201 status code

I have a react front end that communicates with a rails API using Knock and JWT for user authentication. When a user submits their email and password through a login form, the token received in the response data is stored in localStorage for use in other f ...

What is the best way to center a div vertically within a bootstrap 5 carousel across all screen sizes?

Looking to center the text div within a Bootstrap 5 carousel both vertically on large screens and small (mobile) screens. To view the site, visit... Below is the HTML for the div. The targeted div has the CSS class #hero .carousel-container { display ...

Three divs are positioned within the parent element and collectively fill the entire height. The first and last div have varying

I attempted to replicate the design shown in the image below: https://i.sstatic.net/Q7sTI.png Initially, I was successful in achieving this using JavaScript. However, when attempting to recreate the same effect using only CSS without any JavaScript, I en ...

React Material UI Expansion Panel with disabled cursor pointer

Is there a way to only have the cursor hover effect on the ExpandIcon within the Material-ui expansion panel, without disabling it completely? For reference, here is the official documentation for the ExpansionPanel: https://material-ui.com/api/expansion- ...

One way to declare i18next specifically in React's App.tsx file is by following these

In my React App.tsx file, I am looking for a way to declare const { t } = useTranslation() only once. After that, I want to be able to use { t(trans.things) } in my components without having to declare const { t } = useTranslation() again each time. Is t ...

Words with emphasized border and drop shadow effect

I am trying to achieve a specific font style. If it's not possible, I would like to get as close as possible to the desired style. However, due to IE support requirements, I am unable to use text-stroke. https://i.sstatic.net/JwQyb.png The closest a ...

NextJS Deployment on Windows Server with IIS 10

After creating a NextJS application, I used the command "npm run build" to compile the app, resulting in the files being stored in the .next folder. Now, I am looking to host the app on my own servers using IIS (either version 7 or 10). Despite my efforts, ...

What is the correct way to assign a value to the switch?

I have a switch for opening and closing that is being saved on Firestore. When the switch is closed, I want it to remain in the 'close' position, like this: https://i.stack.imgur.com/jjYe5.png Currently, the issue is that when I navigate to ano ...

Background: Cover causing image to be cut off

I'm having trouble trying to display the top part of a background image under my current navigation bar. I've been unable to identify what mistake I may be making here. Here is my HTML code: <section class="jumbotron"> <div class=" ...

I do not have ESLint set up, so I can use JSX without needing 'React' to be in scope

In my research on the React documentation and Stack Overflow, I came across suggestions for fixing the error 'React' must be in scope when using JSX. Even after uninstalling ESLint from VSCode, I still encounter this issue. I developed a basic R ...

Having trouble decoding a cookie received from a React.js front-end on an Express server

When using React js for my front end, I decided to set a cookie using the react-cookie package. After confirming that the request cookie is successfully being set, I moved on to configure the Express server with the cookie parser middleware. app.use(cookie ...

Next.js - the next development environment fails to show the latest code modifications

Recently, I've been going through some tutorials and despite spending considerable time searching for a solution, I'm still unable to figure out why changes I make to a specific component (navbar) are not showing up in the development server. I& ...

Bootstrap allows for the use of video backgrounds, offering the option for borders to be included

Having trouble with a Bootstrap HTML page featuring a video background? The issue is that sometimes the video has borders on the left and right, and occasionally on mobile devices as well. Oddly enough, when the browser (Chrome or Firefox) is refreshed, th ...

When the height of the window decreases, scrolling is not implemented

Having trouble adjusting the height of my Responsive Modal when the window height decreases. The content is slipping under the window and the scroll bar isn't adjusting accordingly. It seems like the nested div structure is causing issues. https://i.s ...

Error: The function explore() is missing a required parameter called 'path'

Here is my code snippet: def navigate(directory): # To avoid issues with forward slashes, normalize the path directory = os.path.normpath(directory) if os.path.isdir(directory): subprocess.run([FILEBROWSER_PATH, directory]) elif os.path.isfile(directo ...

Transforming a form into a React component

Currently, this is the code I have been working on: import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Input from '@material-ui/core/Input'; const useStyles = makeStyles(theme => ({ ...

What is the best way to ensure that my website's elements adjust automatically to different screen sizes?

Recently, I encountered a small snippet of HTML code with the main focus being an h2 element. #top-warning{ justify-content: center !important; display: flex; width: 100%; margin-top: 5vw; letter-spacing: 3px; font-family: "Penguin Regular ...

It appears that the margin is malfunctioning

Let's cut to the chase - I want to add a chat sidebar to my website, but I'm having trouble adding margins to make it close in properly. Here's the code snippet: HTML <div class="inner-chat"> <div class="chat-box-messages"> ...

React Native app unable to play S3 video on iOS device

Looking for some help with video streaming from an s3 bucket using Node.js and React. It's working on all devices except iOS, where the server is returning a 206 success but the stream ends before playing. I've checked headers and can't find ...