Changing body image with an onClick Event - javascript

I was wondering how would I approach to change a body background image with onClick Event. Should I be using useRef hook or. I would really appriciate the help
body {
background: url("http");
background-position: center;
background-size: cover;
overflow-y: hidden;
overflow-x: hidden;
min-width: 100%;
}
function App() {
return (
<div>
<h1 onClick={...}> click here to change background image </h1>
</div>
);
}
export default App;

You can simply use document.body.style.backgroundImage like this:
import { useState } from "react";
import "./styles.css";
export default function App() {
const [counter, setCounter] = useState(0);
const IMAGES = [
"https://cdn.pixabay.com/photo/2012/08/25/22/22/saturn-54999_1280.jpg",
"https://cdn.pixabay.com/photo/2020/07/06/01/33/sky-5375005_1280.jpg",
"https://cdn.pixabay.com/photo/2011/12/14/12/23/solar-system-11111_1280.jpg"
];
const changeBodyBgImage = () => {
document.body.style.backgroundImage = `url(${IMAGES[counter]})`;
setCounter(counter > 2 ? 0 : counter + 1);
};
return (
<div className="App">
<h1 onClick={changeBodyBgImage}>Hello CodeSandbox</h1>
</div>
);
}
Here is the demo: https://codesandbox.io/s/serene-brook-82prg?file=/src/App.js:0-665

Use document.body to set the background changes you need.
The event handler should look like this.
onClick={() => {
document.body.style.background = ...
}}

Related

Connecting body background image to a state in next.js

I am trying to make a pomodoro timer using Next.js And I need to connect body's background image to a state. But my code doesn't work.
I used this code to update body style:
import { VscDebugRestart } from "react-icons/vsc";
import { IoMdSettings } from "react-icons/io";
import { AiFillPlayCircle, AiFillPauseCircle } from "react-icons/ai";
import { FaTasks } from "react-icons/fa";
import { Modal } from "#/components";
import { useModal } from "#/components/modal";
import { useEffect } from "react";
const Timer = () => {
const settingsModal = useModal();
const tasksModal = useModal();
// Update
useEffect(() => {
document.body.style.background =
"url('/images/city-3.jpg') no-repeat center center fixed;";
}, []);
return (
<div className="timer">
<div className="session-options">
<button className="btn">studying</button>
<button className="btn">short break</button>
<button className="btn">long break</button>
</div>
<h1 className="time-info">1:30:00</h1>
<div className="options">
<AiFillPlayCircle className="btn-icon" />
{/* <AiFillPauseCircle className="btn-icon" /> */}
<VscDebugRestart className="btn-icon" />
<IoMdSettings
className="btn-icon"
onClick={settingsModal.open}
/>
<FaTasks className="btn-icon" />
</div>
<Modal modal={settingsModal}>settings</Modal>
</div>
);
};
export default Timer;
But the styling doesn't apply and I can't see any failed requests to image. (I'm sure that image exists)
What can i do to fix it? Or are there any other solutions that makes the image fit in the background even if size changes?
Remove the semicolon from the background string, it is not CSS.
document.body.style.background = "url('/images/city-3.jpg') no-repeat center center fixed"
What a mistake! Anyways, thanks for the help. I fixed it and added the functionality:
const [bgImageName, setBgImageName] = useState<string | undefined>(
undefined
);
useEffect(() => {
setBgImageName("city-1.jpg");
}, []);
useEffect(() => {
document.body.style.background = ` rgba(0, 0, 0, .3) url("/images/${bgImageName}") no-repeat center center fixed`;
document.body.style.backgroundSize = "cover";
document.body.style.backgroundBlendMode = "darken";
}, [bgImageName]);

Change the background-color of the whole app on button click React.js

I am trying to change the color of the background of my whole React App on button click. However, I only change the color of the button itself. I am importing the App.css into my app and I want to dynamically change the CSS of the App from a separate function called ChangeColor. This function is then placed in my Header.js that is then placed in the App.js
Is there a way that I can do this? This is my code:
import React, {useState} from "react";
import Button from "react-bootstrap/esm/Button";
import '../../../App.css'
function ChangeColor() {
const [isActive, setIsActive] = useState(false);
const handleClick = () => {
setIsActive(current => !current);
};
return(
<Button
style={{
backgroundColor: isActive ? 'red' : '',
color: isActive ? 'white' : '',
}}
onClick={handleClick}
> Test </Button>
)
}
export default ChangeColor
.App {
text-align: center;
background-color: white;
}
There are a couple of solutions that come to mind.
Store the background color in state, and toggle between the colours depending on the current state.
(Small note - you shouldn't call your component ChangeColor as it's not really representative of what the component is - changeColor might be a good name for a function. You should call your component ButtonChangeColor, for example.)
const { useState } = React;
function Example() {
const [bgColor, setBgColor] = useState('white');
function toggleBackground() {
if (bgColor === 'white') setBgColor('black');
if (bgColor === 'black') setBgColor('white');
}
const appStyle = ['App', bgColor].join(' ');
return (
<div className={appStyle}>
<button onClick={toggleBackground}>
Toggle background
</button>
</div>
);
}
ReactDOM.render(
<Example />,
document.getElementById('react')
);
.App {
height: 100vh;
background-color: white;
}
.black { background-color: black; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Use CSS variables and modify the current stylesheet using the CSSStyleDeclaration interface - no state required. We can usefully maintain the toggleBackground function outside of the component because it doesn't rely on state to work.
function toggleBackground() {
const { style } = document.documentElement;
const bgColor = style.getPropertyValue('--bg-color');
if (bgColor === 'white' || bgColor === '') {
style.setProperty('--bg-color', 'black');
} else {
style.setProperty('--bg-color', 'white');
}
}
function Example() {
return (
<div className="App">
<button onClick={toggleBackground}>
Toggle background
</button>
</div>
);
}
ReactDOM.render(
<Example />,
document.getElementById('react')
);
:root { --bg-color: white; }
.App {
height: 100vh;
background-color: var(--bg-color);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
you can store isActive and color in localStorage
const [isActive, setIsActive] = useState(localStorage.getItem('is_active') || false);
const handleClick = () => {
setIsActive(current => !current);
};
<Button
style={{
backgroundColor: isActive ? 'red' : '',
color: isActive ? localStorage.getItem('bg_color') : '',
}}
onClick={handleClick}
> Test </Button>
The problem with your code is you are acting on the properties of the button. Instead you should act on the element its color you are trying to change.
In this code snippet the button modifies the color of the root div. Be aware that this solution is just to illustrate your problem. As has been stated by other users there are many ways to achieve what you want and some adhere to best practices while others not. Given the context of the question this answer just to points to why it is not working and not how best to do it. Please, refer to Andy's answer for more information about the latter.
const App = () => {
const changeAppColor = () => {
let el = document.getElementById("root");
if (el.style.backgroundColor === "red") {
el.style.backgroundColor = "unset";
} else {
el.style.backgroundColor = "red";
}
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={changeAppColor}>
Change color
</button>
</div>
);
}
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App />
);
<div id='root'> </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

How to add styles to individual elements in react using e.target, when a button is clicked?

I am trying to add styles to the inidividual elements. I want when an individual div( is clicked to make sure that the paragraph of the specific changes from display: none to dislay:block. But the problem is, when I click only on one , all the paragraph text is displayed.
here is the css below:
.cards{
background-color: red;
display: flex;
justify-content: center;
align-items: center;
height: 20vh;
}
[class*=cardDisplay]{
height: 80%;
display: flex;
align-items: center;
justify-content: center;
width: 200px;
background: black;
color: white;
margin: auto;
}
[class*=card-content]{
display: none;
}
[class*=card-content-2]{
display: block;
}
and the react.js file:
import React from 'react';
import {useState} from "react";
import "./game.css";
function Game() {
const [styling, setStyling] = useState("card-content")
const handleClick = () => {
setStyling("card-content-2")
}
return (
<div className="cards">
<div className="cardDisplay card-1" onClick={handleClick}>
<p className={styling}>Win</p>
</div>
<div className="cardDisplay card-2" onClick={handleClick}>
<p className={styling}>Sorry, No Win</p>
</div>
<div className="cardDisplay card-3" >
<p className={styling} onClick={handleClick}>Sorry, No Win</p>
</div>
</div>
)
}
You're using only one styling that you're applying to all paragraphs. If you want distinct styling for each paragraph, you have to hold that state separately for each paragraph.
Either:
Make the div+paragraph a component that holds its own state, or
Have multiple styling state members (perhaps an array).
I would lean toward the first:
function Card({className = "", children}) {
const [styling, setStyling] = useState("card-content");
const handleClick = () => {
setStyling("card-content-2")
};
return (
<div className={`cardDisplay ${className}`} onClick={handleClick}>
<p className={styling}>{children}</p>
</div>
);
};
function Game() {
return (
<div className="cards">
<Card className="card-1">Win</Card>
<Card className="card-2">Sorry, No Win</Card>
<Card className="card-3">Sorry, No Win</Card>
</div>
);
}
There's lots of ways to spin that, but that's the basic idea.
But there's also an argument for the cards being an array of objects with state; here's an example with the results randomized when the component is first mounted:
function makeCards() {
const num = 3;
const win = Math.floor(Math.random() * num);
return Array.from({length: 3}, (_, index) => ({
id: `card-${index}`,
result: index === win ? "Win" : "Sorry, No Win",
showing: false,
}));
}
function Game() {
const [cards, setCards] = useState(makeCards);
const handleClick = (event) => {
const id = event.currentTarget.getAttribute("data-id");
setCards(prevCards => {
const newCards = prevCards.map(card => {
if (card.id === id) {
return {...card, showing: true};
}
return card;
});
return newCards;
});
};
return (
<div className="cards">
{cards.map(({id, result, showing}) => (
<div key={id} data-id={id} className={`cardDisplay ${id}`} onClick={handleClick}>
<p className={showing ? "card-content" : "card-content-2"}>{result}</p>
</div>
))}
</div>
);
}
This may help you. It really works........
import React from 'react';
import {useState} from "react";
import "./game.css";
function Game() {
const handleClick = (e) => {
e.target.firstChild?.classList?.remove("card-content");
e.target.firstChild?.classList?.add("card-content-2");
};
return (
<div className="cards">
<div className="cardDisplay card-1" onClick={handleClick}>
<p className="card-content">Win</p>
</div>
<div className="cardDisplay card-2" onClick={handleClick}>
<p className="card-content">Sorry, No Win</p>
</div>
<div className="cardDisplay card-3" onClick={handleClick}>
<p className="card-content">Sorry, No Win</p>
</div>
</div>
);
}
What you are currently doing is changing the styling for each of the p tags.
I will advise you have a custom class that returns your div tag that contains the p tag
Have an array of Objects that contain the card style and the text that will be displayed. Map through the array and return the style and tags accordingly. As displayed below.
handle the click events in the custom div.
import React from 'react';
import "./game.css";
import MyDiv from './MyDiv';
const cards = [{ cardStyle: 'card-1', text: "Win" },
{ cardStyle: 'card-2', text: 'Sorry, No Win' },
{ cardStyle: 'card-3', text: 'Sorry, NoWin' }];
function Game() {
return (
<div className="cards">
{cards.map((card, index) =>
(<MyDiv cardNumberStyle={card.cardStyle}
key={index}
textToDisplay={card.text} />))
}
</div>
);
}
export default Game;
And then MyDiv is:
import React, { useState } from "react";
const MyDiv = ({ cardNumberStyle, textToDisplay }) => {
const [styling, setStyling] = useState('card-content');
///Handles clicks
const handleClick = () => {
//conditionally change the styling
if (styling === 'card-content')
setStyling('card-content-2')
else setStyling('card-content');
}
return (
<div className={`cardDisplay ${cardNumberStyle}`} onClick={handleClick}>
<p className={styling}>{textToDisplay}</p>
</div>
);
}
export default MyDiv;

Show hover on specific card in react

I am facing this problem. I want to show hover box on this box which is chosen. F.e when I hover on Box One I want to show Hover One, Box Two -> Hover Two. But in my example when I hover on One both are displayed. I am trying to do this with refs or e.target but always something is not as I want.
Link to stackblitz: https://stackblitz.com/edit/react-hc4741?file=src/App.js
import React, { useState } from "react";
import "./style.css";
import { BooksSection, BookCard, BookCardHover } from "./Styled";
export default function App() {
const [displayBookCardHover, setDisplayBookCardHover] = useState(false);
const showCardHover = () => {
setDisplayBookCardHover(true);
};
const hiddenCardHover = () => {
setDisplayBookCardHover(false);
};
return (
<div>
<BooksSection>
<BookCard
bgColor={"#000"}
color={"#fff"}
onMouseEnter={showCardHover}
onMouseLeave={hiddenCardHover}
>
<BookCardHover display={displayBookCardHover}>
Hover One
</BookCardHover>
Box One
</BookCard>
<BookCard
bgColor={"#fff"}
color={"#000"}
onMouseEnter={showCardHover}
onMouseLeave={hiddenCardHover}
>
<BookCardHover display={displayBookCardHover}>
Hover Two
</BookCardHover>
Box Two
</BookCard>
</BooksSection>
</div>
);
}
styled components
import styled from "styled-components";
export const BooksSection = styled.div`
display: flex;
flex-direction: row;
flex-wrap: wrap;
width: 100wh;
`;
export const BookCard = styled.div`
width: 50%;
height: 500px;
padding: 20px 0;
background: ${props => props.bgColor};
color: ${props => props.color};
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
position: relative;
`;
export const BookCardHover = styled.div`
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
font-size: 50px;
background: rgba(0, 0, 0, 0.7);
visibility: ${({ display }) => (display ? "100" : "hidden")};
`;
The problem is you have the exact same component with the exact same prop value in both places, so they will be shown/hidden at the same time no matter what you do to the displayBookCardHover value.
The trick is to use a separate value for each. Like this:
const [hoverIndex, setHoverIndex] = useState(-1);
...
const showCardHover = (index) => {
setHoverIndex(index);
}
const hiddenCardHover = () => {
setHoverIndex(-1);
}
...
<BookCard
...
onMouseEnter={() => showCardHover(0)}
...
>
<BookCardHover display={hoverIndex === 0}>
...
<BookCardHover display={hoverIndex === 1}>
Hope you get the idea.
On a side note, there's no "100" value for visibility prop. It's either "hidden" or "visible".
import React, { useState } from "react";
import "./style.css";
import { BooksSection, BookCard, BookCardHover } from "./Styled";
export default function App() {
const [displayBookCardHover, setDisplayBookCardHover] = useState({
boxOneHover: false,
boxTowHover: false
});
const showCardHover = box => {
if (box === 1) {
setDisplayBookCardHover(ps=>({ ...ps, boxOneHover: true }));
} else {
setDisplayBookCardHover(ps=>({ ...ps, boxTowHover: true }));
}
};
const hiddenCardHover = box => {
if (box === 1) {
setDisplayBookCardHover(ps=>({ ...ps, boxOneHover: false }));
} else {
setDisplayBookCardHover(ps=>({ ...ps, boxTowHover: false }));
}
};
return (
<div>
<BooksSection>
<BookCard
bgColor={"#000"}
color={"#fff"}
onMouseEnter={() => showCardHover(1)}
onMouseLeave={() => hiddenCardHover(1)}
>
<BookCardHover display={displayBookCardHover.boxOneHover}>
Hover One
</BookCardHover>
Box One
</BookCard>
<BookCard
bgColor={"#fff"}
color={"#000"}
onMouseEnter={() => showCardHover(2)}
onMouseLeave={() => hiddenCardHover(2)}
>
<BookCardHover display={displayBookCardHover.boxTowHover}>
Hover Two
</BookCardHover>
Box Two
</BookCard>
</BooksSection>
</div>
);
}
I think that the BookCard should be a component. Each one should have its own state. In App.js you can use BookCard and pass bgColor and color and whatever you want to customize each BookCard as props and use them in it.
The issue with your code is - both of the BookCardHover component base their state of the display using the same reference state displayBookCardHover, so, when one changes the value of displayBookCardHover, it automatically reflect on the other. I would recommend the approch suggested by #technophyle to seperate them.

How to get parent width/height in React using Hooks?

I'm creating a component and I need to get it's parent <div> width and height. I'm using Hooks, so all my components are functions. I've read some examples using classes, but this won't apply to my component.
So I have this component:
export default function PlantationMap(props) {
<div className="stage-canvas">
<Stage
width={window.innerWidth * 0.5}
height={window.innerHeight * 0.5}
onWheel={handleWheel}
scaleX={stage.stageScale}
scaleY={stage.stageScale}
x={stage.stageX}
y={stage.stageY}
draggable
/ >
</div>
}
How could I get the <div> height and width to use in <Stage width={} height={} />?
Thank you very much in advance
Edit: I tried using the useRef() hook, like this:
const div = useRef();
return (
<div ref={div}>
...
</div>
)
But I can't access the div.current object
I think useCallback is what you want to use so you can get the width and height when it changes.
const [height, setHeight] = useState(null);
const [width, setWidth] = useState(null);
const div = useCallback(node => {
if (node !== null) {
setHeight(node.getBoundingClientRect().height);
setWidth(node.getBoundingClientRect().width);
}
}, []);
return (
<div ref={div}>
...
</div>
)
Declare a reference using useRef hook and then read current.offsetHeight and current.offsetWidth properties.
Here is the code:
import React, { useEffect, useRef } from 'react';
const PlantationMap = (props) => {
const stageCanvasRef = useRef(null);
// useEffect will run on stageCanvasRef value assignment
useEffect( () => {
// The 'current' property contains info of the reference:
// align, title, ... , width, height, etc.
if(stageCanvasRef.current){
let height = stageCanvasRef.current.offsetHeight;
let width = stageCanvasRef.current.offsetWidth;
}
}, [stageCanvasRef]);
return(
<div className = "stage-canvas" ref = {stageCanvasRef}>
<Stage
width={window.innerWidth * 0.5}
height={window.innerHeight * 0.5}
onWheel={handleWheel}
scaleX={stage.stageScale}
scaleY={stage.stageScale}
x={stage.stageX}
y={stage.stageY}
draggable
/ >
</div>);
}
export default PlantationMap;
You can make use of the built-in ResizeObserver:
export default function PlantationMap(props) {
const [width, setWidth] = useState(100);
const [height, setHeight] = useState(100);
useEffect(() => {
const resizeObserver = new ResizeObserver((event) => {
// Depending on the layout, you may need to swap inlineSize with blockSize
// https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/contentBoxSize
setWidth(event[0].contentBoxSize[0].inlineSize);
setHeight(event[0].contentBoxSize[0].blockSize);
});
resizeObserver.observe(document.getElementById("div1"));
});
return (
<div id="div1" className="stage-canvas">
<Stage
width={width * 0.5}
height={height * 0.5}
onWheel={handleWheel}
scaleX={stage.stageScale}
scaleY={stage.stageScale}
x={stage.stageX}
y={stage.stageY}
draggable
/ >
</div>
);
}
I think ResizeObserver is the way to go as mentioned in the answer from Dan.
I just wouldn't use the document.getElementById. Either use useMeasure from react-use or create everything on your own.
There are two scenarios:
Component contains the container that you'd like to observe
Component is a child component and doesn't have the container reference
To 1 - Reference directly accessible
In this case, you can create the reference with useRef in the component and use it at resizeObserver.observe(demoRef.current).
import "./styles.css";
import React, { useEffect, useRef, useState } from "react";
const DisplaySize = ({ width, height }) => (
<div className="centered">
<h1>
{width.toFixed(0)}x{height.toFixed(0)}
</h1>
</div>
);
const Demo = () => {
const [width, setWidth] = useState(100);
const [height, setHeight] = useState(100);
const demoRef = useRef();
useEffect(() => {
const resizeObserver = new ResizeObserver((event) => {
// Depending on the layout, you may need to swap inlineSize with blockSize
// https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/contentBoxSize
setWidth(event[0].contentBoxSize[0].inlineSize);
setHeight(event[0].contentBoxSize[0].blockSize);
});
if (demoRef) {
resizeObserver.observe(demoRef.current);
}
}, [demoRef]);
return (
<div ref={demoRef} className="App">
<DisplaySize width={width} height={height} />
</div>
);
}; //);
export default function App() {
return <Demo />;
}
To 2 - Reference of container not directly accessible:
This case is probably happening more often and requires slightly more code.
You need to pass the reference from the parent to the child component with React.forwardRef.
Demo code can be found below or in the following Codesandbox
Some words to the code:
In the parent component you create a reference with const containerRef = useRef() and use it at the main container with <div ref={containerRef}/>. Under the hood it will do something like ref => containerRef.current=ref
Next, pass the reference to the Demo component.
Why not use React.createRef?
That would work too but it would recreate the reference on every render of your App. Please have a look here for an explanation of the difference between useRef and createRef.
In short, use useRef with functional components and use createRef with class-based components.
const {useEffect, useRef, useState} = React;
const DisplaySize = ({ width, height }) => (
<div className="centered">
<h1>
{width.toFixed(0)}x{height.toFixed(0)}
</h1>
</div>
);
const Demo = React.forwardRef((props, ref) => {
const [width, setWidth] = useState(100);
const [height, setHeight] = useState(100);
useEffect(() => {
const resizeObserver = new ResizeObserver((event) => {
// Depending on the layout, you may need to swap inlineSize with blockSize
// https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/contentBoxSize
setWidth(event[0].contentBoxSize[0].inlineSize);
setHeight(event[0].contentBoxSize[0].blockSize);
});
if (ref && ref.current) {
resizeObserver.observe(ref.current);
}
}, [ref]);
return <DisplaySize width={width} height={height} />;
});
function App() {
const containerRef = useRef();
return (
<div ref={containerRef} className="App">
<Demo ref={containerRef} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<App />,
rootElement
);
/* apply a natural box layout model to all elements, but allowing components to change */
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
html,
body {
margin: 0;
padding: 0;
}
.App {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden;
font-family: sans-serif;
text-align: center;
border: 4px solid red;
}
.centered {
display: flex; /* establish flex container */
flex-direction: column; /* make main axis vertical */
justify-content: center; /* center items vertically, in this case */
align-items: center; /* center items horizontally, in this case */
height: 100%;
}
<script crossorigin src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<div id="root"></div>
Library React-use
There are also some useful hooks in React-use that could help here.
useWindowSize and useSize look pretty similar but after looking at the source code the first one relies on the window.onresize event and requires less code to implement.
useSize will add an iframe below the current component (z-index: -1) to track the size with resize event and requires more code. It also adds a little debounce with setTimeout.
So use useWindowSize if you just need the width/height to do some calculations on the first render and useSize if you'd like to show that the size changed.
useWindowSize
If you just need to get the window size useWindowSize is the way to go.
They're doing it with onresize event with document.addEventlistener('resize', resizeHandler) and checking innerWidth / innerHeight
Codesandbox Demo
useMeasure
To track an element size, useMeasure can be used. It is using ResizeObserver under the hood, so it's like the code above where ref is the reference you'd like to track:
The first element returned by useMeasure is the setRef method.
So you can do the following in your component:
const [setRef, { width, height }] = useMeasure();
useEffect(() => {
setRef(ref.current)
}, [])
Please have a look at the following Codesandbox.
useSize
If you want to track the size of a component useSize could be used as mentioned in the docs.
Codesandbox Demo useSize
to my knowledge if it is concerned with style can only be registered by:
<Stage style={{width:window.innerWidth * 0.5,height:width:window.innerWidth * 0.5}} />

Categories