Change the background image dynamically - javascript

I would like to modify the image in the background with the help of a comment.
The images come from the tmdb API.
So I think you have to create a background image component and pass it on to the URL.
I know that CSS has the background-image property, but it works for static images ...
What is the best method, I would like to make this component reusable.

Here is how you would have to do it.
Create your <div> and its style with a default background-image
Create 3 <button> to triggers your function changeImage() and provide a parameter
Change the style.backgroundImage with JavaScript such as below:
function changeImage(category){
document.getElementById('div-bg').style.backgroundImage = 'url("https://source.unsplash.com/320x240/?' + category + '")';
}
#div-bg {
display: block;
width: 320px;
height: 240px;
background-image: url("https://source.unsplash.com/320x240/?sky");
}
<div id="div-bg"></div>
<button onclick="changeImage('nature')">Nature</button>
<button onclick="changeImage('animal')">Animal</button>
<button onclick="changeImage('fire')">Fire</button>
If you have any question, please ask!

By doing this it works, I have my background. But I did not manage to do it with a reusable component
import React from 'react';
const VideoDetail = ({ title, description, background }) => {
const IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500/";
const backgroundStyle = {
color: 'white',
backgroundRepeat: 'no-repeat',
backgroundAttachment: 'scroll',
backgroundPosition: 'center',
backgroundSize: 'cover',
width: "100%",
height: "400px",
backgroundImage: `url(${IMAGE_BASE_URL}${background})`
};
return(
<div>
<div style={background !== undefined ? backgroundStyle : null }>
<h1>{title}</h1>
<p>{description}</p>
</div>
</div>
)
}
export default VideoDetail;import React from 'react';

Related

Convert from css to makestyle material UI

I want to add an iconButton and display a website preview when the mouse hover the help icon. I found something similar using css but I need to convert that to material UI.
This is the css code to be converted from this post How to show live preview in a small popup of linked page on mouse over on link?
.box{
display: none;
width: 100%;
}
a:hover + .box,.box:hover{
display: block;
position: relative;
z-index: 100;
}
This is what I have so far:
const HoverText = () => {
return (
<div className={classes.box}>
<iframe src="https://en.wikipedia.org/" width="500px" height="500px">
</iframe>
</div>
);
};
return (
<>
<IconButton size="large" color="inherit" onClick={() => window.open("https://en.wikipedia.org/", "_blank")}>
<HelpIcon className={classes.act} />
<HoverText />
</IconButton>
</>
);
Could you please help me to fix this:
const useStyles = makeStyles((theme: Theme) =>
createStyles({
box: {
width: '100%',
display: 'none'
},
act: {
"&:hover + .box, .box:hover": {
display: 'block',
position: 'relative',
zIndex: 100
}
}
}),
);
Im expect to display a preview of a website page when mouse is over the icon.
You have to use the $ character when referencing another rule name. I changed a code a bit, use classes.act on IconButton (the hover effect will be better), and use the following:
const useStyles = makeStyles(() =>
createStyles({
box: {
width: 0,
height: 0,
display: "none"
},
act: {
"&:hover $box": {
display: "block",
zIndex: 100
}
}
})
);
Use $box instead of .box.
There is no box class generated when you compile your code (You can inspect your code and see what it compiles to). So the .box class selector does not work because there is no box class.
You should use $ to select another local rule or class within the same stylesheet. Read more.
"&:hover + $box, $box:hover"

React doesn't insert image as background

I'm creating a web page and I took a jpg and pgn image to put as a background.
But by no means does it appear on the page.
import './Entrada.css'
const Entrada = () => {
return(
<div style={{
backgroundImage: "url(/secoes_02.jpg)"
}}>
<div><img src='secoes_02.jpg'/></div>
<div className='texto'>testatastastasta</div>
</div>
)
}
export default Entrada
In the code above I can place the image as a figure, but I cannot as a background.
I've already tried to insert it by Css and tried import to.
.geral{
background: url("/public/img/partes/secoes_02.jpg");
}
But in no way does it appear in my react.
I already reinstalled the nodejs packages and changed the folder location.
And the error continues.
Has anyone experienced this?
Try it plz. It works for me.
import footer from '../../assets/images/footer.png';
function MyComponent() {
return (
<footer style={{ background: `url(${footer})`, backgroundSize: "contain" }}>
Try this.. worked for me
js:
render() {
return (
<div className="bgimage">
<div className='texto'>testatastastasta</div>
</div>
)
}
css:
.bgimage {
background-position: center;
background-repeat: no-repeat;
background-size: cover;
height: 100%;
background-image: url(https://business.adobe.com/content/dam/dx/us/en/products/magento/open-source/open-source-marquee-2x.png.img.png);
}
Height is given 100%, based on your need you can adjust.

Properties background image not working [React]

I'm trying to set the background image of a div depending on the value of a component property, the background doesn't show, however it does show when I harcode the background-image property in the css file.
Here is the component code :
import React, { Component } from "react";
import "./Banner.css";
export default class Banner extends Component {
render() {
const style = {
backgroundImage: `url("${this.props.image}")`,
};
return (
<div className="banner" style={style}>
Chez vous, partout et ailleurs
</div>
);
}
}
Here is the Banner.css file:
.banner {
/* background-image: url("../assets/images/moutains.png"); */
background-size: cover;
height: 170px;
border-radius: 20px;
text-align: center;
vertical-align: middle;
line-height: 170px;
font-size: 2.5rem;
color: #fff;
}
In the parent component:
<Banner image="../assets/images/moutains.png" text="" />
EDIT: Complete code and assets here: https://github.com/musk-coding/kasa
codesandbox: https://codesandbox.io/s/github/musk-coding/kasa
Thanks in advance for your help
Since, you are trying to access the image directly in your Component using the inline CSS. You must move your image to the public folder.
CODESANDBOX LINK: https://codesandbox.io/s/image-relative-path-issue-orbkw?file=/src/components/Home.js
Code Changes:
export default class Home extends Component {
render() {
const imageURL = "./assets/images/island-waves.png";
return (
<div className="container">
<div className="slogan" style={{ backgroundImage: `url(${imageURL})` }}>
Chez vous, partout et ailleurs
</div>
<Gallery />
</div>
);
}
}
NOTE: From React Docs, you can see the ways to add images in Component. create-reac-app-images-docs. But since you want an inline CSS, in that case we have to move our assets folder into the public folder to make sure that the image is properly referenced with our component.

Cannot fit inner image into its parent container on this ReactJS app

I have one very basic ReactJS component called: Designer which displays the Eiffel Tower as well as a bottom panel with some controls in it.
The Designer is inside a div with the following size: { width: 510px, height: 300px}.
The Eiffel Tower image has the following size: { width: 300px, height: 800px}.
This is the current rendered output of the Designer:
But my problem is that the Eiffel Tower image is not getting fit into its parent div.
My goal is what you can see on the following image:
If on the file: /src/CanvasCrop/CanvasCrop we do: let showImage = false;, we get the following:
so, we confirm that its parent div (green background) gets sized accordingly having its own width and height whether the image is getting shown or not.
Here is its source code (original):
/src/CanvasCrop/CanvasCrop:
import React, { Component } from "react";
import "./CanvasCrop.scss";
class CanvasCrop extends Component {
render() {
let showImage = true;
return (
<div className="partial-designer-canvas-crop">
<div>
{
showImage &&
<img
src="https://i.ibb.co/DKxRFtb/image.jpg"
style={{
maxWidth: "100%",
maxHeight: "100%",
transform: "scale(-50%, -50%)"
}}
alt="target"
/>
}
</div>
</div>
);
}
}
export default CanvasCrop;
Here is the outer source code:
/index.js:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.scss";
import Designer from "./Designer/Designer";
function App() {
return (
<div>
<span class="title">Trying to fit Eiffel Tower</span>
<div className="App"
style={{
// keep this as it is
overflow: 'auto',
width: '510px',
height: '300px',
}}
>
<Designer />
</div>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Here you have the CodeSandbox.io you can experiment with:
https://codesandbox.io/s/7jv56qr1yx
Could you please, provide back a fork of the above CodeSandbox.io with the Eiffel Tower fitted into its parent div without setting manually a fixed width / height?
Side note: if instead of a portrait image, we use a landscape image, it should also fit into its parent div without going beyond its limits.
Example image (size: { width: 800px, height: 300px}):
https://i.stack.imgur.com/jUeCD.jpg
Thanks!
If I understand your problem correctly, it looks like you are missing a height: 100% on your .partial-designer-canvas.
Here, try this:
https://codesandbox.io/s/x664y69ow
I only changed src/Canvas/Canvas.scss. You can add a calc to account for your tool bar too, like so:
.partial-designer-canvas {height: calc(100% - 60px)}

How to bypass React's error handling of colors

Trying to figure out if there is away of bypassing React's error handling for colors.
The first inner DIV serves as a default with an empty background if a user inputs a color that is incorrect, whether a Hex color or a string.
The second inner DIV sits on top of the first, and is meant to display the color of this.props.value.
This works fine to show my emptyBackground value in the first div, and when a correct color is inputed by the user, say orange, the second div will display a background color of orange, overlapping the first.
Now if I were to change orange to orangered, this div will change to orangered.
The part I am trying to get around is when I type orangere, it will still show the original orange color instead of the default background of the second div. It seems that react will not prompt a re-render when an improper color has been entered. Any way to get around this?
export default class ColorRender extends Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
}
onChange(e) {
this.props.onChange(e.target.value);
}
render() {
const disabled = this.props.disabled || this.props.readonly;
return (
<div
style={{ position: 'relative' }}
>
<input
type="text"
value={this.props.value}
placeholder={this.props.placeholder}
onChange={this.onChange}
style={{
marginBottom: 20,
width: `calc(100% - ${COLOR_BOX_WIDTH}px - ${COLOR_BOX_MARGIN_RIGHT}px - ${COLOR_BOX_MARGIN_LEFT}px)`,
}}
disabled={disabled}
/>
<div
style={{
...contentStyle,
backgroundImage: `url(${emptyBackground})`,
}}
/>
<div
className="color-display"
style={{
...contentStyle,
backgroundColor: this.props.value,
zIndex: 1000,
}}
/>
</div>
);
}
}
This behavior has nothing to do with React. Modern browsers will simply ignore attempts to set color properties to an unsupported value. You can easily try this yourself by opening up the dev console, selecting a DOM element somehow, and setting its color to orange with something like myElement.style.backgroundColor = 'orange'. Then try setting it to an invalid value like 'orangere'. The element will remain orange instead of reverting to an default or inherited value.
Probably the best way to address this would be to manually check that the user input is a valid color. Something like the is-color package will check not only if it's a valid color name, but HEX and RGB values as well. If the user input is valid, have React render it as usual. But if it's invalid, you can catch that and use a default or inherited value instead.
Although, this is a standard DOM element behavior (as noted by #jered), you can override it with react.
Wrap the .color-display div with another div (the .color-display-wrapper), and set the default color on it. Update the .color-display background via a CSS variable. If the value in the variable is invalid, the background color would be transparent, and the wrapper's background would be displayed.
class ColorRender extends React.Component {
state = { color: 'orange' };
onChange = (e) => this.setState({ color: e.target.value });
render() {
const {color} = this.state;
return (
<div>
<input type="text" onChange={this.onChange} />
<div className="color-display-wrapper">
<div
className="color-display"
style={{ '--color': color }}
/>
</div>
</div>
);
}
}
ReactDOM.render(
<ColorRender />,
demo
);
:root {
--color: transparent;
}
.color-display-wrapper {
width: 200px;
height: 200px;
background: url(https://picsum.photos/200/200);
}
.color-display {
position: relative;
background: var(--color);
height: 100%;
}
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="demo"></div>

Categories