Setting background image within React component - css

I am currently fiddeling with this transformation snippet, and I want to change the background of the boxes to images, instead of a gradient. However, it does not seem to work.
<div
className="element"
style={{
width: element.width,
height: element.height,
backgroundImage: this.state.backgroundImage,
...styles,
}}
>
import BackgroundImage from './door1.png';
...
...
constructor(props) {
super(props);
this.state = {
elements: [
{
id: "el-3",
x: 100,
y: 225,
scaleX: 1,
scaleY: 1,
width: 100,
height: 100,
angle: 0,
backgroundImage: {BackgroundImage},
classPrefix: "tr2",
text: "Scale Disabled",
styles: {
padding: 5,
},
disableScale: false,
},
],
offsetX: 40,
offsetY: 20,
zoom: 1,
};
this.workspaceRef = React.createRef();
}
Any ideas?
I also tried to do something like this:
Setting Background-Image in React ,
Syled Components Background Image React ,
Setting background image as prop in react
But it didn't seem to work
I also tried to put it inside the div, like this:
<div
className="element"
style={{
width: element.width,
height: element.height,
backgroundImage: this.state.backgroundImage,
...styles,
}}
>
<img src={element.backgroundImage.BackgroundImage} />
{element.text}
</div>
but then it ended up looking like this:
Door

Just a tiny little modification
change your json objects like
...
backgroundImage: BackgroundImage, //without curly braces
....
and in the div
style={{
....
backgroundImage: `url("${element.backgroundImage}")`,
...styles
}}
check it here

Related

Text on top of blurred Image

I am trying to create a custom card component in React and I want the content to be on top of the blurred background image. I read some examples but I cant seem to figure out the exact solution needed. Here is my code.
`
import React from "react";
import { motion } from "framer-motion";
export default function Pricing_Card({ title, image, children, heigth }) {
return (
<div
style={{
margin: 20,
// marginLeft: "10%",
width: "20%",
height: heigth,
borderRadius: "10px",
boxShadow: "3px 3px 3px #D3D3D3",
minWidth: "200px",
minHeight: "300px",
backgroundImage:
'url("https://www.thriftyfrugalmom.com/wp-content/uploads/2021/10/Meatless-Mexican-Rice-Bowls.jpg")',
backgroundSize: "cover",
filter: "blur(1px)",
}}
>
<div
style={{
position: "relative",
color: "black",
textAlign: "center",
fontSize: 30,
margin: 7,
fontWeight: "bold",
fontFamily: "Plus Jakarta Sans",
}}
>
{title}
</div>
<div>{children}</div>
</div>
);
}
`
I also attached an image to see exactly what I get the test2 has the blur effect.
Thanks in advance!

How to place icon at the end in linear progress bar MUI?

I'm using MUI v5 to build linear progress bar.I have a scenario where if value in progress bar is 100%,I need to show tick icon at the end.The width of the bar with/without tick icon should be same,meaning icon shouldn't be placed after the bar.It should be at the end of bar.I tried with stylings and able to place tick icon at the end.But I'm unable to show the icon clearly as the bar overlaps with tick icon.
<div style={{ display: "flex", flexDirection: "row", position: "relative", alignItems: "center" }}>
<LinearProgress
variant="determinate"
sx={{
width: "100%",
borderRadius: "4px"
}}
value={50}
/>
<CheckCircleIcon sx={{ color: "blue" }} style={{ position: "absolute", width: "20px", display: "flex", justifyContent: "flex-end", right: "-2px", color: "#fff", fontWeight: "bold" }} />
</div>
Current Design
Expected Design
Here is a live demo where I've customized an MUI Slider with a checkmark SliderThumb.
The demo includes the foundation for using this as a progress bar:
Disable the slider to ignore user input. Keep in mind that disabling will change the color to gray. You can override disabled behavior through .Mui-disabled
Set the slider's value using a state variable that corresponds to your current progress
You may also choose to customize a LinearProgress component in the same way I've customized the Slider above. See the docs for LinearProgress customization.
Full slider code:
import * as React from 'react'
import Slider, { SliderThumb } from '#mui/material/Slider'
import { styled } from '#mui/material/styles'
import Box from '#mui/material/Box'
import CheckCircleIcon from '#mui/icons-material/CheckCircle'
const CheckMarkSlider = styled(Slider)(({ theme }) =>
({
color: '#3a8589',
height: 3,
padding: '13px 0',
'& .MuiSlider-thumb':
{
height: 20,
width: 20,
backgroundColor: '#fff',
border: '1px solid currentColor',
'&:hover': {
boxShadow: '0 0 0 8px rgba(58, 133, 137, 0.16)',
},
'& .checkmark-bar':
{
height: 9,
width: 1,
backgroundColor: 'currentColor',
marginLeft: 1,
marginRight: 1,
},
},
'& .MuiSlider-track':
{
height: 3,
},
'& .MuiSlider-rail':
{
color: theme.palette.mode === 'dark' ? '#bfbfbf' : '#d8d8d8',
opacity: theme.palette.mode === 'dark' ? undefined : 1,
height: 3,
},
}))
const CheckMarkThumbComponent = (props) =>
{
const { children, ...other } = props
return (
<SliderThumb {...other}>
{children}
<CheckCircleIcon />
</SliderThumb>
)
}
const CustomizedSlider = () =>
{
const [value, setValue] = React.useState(20)
React.useEffect(() =>
{
const intervalId = setInterval(() => setValue(Math.random() * 100), 500)
return () => clearInterval(intervalId)
}, [value])
return (
<Box sx={{ width: 320 }}>
<CheckMarkSlider
value = {value}
disabled
components={{ Thumb: CheckMarkThumbComponent }} />
</Box>
)
}
export default CustomizedSlider

How To Transition React Elements That Already Have An Animation

I need some help merging an animation and a transition that occur at different times using react-spring.
When the component is mounted using useSpring I make the component appear, but I would like it so that when the button child is removed the container transitions smoothly upwards. Theres more details in the example.
https://codesandbox.io/s/naughty-dawn-r0e5x
PLEASE HELP :)
I created a solution. There is a new Spring animation mainly for the button, but we can use part of it for the original div. In this case the maxHeight property. So this way you can combine the animations.
import ReactDOM from "react-dom";
import React, { useState } from "react";
import { useSpring, animated } from "react-spring";
function WelcomeMessage() {
const [isStarted, setIsStarted] = useState(false);
const animation1 = useSpring({
right: "1%",
opacity: 1,
from: { right: "-20%", opacity: 0 },
delay: 300
});
const animation2 = useSpring({
opacity: isStarted ? 0 : 1,
maxHeight: isStarted ? 150 : 250,
transform: `translateY(${isStarted ? "-50px" : "0px"})`
});
return (
<animated.div
style={{
backgroundColor: "pink",
position: "fixed",
top: "2%",
right: "1%",
cursor: "default",
borderRadius: 5,
width: "90%",
maxWidth: 400,
...animation1,
maxHeight: animation2.maxHeight
}}
>
<div style={{ padding: "15px 25px" }}>
<span>
This is a toaster notification component. When you click the following
button it should disappear and the pink container's bottom section
should transition upwards when it decreases in height.
</span>
<br />
<br />
{
<animated.button
style={{ width: "100%", fontSize: 48, ...animation2 }}
onClick={() => {
setIsStarted(true);
}}
>
Get Started
</animated.button>
}
</div>
</animated.div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<WelcomeMessage />, rootElement);
Here is the example: https://codesandbox.io/s/green-star-nzfj8
Is this answer your question?

How to make Material-UI Snackbar not take up the whole screen width using anchorOrigin?

I have a class in React which uses an input field which is part of the website header:
If the input is invalid then I want to display a snackbar. I'm using Material-UI components.
The problem is I defined anchorOrigin to be center and top as per Material-UI API. However the snackbar takes up the whole screen width while I want it to only take up the top center location of the screen. My message is quite short, for example "Value invalid" but if it's longer then I should be able to use newlines. I'm not sure if there's some setting in Material-UI API to alter this (I couldn't find one) or I need to use CSS.
This is my code:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import InputBase from '#material-ui/core/InputBase';
import Snackbar from '#material-ui/core/Snackbar';
import SnackbarMessage from './SnackbarMessage.js';
const classes = theme => ({
inputRoot: {
color: 'inherit',
width: '100%',
},
inputInput: {
paddingTop: theme.spacing.unit,
paddingRight: theme.spacing.unit,
paddingBottom: theme.spacing.unit,
paddingLeft: theme.spacing.unit * 10,
transition: theme.transitions.create('width'),
width: '100%',
[theme.breakpoints.up('sm')]: {
width: 120,
'&:focus': {
width: 200,
},
},
}
});
class Test extends Component {
state = {
appId: '',
snackBarOpen: false
}
render() {
return (
<div>
<InputBase
placeholder="Search…"
classes={{
root: classes.inputRoot,
input: classes.inputInput,
}}
value={'test'} />
<Snackbar
anchorOrigin={{
vertical: 'top',
horizontal: 'center'
}}
open={true}
autoHideDuration={5000}
>
<SnackbarMessage
variant="warning"
message={"test message"}
/>
</Snackbar>
</div>
)
}
}
Material-UI set Snackbars to full viewport-width below the breakpoint "md" (600px).
You can use overrides (https://material-ui.com/customization/overrides/) and set new values to the default CSS classes of the component described in the components API (i.e. https://material-ui.com/api/snackbar/). So you can override the class anchorOriginTopCenter as follows:
const styles = theme => ({
anchorOriginTopCenter: {
[theme.breakpoints.down('md')]: {
top: "your value/function here",
justifyContent: 'center',
},
},
root: {
[theme.breakpoints.down('md')]: {
borderRadius: 4,
minWidth: "your value / function here",
},
},
});
The first objects overrides the default class {anchorOriginTopCenter}, the second 'root' is applied to first element in your snackbar (probably a 'div').
I do not know if we can add some style to the component anchor origin field. I think the div needs to be managed using CSS. It's an anchor, not style.
<Snakbar
className = "my-snakbar"
{/*All your other stuff*/}
>
{//Stuff}
</Snakbar>
CSS
.my-snakbar {
width: 200px;
//Maybe use flexbox for positioning then
}
Let me know your thoughts
Daniel
Improved Answer
Code copied from origional question and modified
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Snackbar from '#material-ui/core/Snackbar';
const classes = theme => ({
inputRoot: {
color: 'inherit',
width: '100%',
},
inputInput: {
paddingTop: theme.spacing.unit,
paddingRight: theme.spacing.unit,
paddingBottom: theme.spacing.unit,
paddingLeft: theme.spacing.unit * 10,
transition: theme.transitions.create('width'),
width: '100%',
[theme.breakpoints.up('sm')]: {
width: 120,
'&:focus': {
width: 200,
},
},
}
});
class ComingSoon extends Component {
render() {
const styles = {
container: {
position: "fixed",
top: "0px",
width: "100%",
height: "30px"
},
snakbar: {
background: "black",
color: "white",
width: "100px",
height: "100%",
display: "flex",
justifyContent: "center",
alignContent: "center",
margin: "0 auto"
}
};
return (
<div className = "snakbar-container" style = {styles.container}>
<Snackbar
className = "my-snakbar"
style = {styles.snakbar}
anchorOrigin={{
vertical: 'top',
horizontal: 'center'
}}
open={true}
autoHideDuration={5000}
>
<span>My Message</span>
</Snackbar>
</div>
)
}
}
export default ComingSoon;
Screen shot:
Let me know if this helped
Daniel

material-ui-next: Setting image size to fit a container

I've started out with Material-ui-next and have some problems with displaying images that they use the entire size of a container.
E.g. I use:
const styles = theme => ({
Card: {
width: 300,
margin: 'auto'
},
Media: {
height: 550
}
});
In render:
<Card className={classes.Card}>
<CardMedia
className={classes.Media}
image={ImgPomodoR}
title="a pomodoro tomatoe timer in material design"
/>
<CardContent>
<Typography gutterBottom variant="headline" component="h2">
...
The documentation says I have to specify a height for the image to get displayed. The 'media' example gives the image a height of 0, however, if I apply that my image is not getting displayed - mentioned example.
Right now, for me it's a trial and error of the Media-height, that it fits the Card container without being cropped.
Is there no 'auto' way of doing this?
Any help is highly appreciated,
cheers mates,
Tobias
Edit: I should mention that height: "100%" // maxHeight: "100%" does also not work for me.
I was having the same issue. Setting both width and height to '100%' worked for me.
const styles = theme => ({
Card: {
width: 300,
margin: 'auto'
},
Media: {
height: '100%',
width: '100%'
}
});
However, if your images have different heights, this will cause cards to be different heights and most of the time that is not what you want. For that, you can specify a height and keep the width at '100%'.
const styles = theme => ({
Card: {
width: 300,
margin: 'auto'
},
Media: {
height: 550,
width: '100%'
}
});
This will stretch the images to fit the container. For my case, I wanted part of the image to be shown without stretching the images. To achieve this, simply set the objectFit property to cover. This worked nicely for me.
const styles = theme => ({
Card: {
width: 300,
margin: 'auto'
},
Media: {
height: 550,
width: '100%',
objectFit: 'cover'
}
});
Hope this helps someone,
I think it would work
const styles = theme => ({
card:{
backgroundColor: 'white',
marginBottom: 40,
},
media: {
height: 0,
// paddingTop: '56.25%', // 16:9,
paddingTop: '100%', // 1:1,
},
});

Resources