'Is there a way to implement styles on dynamically generated div inside a component in React
In React, I have a component called DivHelper which generates 2 divs one below the other - instead i want to place them side by side and I cant see the code of Divhelper generates the divs. Is there a way to access dynamically generated divs ?
For example -
///Some random code
< DivHelper/>
///Some more code
This becomes
///Some random code
<div>1 Div</div>
<div>2 Div</div>
///Some more code
and thus, the output is
1 Div
2 Div
Instead I want it to be placed on side by side reversed (like float) 2 Div 1 Div
Is this possible ?
Solution 1:[1]
You can dynamically change the className of your components in React. With your CSS you can then style the component and the layout as you want.
For example:
import { useState } from "react";
import "./styles.css";
export default function App() {
const [display, setDisplay] = useState("row");
const handleClick = () => {
display === "row" ? setDisplay("column") : setDisplay("row");
};
return (
<div className="App">
<h1>Dynamic display</h1>
<button onClick={() => handleClick()}>Change display</button>
<div className={"container " + display}>
<div className="square red">First div</div>
<div className="square green">Second div</div>
</div>
</div>
);
}
And your CSS file:
.container {
display: flex;
}
.row {
flex-direction: row;
}
.column {
flex-direction: column;
}
.square {
background: "red";
height: 100px;
width: 100px;
}
.red {
background: #f00;
}
.green {
background: #0f0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fred |
