Chrome shows illegal invocation when running react - javascript

I am trying to change classes of my component's div tag. But I get illegal invocation. Here's my code.
I don't know what I am doing wrong? I am new to react and javascript. I am trying to float my div with id of power to left or right conditionally like a toggle switch. I get the error when I click on the div. Not in the beginning.
let power = false;
let bank;
let target = document.getElementById;
function powerButton() {
power = !power;
if (power) {
target("power").className = "float-right";
} else {
target("power").className = "float-left";
}
}
class App extends React.Component {
// eslint-disable-next-line no-useless-constructor
constructor(props) {
super(props);
}
render() {
return (
<
<div
id="controls"
className=" d-inline-block float-right mt-5 text-center font-weight-bold "
style={{ marginRight: "40px" }}
>
<p style={{ margin: "0" }}>Power</p>
<div
onClick={powerButton}
className=" mx-auto"
style={{
width: "54px",
height: "24px",
padding: "2px",
backgroundColor: "black",
}}
>
<div
id="power"
style={{
backgroundColor: "blue",
width: "23px",
height: "19px",
border: "1px solid black",
}}
/>
</div>
<p
style={{
padding: "15px 0px",
width: "200px",
height: "45px",
lineHeight: "22px",
margin: "15px 0px ",
backgroundColor: "grey",
}}
>
AAA
</p>
<div style={{ marginBottom: "5px" }}>
<input style={{ color: "black" }} type="range" />
</div>
<p style={{ margin: "0" }}>Bank</p>
<div
className=" mx-auto"
style={{
width: "54px",
height: "24px",
padding: "2px",
backgroundColor: "black",
}}
>
<div
id="bank"
style={{
backgroundColor: "blue",
width: "23px",
height: "19px",
border: "1px solid black",
}}
/>
</div>
</div>
</div>
</div>
);
}
}

You have that error because you've lost the "context" of the function, I mean "document". To resolve this, use .bind in newer versions of Javascript:
if (power) {
target.bind(document)("power").className = "float-right";
} else {
target.bind(document)("power").className = "float-left";
}

The illegal invocation is because of wrong context i.e. getElementById is not being called by the document object. Also in React, do things via state updates and not direct DOM manipulation. You first need to understand core JavaScript concepts and learn React concepts from documentation.

Related

Render single component on hover

I currently have two avatars that are rendered on a page. On hover I want a card to pop up that displays player information.
Currently when hovering on the first avatar both player cards pop up and i only want the card of the avatar that is hovered over.
The second issue is that on hover of the second avatar nothing happens.
I'd like the card of the avatar that is hovered to only pop up.
function Profiles() {
const { hovered, ref } = useHover();
return (
<Container style={{ display: "flex" }}>
<div ref={ref}>
{hovered ? (
<PlayerOne />
) : (
<Avatar
radius="xl"
size="xl"
src={tobias}
style={{ border: "black solid .1rem" }}
sx={(theme) => ({
backgroundColor: theme.colors.yellow[1],
"&:hover": {
backgroundColor: theme.colors.yellow[3],
},
})}
/>
)}
</div>
<div>
{hovered ? (
<PlayerTwo />
) : (
<Avatar
radius="xl"
size="xl"
src={vij}
style={{ border: "black solid .1rem" }}
sx={(theme) => ({
backgroundColor: theme.colors.yellow[1],
"&:hover": {
backgroundColor: theme.colors.yellow[3],
},
})}
/>
)}
</div>
</Container>
);
}
export default Profiles;
this makes sense but just use good old CSS. oh and if using React its className of course, not class
<div class="parent">
<div class="child1">
<PlayerOne />
</div>
<div class="child2">
<Avatar
radius="xl"
size="xl"
src={vij}
style={{ border: "black solid .1rem" }}
sx={(theme) => ({
backgroundColor: theme.colors.yellow[1],
"&:hover": {
backgroundColor: theme.colors.yellow[3],
},
})}
/>
</div>
</div>
<div class="parent">
<div class="child1">
<PlayerTwo />
</div>
<div class="child2">
<Avatar
radius="xl"
size="xl"
src={tobias}
style={{ border: "black solid .1rem" }}
sx={(theme) => ({
backgroundColor: theme.colors.yellow[1],
"&:hover": {
backgroundColor: theme.colors.yellow[3],
},
})}
/>
</div>
</div>
in your CSS
.child1 { display: none; }
.parent:hover > .child1 { display: none; }
.parent:hover > .child2 { display: block; }

How can I save this page to localStorage

When I deploy my application.
Each time I refresh the brown. I get a message saying page not found.
I know that React JS is a memory based applicaion, it does not store anything.
If I need to, I will have to use localStorage and many other options out there like IndexedDB, cookies etc.
My problem is, what I need to store to localStorage in not a function or method. My page has only content.
How do I add that to localStorage or what do I do ?
import React, { useState, useEffect } from "react";
import {Link, generatePath } from "react-router-dom";
import Navigationbar from "../components/navigationbar/navigationbar";
import ProductsHeader from "../components/products-header/ProductsHeader";
import Shopbybrand from "../components/shopbybrand/shopbybrand";
import Footer from "../components/footer/footer";
const Products = ({ products, countCartItem }) => {
return (
<>
<div style={{ background: "transparent", display: "flow-root" }}>
<div
className="productDetails"
style={{
display: "block",
background: "black",
borderRadius: " 0 0 30px 30px",
padding: 20,
marginBottom: 30,
}}
>
<Navigationbar countCartItem={countCartItem} />
<ProductsHeader />
</div>
<div className="container">
<div>
<span style={{ fontSize: 12, fontWeight: 700 }}>Vouchers</span>
<br />
<span style={{ fontSize: 40, fontWeight: 700, }}>Discover</span>
<ul
style={{
listStyle: "none",
padding: 0,
paddingTop: 50,
maxWidth: 1800,
margin: "0 auto",
display: "flex",
flexWrap: "wrap",
justifyContent: "start"
}}
>
{products.map((item) => (
<li
key={item.ProductCode}
style={{ paddingBottom: 15, maxWidth: 240, float: "", display: "flex", margin: "9px" }}
>
<Link
to={generatePath(
"/itemDetail/:ProductCode/:FaceValue/:Vendor/",
{
ProductCode: item.ProductCode,
FaceValue: item.FaceValue,
// Vendor: item.Vendor.replaceAll(/\W/g, "")
Vendor: item.Vendor,
Vat: item.Vat,
}
)}
>
<div
className="card"
style={{ margin: 0, borderRadius: 25, backgroundColor: "#white" }}
>
<img
src={item.Logo}
className="card-img-top"
alt="..."
style={{ width: "390px !important", borderRadius: 25 }}
/>
<div style={{ marginTop: "10px", margin: 20 }}>
<p style={{color: "black"}}>{item.Vendor}</p>
<h6 style={{ fontSize: 19, fontWeight: 600, color: "black" }}>
{item.Description}
</h6>
<h2 style={{ fontSize: 26, fontWeight: 700, color: "black" }}>
R {item.FaceValue}{" "}
<span style={{ display: "none", color: "black" }}>{item.Vat} </span>
</h2>
</div>
</div>
</Link>
</li>
))}
</ul>
</div>
</div>
</div>
<div style={{ display: "flex !important", background: "white", marginTop: 65 }}>
<Shopbybrand />
<Footer />
</div>
</>
);
};
export default Products;
Actually, when you deploy your react app to Netlify it shows error so, to resolve it Add a new file name _redirects inside your build folder & paste the below content-
/* /index.html 200
Now push your new changes to server.

React Js - Styling innerHTML on component - Not working - Parent styling is overriding child styling

I have two react components.
List container
List
The list needs to be inside the list container. Like so:
<Container innerhtml={<List></List>} ></Container>
The content of both components renders. However the styling of the child is overridden by the parents styling. (In this case, the background color)
This is the full code:
import React from "react";
export default function main() {
return <div>
<Container
innerhtml={<List></List>}
></Container>
</div>
}
function List() {
return <div style={{ backgroundColor: "#red!important", height: "150px", width: "150px" }}>
this is a list
</div>
}
function Container(props) {
return <div style={{ backgroundColor: "#94e49d38", height: "400px", width: "100vw-10px" }}>
this is container
{props.innerhtml}
</div>
}
I think it may be a similar thing to this: Style not working for innerHTML in Angular
However I cant find a React equivalent.
How can I get the list style to work?
Thank you
By refactoring a bit your code I found this Solution:
export default function Main() {
return (
<div>
<Container>
<List></List>
</Container>
</div>
);
}
function List() {
return (
<div style={{ backgroundColor: "red", height: "150px", width: "150px" }}>
this is a list
</div>
);
}
function Container(props) {
return (
<div
style={{
backgroundColor: "#94e49d38",
height: "400px",
width: "100vw-10px"
}}
>
{props.children}
</div>
);
}
by passing props.childreninstead of innerHtml and by removing the "#" before red this works fine, see the sandbox
import React from "react";
export default function Main() {
return (
<div>
<Container>
<List/>
</Container>
</div>
}
function List() {
return (
<div style={{ backgroundColor: "#75e936", height: "150px", width: "150px" }}>
this is a list
</div>
}
function Container(props) {
return(
<div style={{ backgroundColor: "#94e49d38", height: "400px", width: "100vw-10px" }}>
this is container
{props.children}
</div>
)
}
You put hashtag which is not required.
Change from
backgroundColor: "#red !important"
to
backgroundColor: "red !important"
#red is an invalid property value. It should be red as shown below.
backgroundColor: " red !important"

React - how to apply local storage for hook value

I use the react-range package for personal purposes of my project, the problem is that I cannot save the value when the page is refreshed, I tried to use the local storage but I could not
As you understand, I need to save the value using local storage, in addition, I will leave a link to mine on codesandbox link
SideBarBlurChange.jsx
import React, {useEffect, useState} from "react";
import {getTrackBackground, Range} from "react-range";
const STEP = 0.1;
const MIN = 0;
const MAX = 100;
export default function SideBarBlurChange(props) {
const [values, SetValues] = useState([20])
const SaveChanges = () => {
alert(values)
}
return (
<>
<div
style={{
display: "flex",
justifyContent: "center",
flexWrap: "wrap",
}}
>
<Range
values={values}
step={STEP}
min={MIN}
max={MAX}
onChange={(values) => SetValues(values)}
renderTrack={({ props, children }) => (
<div
onMouseDown={props.onMouseDown}
onTouchStart={props.onTouchStart}
style={{
...props.style,
height: "36px",
display: "flex",
width: "100%"
}}
>
<div
ref={props.ref}
style={{
height: "5px",
width: "100%",
borderRadius: "4px",
background: getTrackBackground({
values: values,
colors: ["#548BF4", "#ccc"],
min: MIN,
max: MAX
}),
alignSelf: "center"
}}
>
{children}
</div>
</div>
)}
renderThumb={({ props, isDragged }) => (
<div
{...props}
style={{
...props.style,
height: "42px",
width: "42px",
borderRadius: "4px",
backgroundColor: "#FFF",
display: "flex",
justifyContent: "center",
alignItems: "center",
boxShadow: "0px 2px 6px #AAA"
}}
>
<div
style={{
height: "16px",
width: "5px",
backgroundColor: isDragged ? "#548BF4" : "#CCC"
}}
/>
</div>
)}
/>
<output style={{ marginTop: "30px" }} id="output">
{values[0].toFixed(1)}
</output>
<button onClick={() => SaveChanges()}>Save</button>
</div>
</>
);
}
I think your main problem was that localStorage doesn't store anything besides strings. You're going to want to parseInt then check to make sure localStorage isn't null. Can you try this and see if it works?
const ls = parseInt(window.localStorage.getItem('values'));
const [values, SetValues] = useState(ls ? [ls] : [20]);
const SaveChanges = () => {
alert(values);
localStorage.setItem('values', values);
}

error try set style array to element with react js

When try assign a style to element, I recive the next error.
Error: Objects are not valid as a React child (found: object with keys {border, padding, whiteSpace, textOverflow, overflow, position, float, height, width}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Gridnamic`.
I tried use Object.assign, set the array inline style={{width: "45px"}} and doesnt work.
My array style is:
var styles = {
columns: {
border: "1px solid #ddd",
padding: "5px",
whiteSpace: "nowrap",
textOverflow: "ellipsis",
overflow:"hidden",
position: "relative",
float: "left",
height: "45px",
width: "200px"
},
columnSelect: {
border: "1px solid #ddd",
padding: "5px",
whiteSpace: "nowrap",
textOverflow: "ellipsis",
overflow:"hidden",
position: "relative",
float: "left",
height: "45px",
width: "50px"
}
};
And my render method is:
return <div>
<p>{this.state.selected.length} seleccionados</p>
<div className="table-responsive">
<div style={styles.row}>
<div style={styles.rowContent}>
<div style={styles.columnSelect}><input type="checkbox" onClick={this.selectElement.bind(this)} className="selectAll"/></div>
{this.state.columns.map(column =>
<div style={styles.columns} key={column.name}>{column.title}</div>
)}
</div>
</div>
<div style={styles.row}>
<div style={styles.rowContent}>
<div> style={styles.columnSelect}</div>
{this.state.columns.map(column =>
<div style={styles.columns} key={column.name}>
<input placeholder="Buscar" className="form-control" ref={'filter-'+column.name} name={column.name} onChange={this.filter.bind(this)} />
</div>
)}
</div>
</div>
</div>
<p>{this.state.rows.length} registros.</p>
</div>;
Thanks developers.
Chill
The issue is here: <div> style={styles.columnSelect}</div>. Probably meant to do <div style={styles.columnSelect}></div> .

Categories

Resources