Emotion: Using both a class and the "css" method in "className" prop - reactjs

How can both a class plus additional CSS be applied when Emotion is used with the className prop in React?
For example, how can one add a class myClass to the following?
import {css} from 'emotion'
<div className={css`color: red`}>

I've never used Emotion but it looks like you can simply add your class and another template string around the css function.
<div className={`myClass ${css`color: red`}`}>
I tested this with one of their inline editors on a page in their Introduction then checked the markup. Seemed to work.

You can use composes with regular classes or classes from a css module
<div className={css`
composes: ${'some-class'};
color: red;` >
May be this can help you if you are still stuck click here

emotion v11 answer
import { css, ClassNames } from '#emotion/react'
const orange = css`color:orange;`
const bold = css`font-weight:bold;`
render(
<>
Using ClassNames
<br/>
<ClassNames>
{({ css, cx, theme }) => (
<>
<div className={`case1 ${css`color:red;`}`}>Case1</div>
<div className={cx('case2', css`color:green;`)}>Case2</div>
<div className={cx('case3', css`${orange}`)}>Case3</div>
<div className="Case4" css={orange}>Case4</div>
<div className="Case6" css={[orange, bold]}>Case5</div>
<div className={cx('case6', orange)}>Case6 (not working)</div>
</>
)}
</ClassNames>
<br/>
without ClassNames
<br/>
<>
<div className={`raw1 ${css`color:red;`}`}>Raw1 (now working)</div>
<div className="raw2" css={orange}>Case4</div>
<div className="raw3" css={[orange, bold,'abc']}>Case5 (no abc)</div>
</>
</>
)

Related

How to solve react hydration error in Nextjs

I have created small nextjs page using wordpress REST API, Now react-hydration-error error show this page.I am using react html parser npm. How do I solve this error. could you please solve this error.
my code:
import Image from 'next/image'
import React ,{Component}from 'react'
import Link from 'next/link';
import { BiCalendar } from "react-icons/bi";
import ReactHtmlParser from 'react-html-parser';
export default class Blog extends Component{
constructor(props){
super(props);
this.state={
data: props.bloglist,
isLoading: true,
dataLoaded: false,
};
}
render(){
if (!this.state.data) {
return null;
}
console.log(this.state.data)
return(
<>
<div className="container blog-section">
<div className='row'>
<h2>Latest Posts</h2>
</div>
<div className='row'>
{
this.state.data.map(((x,i) =>(
<div className='col-md-4 boxs text-center' key={i}>
<div className='bg-info'>
<img src={x.images.large} className='img-fluid'/>
<h3>{x.title.rendered} </h3>
<p className='shopping'><span><BiCalendar/> {x.date}</span> </p>
{/* <p dangerouslySetInnerHTML={{__html: x.excerpt.rendered}}></p><span><BiShoppingBag/> {x.slug}</span> */}
<p class='expert'>{ReactHtmlParser(x.excerpt.rendered)}</p>
<Link href={"/blog"+"/"+x.slug+"/"+x.id } passHref={true}><p className='readmore'><span>Readmore </span></p></Link>
</div>
</div>
)))
}
</div>
</div>
</>
)
}
}
My original issues:
paragraph coming this format <p>If you have heard that there are ways to make money while shopping in the UAE and would lik</p> from API, So I converted to html.
I had this error, in my case I had <p> tag nested inside another <p> tag,
I was using Typography (MUI v5) to render text, switching to <Box> from <Typography> fixed the error.
We use components to build the React-based websites, These components are made using HTML tags. It is very important not to nest the same HTML elements.
For Example:
function Logo() {
return (
<Link href="/">
<a>
<Image
src="/images/logo.svg"
width={100}
height={75}
/>
</a>
</Link>
);
}
export default Logo;
Above is the Logo Component which has already the <a></a> tag inside it.
In this example, you will get the React Hydration Error if the <a> tag is used inside another <a> tag.
<a href="#">
<Logo />
</a>
So do not include the same HTML tags, which are hidden inside the
components to avoid react hydration error.
In my case I am using NextJS and I had a dropdown with react-select, the default value was changing after a small calculation, that does not like to nextjs, this is my previous code:
<Select options={seasons}
onChange={() => setSeason(e.value)}
defaultValue={seasons.find((x) => x.value == season) ? seasons.find((x) => x.value == season) : seasons[0]}
/>
So, I changed that calculation to the useEffect and initialized the react-select dropdown only when that value was calculated,now this is my current code that works:
{defaultSeason && (<Select options={seasons}
onChange={() => setSeason(e.value)}
defaultValue={defaultSeason}
/>)}
So, basically check that the defaultValue or anything else does not change after the html is sent to the client part in NextJS.
Follow these: https://nextjs.org/docs/messages/react-hydration-error
Or try deleting <a> within <Link> maybe.
My first code was this:
const isUserLoggedIn = is_user_logged_in()
// is_user_logged_in() checks for cookie of user token and returns boolean
Got the error about hydration
Then changed code to this:
const [isUserLoggedIn, setIsUserLoggedIn] = useState(null)
useEffect(() => {
setIsUserLoggedIn(is_user_logged_in())
}, [])
Renders was like this:
{isUserLoggedIn ? (
<>
{/* After login */}
<Profile USER={USER}/>
</>
) : (
<>
{/* Before login */}
<SigninButtons/>
</>
)}
And error solved
You can also check this
https://nextjs.org/docs/messages/react-hydration-error
Just try restarting the server. npm run dev. It worked for me. I was using react-hot-toaster.
Also try to check if you have sth like this:
<p>
<div>
Hello
</div>
</p>
div cant be inside p tag

ReactJS making a decorator with React.cloneElement: can't set new child's class (className)

I have an app like this, which uses various "thingies" of different kinds. It knows what stuff should be in the thingies:
function Thingy(props) {
const {top_stuff, bottom_stuff} = props;
return (
<div className="a-thingy">
<div>Today's thingy...</div>
<div className="top">
{top_stuff}
</div>
<div className="bottom">
{bottom_stuff}
</div>
</div>
)
}
It also needs to do some more sophisticated things with the Thingies, like putting a button along side them, or changing the way they layout.
So I want to provide these extras with a Decorator. The Decorator doesn't need to know anything about any sort of stuff
export default function App() {
return (
<div className="app">
<div className="title">
Decorator issue
</div>
<Decorator>
<Thingy top_stuff='top' bottom_stuff='bottom'/>
</Decorator>
</div>
);
}
This looks nice and clean: the App tells the Thingy what is in it, and it Decorates the Thingy the way it wants.
Anything that the Decorator does with css should clearly be in the Decorator css definition. This means that the Decorator needs a way of pointing at the Thingy in css.
I tried to annotate the Thingy's class name:
function Decorator({children}) {
return (
<div className="decorator">
<div className="decorator-heading">decorator</div>
{React.cloneElement(React.Children.only(children),
{className: "decorated"})}
<button>Do Stuff With Content</button>
</div>
)
}
... but that doesn't work.
Why is this? ( sandbox )
For clarification: I want the parent (Decorator) to be able to modify the className that the child has, so that the Decorator css can target that child by class name.
Your code looks fine, the reason it didn't work is because you're passing className from <Decorator /> but NOT using it inside <Thingy />.
So to make that work
function Thingy(props) {
const { top_stuff, bottom_stuff } = props;
return (
// here, concat props.className (passed from <Decorator />)
// make sure you have a space between classes
<div className={`a-thingy ${props.className}`}>
<div>The thingy...</div>
<div className="top">{top_stuff}</div>
<div className="bottom">{bottom_stuff}</div>
</div>
);
}
Now, you can control Thingy styles from Decorator like this
/* Thingy styles */
.decorated {
color: red;
}
/* top style */
.decorated .top {
color: blue;
}
CodeSanbox

Style a property in ReactJS

I got React noob question.. The thing is that I have a method with a mount of JSX attributies with their respective properties.
The question is, how can I get to the imageUrl attribute a style? such as give border-radius: 10px or centering in the page.
xxxx (item:aaaa, index:bbb) {
return (
<div className="Post ms-u sm3 ms-u-lg3 ms-u-xl">
<div className="content">
<PersonaControl
id={"BlogItem" + index}
identifier={item.blogOwnerEMail}
displayName={item.blogOwnerName}
size={PersonaSize.extraLarge}
hidePersonaDetails={true}
imageUrl={item.blogLeaderPicture && item.blogLeaderPicture}
labels={this.props.labels}
/>
Here is the render method. I try to double the information of the property xxxx how calls me the content of the parameter aaaa:
render() {
return (
<div className="clearBoth"></div>
<div className="bandContent" style={{ backgroundColor: this.props.backgroundColor }}>
{this.state.leadershipBlogDataItems.map(i => {return this.leadershipBlogDataItems(i, this.state.leadershipBlogDataItems.indexOf(i))})}
<div className="blogPost"></div>
You simply have to add a style property. You can do this by adding:
<div style={{ border: "1px" }} > </div>
If you want to add the "classic" css, with a file, simply add a className to the div, and import the css file as shown below.
import "./style.css";
<div className="yourstylename"> </div>
Inside style.css you simply add your css. By the way, the import shown above only works if the css file is in the same folder as your component/js file.

react-bootstrap Jumbotron background image

Looking for a way to change the background-image of a jumbotron component
this is what I've tried but no luck:
class Jumbo extends Component {
render() {
var styles ={
"background-image":"http://worldkings.org/Userfiles/Upload/images/Yale.jpg"
}
return (
<div>
<Jumbotron style={styles}>
<h1>Public Art</h1>
<br/>
<p>
A crowd-sourced archive of art in public spaces.
</p>
<Button bsStyle="primary" href="#" >Learn more</Button>
<Button bsStyle="primary" href="#" >Submit a Piece</Button>
{/*link these!*/}
</Jumbotron>
</div>
);
}
}
any pointers?
Apparently you have to use backgroundImage instead of "background-image" for inline styles according to React doc's example:
const divStyle = {
color: 'blue',
backgroundImage: 'url(' + imgUrl + ')',
};
function HelloWorldComponent() {
return <div style={divStyle}>Hello World!</div>;
}
Taken From: https://reactjs.org/docs/dom-elements.html
style
The style attribute accepts a JavaScript object with camelCased
properties rather than a CSS string. This is consistent with the DOM
style JavaScript property, is more efficient, and prevents XSS
security holes.
Found a great solution here. I know this is old but it's the first result that comes up when searching the problem. Future react bootstrappers, enjoy!
First, import your image normally:
import bgimage from '../image_background.png'
Then you can apply the style to your tag like so:
<Jumbotron style={{ backgroundImage: `url(${bgimage})`, backgroundSize: 'cover' }}>

How do I give a background image to a div in React Js

I want to have an image in the background of a div without a const.
I need the image to be a background image, so I can put text over it.
I want to avoid hardcoding the background image in a sass file. However, I am curious how it is written in a sass file.
The following is just an image, not a background image:
class Card extends Component {
render() {
return (
<div className='home-card-view flex-center'>
<div>
<img className='home-card-image' src="https://thumbnail.imageurlpathlsakfjlsdfj)" />
<h2 className='home-card-title'> Title </h2>
<h4> Subtitle stuf that should explain more </h4>
</div>
</div>
)
}
}
export default Card
Can I get a background image in a div in React?
Also how would it be done in the Sass file.
If you have many elements you want to do this and you want to abstract away as much as possible to the Sass file and you're ok targeting modern browsers only, you can use CSS custom properties.
In your Sass file:
.home-card-image{
background-image:url( var(--homeCardImage) );
[background-position, size, etc...]
}
and then in React, you just set the custom property to whatever you want:
class Card extends Component {
render() {
return (
<div className='home-card-view flex-center'
style='--homeCardImage: "YOUR-IMAGE-URL-HERE"'>
<div>
<h2 className='home-card-title'> Title </h2>
<h4> Subtitle stuf that should explain more </h4>
</div>
</div>
)
}
}
export default Card
Why might you do this? Well, if you want to allow yourself to do something more than just a single background-image in future you can. For example, if you wanted to overlay a second background-image with a gradient overlay, you could do that just in the sass file, like so:
.home-card-image{
background-image:url( var(--homeCardImage) ), linear-gradient(to bottom, rgba(0,0,0,0), rgba(0,0,0,.5);
[background-position, size, etc...]
}
And you wouldn't need to touch the React component.
Just apply inline style to the component that you want to have the background-image property (Example below)
class Card extends Component {
render() {
const image_url = 'YOUR IMAGE URL';
return (
<div className='home-card-view flex-center'
style={{ backgroundImage : `url(${image_url})` }}>
<div>
<img className='home-card-image' src="https://thumbnail.imageurlpathlsakfjlsdfj)" />
<h2 className='home-card-title'> Title </h2>
<h4> Subtitle stuf that should explain more </h4>
</div>
</div>
)
}
}
export default Card

Resources