I'm quite new to React, and I'm trying to use Parallax.js library in react. Now I have done the basics and installed the library using npm, I have imported the library and I have followed this topic that related to my question.
But now I'm having difficulty to make parallax work, I recieve the following error:
index.js:1 Warning: React does not recognize the `dataDepth` prop on a DOM element. If you intentionally
want it to appear in the DOM as a custom attribute, spell it as lowercase `datadepth` instead. If you accidentally passed it from a parent component, remove it from the DOM element.
in li (at home.js:17)
in ul (at home.js:16)
in section (at home.js:15)
in ParallaxComponent (at App.js:7)
in App (at src/index.js:9)
in StrictMode (at src/index.js:8)
And this is my code
import React, { Component } from 'react'
import './css/style.css';
import headerbg from './images/header-bg.svg';
import Parallax from 'parallax-js' // Now published on NPM
class ParallaxComponent extends Component {
componentDidMount() {
this.parallax = new Parallax(this.scene)
}
componentWillUnmount() {
this.parallax.disable()
}
render() {
return (
<section className="header">
<ul ref={el => this.scene = el}>
<li className="layer" dataDepth="1.00">
<img src={headerbg} alt="Header background"/>
</li>
</ul>
<div className="content">
<h1>אנחנו דואגים להכל</h1>
<h2>אתם רק צריכים לאשר</h2>
<p>
אצלנו ב Triple V אין פשרות, איכות היא המטרה העליונה! <br/>
כל האתרים שלנו נבנים תחת פלטפורמת וורדפרס עם ציוני <br/>
מהירות שלא יורדים מ80 למובייל! <br/>
למה זה חשוב אתם שואלים? גוגל אוהב מהירות
<br/>
ככל שהאתר שלכם יותר מהיר ככה גוגל יותר מרוצה.
</p>
</div>
</section>
)
}
}
export default ParallaxComponent;
How can I run Parallax.js inside React library properly?
Try using data-depth attribute instead of DataDepth on your layers.
Related
I have followed this tutorial to make a hamburger menu in react/next.js: https://youtu.be/prbOI7G0RvY
import { useState } from "react";
import user from '../styles/userview.module.css'
export function PageHeader() {
const [isOpen, setIsOpen] = useState(false);
const openMenu= ()=> setIsOpen(!isOpen);
return (
<header className={user.header}>
<nav className={user.navbar}>
<a className={user.navlogo}>[BrandLogo]</a>
<ul className={isOpen === false ?
user.navmenu : user.navmenu + ' ' + user.active}>
<li className={user.navitem}>
<a className={user.navlink}>Home</a>
</li>
<li className={user.navitem}>
<a className={user.navlink}>About</a>
</li>
<li className={user.navitem}>
<a className={user.navlink}>Contact</a>
</li>
</ul>
<button className={isOpen === false ? user.hamburger : user.hamburger + ' ' + user.active}
onClick= {openMenu}
>
<span className={user.bar}></span>
<span className={user.bar}></span>
<span className={user.bar}></span>
</button>
</nav>
</header>
)
}
But I keep getting this error message:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
It also indicates the problem is at this row: const [isOpen, setIsOpen] = useState(false);
Can someone please help me to understand what is wrong?
EDIT:
Here is a picture of the exact error message: https://pasteboard.co/3xyAu6m8IeAW.png
EDIT 2:
I opened up my repo so you can see/test it on your own. Maybe the fault is in another file? The burgermenu is in the main-branch and ..components/userview and the page that imports and show the burgermenu is ../pages/hamburgertestfile.
You cant call hooks from a regular javascript function as specified in the docs, therefore try importing React in your first line to convert the javascript function into a React function
import React, { useState } from "react";
The answer was provided by a user of the Next.js-github-forum:
https://github.com/vercel/next.js/discussions/34858
How do I render before or after a child element in a container?
I am learning React by integrating it into my own website. I started with this:
function createErrorSection(name, title, description) {
const section = document.createElement('section');
const container = document.createElement('div');
const h2 = document.createElement('h2');
const p = document.createElement('p');
section.appendChild(container);
container.appendChild(h2);
container.appendChild(p);
section.id = name;
section.classList = 'section-error';
container.classList = 'section-error-container';
h2.textContent = title;
p.textContent = description;
return section;
}
Which I turned into this:
function createErrorSection(name, title, description) {
return (
<section id={name} className='section-error'>
<div className='section-error-container'>
<h2>{title}</h2>
<p>{description}</p>
</div>
</section>
);
}
This is eventually propagated down to either node.before(section) or node.after(section).
I checked inside ReactDOM, ReactDOM/server and React with no luck. I saw I could create an HTML string, but I need an HTMLElement and would rather not do my own rendering if it can be avoided (I want to learn the React way, I already know the vanilla way).
My end goal is to learn how and when to use React properly. I'd love to know the proper way, but insight, advice and workarounds are also greatly appreciated!
In React you rather want to create a custom component with a single argument which contains the corresponding properties:
// single argument contains all props
function ErrorSection({name, title, description}) {
return (
<section id={name} className='section-error'>
<div className='section-error-container'>
<h2>{title}</h2>
<p>{description}</p>
</div>
</section>
);
}
now you need to import ReactDOM and call render in order to show the component ErrorSecion with some specific property values inside a HTML node with the id #app. Make sure that your HTML document contains such a node.
import ReactDOM from "react-dom";
ReactDOM.render(
<ErrorSection name="..." title="..." description="..." />,
document.querySelector("#app")
);
Most of the react apps render some dynamically generated nested components into the DOM using a single empty HTML node inside the document body (e.g. div#app or div#root). So you most likely will only need to have a single ReactDOM.render call in your entire project.
First of all, component's name should be written in PascalCase.
In React, you should rethink the way you render elements.
There are different approaches for different purposes:
Pass components to the children prop
const Wrapper = ({ children }) => (
<div className="wrapper">
<h1>Wrapper heading</h1>
{children}
</div>
);
Now you can pass children to the wrapper this way:
const AnotherComponent = () => (
<Wrapper>
<div>Element that will be rendered where the children prop is placed</div>.
</Wrapper>
);
Pass components to custom props:
If you need to render many components in different spots, you can do this:
const MultiSpotComponent = ({ HeaderComponent, FooterComponent }) => (
<div>
{HeaderComponent}
<div>Some content</div>
{FooterComponent}
</div>
);
And then pass your components to the props the same way you do with attributes in HTML:
<MultiSpotComponent HeaderComponent={CustomHeader} FooterComponent={CustomFooter} />
Notice that I used self-closing tag for the component, because I don't render children inside it.
Render list
const AnotherComponent = () => {
const dynamicArray = ['some', 'dynamic', 'values'];
return (
<div>
{dynamicArray.map(value => <div key={value}>{value}</div>)}
</div>
);
};
I have described only 3 most-used approaches, but there are more ways to render elements. You can learn more at Official React Documentation
I am using some css animations from animate.css and I'm using react.js which works fine at the top of my page however, I also have some animations near the middle of the page. When my page loads everything animates at once which means once I scroll down the animations in the middle of the page have already completed. I am looking for away to delay the animations until that area of the screen is visible. I have found some questions/answers on here but they date back quite a few years and appear to be outdated.
As seen in the code below the animate__animated animate__bounce animate__zoomInDown classes are derived from animate.css but play immediately when the page is loaded and not when visible onscreen:
import React from "react";
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { faHourglassStart} from '#fortawesome/free-solid-svg-icons'
function MiddleContainer() {
return (
<div>
<div id = "middle-container" class="middle-container">
<h1>What can I offer you?</h1>
<div className = "fast animate__animated animate__bounce animate__zoomInDown">
<FontAwesomeIcon className="social-icon" icon={faHourglassStart} size = '4x' color = "black"/>
<h4>Fast and Reliable Service</h4>
<p>Your product will be delivered to you with precision, care and in a timely manner.</p>
<p>Add more info here when you are done with the css. </p>
</div>
</div>
</div>
)
}
export default MiddleContainer;
So I was able to solve this myself using a different library as I couldn't find any documentation from animate.css on how to animate on scroll
The new library with documentation that worked is AOS from https://michalsnik.github.io/aos/
I had to use useEffect from react.js in order for it to work.
Here is my code with animate on scroll working:
import React, { useEffect } from "react";
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { faHourglassStart} from '#fortawesome/free-solid-svg-icons'
import AOS from "aos";
import "aos/dist/aos.css";
function MiddleContainer() {
useEffect(() => {
AOS.init({
// duration : 5000
});
}, []);
return (
<div>
<div id = "middle-container" class="middle-container">
<h1>What can I offer you?</h1>
<div className = "fast" data-aos="zoom-in">
<FontAwesomeIcon className="social-icon" icon={faHourglassStart} size = '4x'
color = "black"/>
<h4>Fast and Reliable Service</h4>
<p>Your product will be delivered to you with precision, care and in a
timely manner.</p>
<p>Add more info here when you are done with the css. </p>
</div>
</div>
</div>
)
}
export default MiddleContainer;
I am new to react and am trying to toggle a body class using two different buttons. One is supposed to add a class using an onClick event and the other is supposed to remove the class. Below is an example of my code.
Right now in the console I can see the event fire twice but the class remains. As I stated I am new to React so I know I may be doing this incorrectly.
bodyFixed() {
document.body.classList.add('body-fixed');
}
bodyRelative() {
document.body.classList.remove('body-fixed');
}
You are trying to modify the dom directly like you would with vanilla js or JQuery, but this is not how react is meant to be used. React creates a virtual dom that you create and manage, and then react handle changing the page for you.
I recommend following a guide like this one to learn basic setup and concepts (skip to the part where he uses JSX).
I can further point you in the right direction if you show your whole component file.
You want to toggle a className prop value in the React way.
The React way is having a state prop and having a handler function that will toggle the state value, rather than manipulating the DOM node directly (the way you're doing it).
I would suggest you to take a look at React Main Concepts: Handling events and later once you feel a little bit more comfortable to read about Virtual DOM and Reconciliation in React.
Here's how can you do it:
const { classNames } = window
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
isToggled: true
}
this.toggleClass = this.toggleClass.bind(this)
}
toggleClass() {
const { isToggled } = this.state
this.setState({
isToggled: !isToggled
})
}
render() {
const { isToggled } = this.state
const className = classNames({
'body-fixed': isToggled
})
return <div className={className}>
<div>Current `className`: <b>{ className }</b></div>
<button onClick={this.toggleClass}>Toggle class</button>
</div>
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
);
<script src="https://unpkg.com/classnames#2.2.6/index.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container"></div>
I was able to use the code I listed earlier. I had my onClick events positioned incorrectly. Here is an example of the code I used:
bodyFixed() {
document.body.classList.add('body-fixed');
}
bodyRelative() {
document.body.classList.remove('body-fixed');
}
<Toggle>
{({on, getTogglerProps, setOn, setOff, toggle, showAlert}) =>
<div>
<button className="search-icon-top" {...getTogglerProps()}>{on ? <img className="times" onClick={this.bodyRelative} src={require('img/times.svg')} alt=" " /> : <i className="fa fa-search" onClick={this.bodyFixed}></i>}</button>
<div>
{on ? <TodaySearchBox /> : ''}
</div>
</div>}
</Toggle>
This is just a start for now. Thank you for the input.
EDIT: I am open to suggestions. Like I said I am new to React.
I want to use it for my website, but having trouble loading it. Nothing shows up.
I tried clearing my caches and cookies, and disabling all plugins, extensions, and add-ons, but it still does not work.
Here is the following code:
import React, { Component } from 'react'
import { Divider } from 'material-ui'
const styles = {
title:{
color: 'white',
textAlign: 'left',
marginLeft: 30
}
}
export default class TestingDisqus extends Component{
render(){
return(
<div>
<div style={styles.title}>
<font size="4">
Testing Disqus
</font>
</div>
<Divider style={{backgroundColor:'#282828'}}/>
<div id="disqus_thread"></div>
<script>
(function()
var d = document, s = d.createElement('script');
s.src = '//testingdisqus.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
</div>
)
}
}
Any insights would be appreciated! Thank you in advance.
In React it's best not to select and directly manipulate the DOM. React uses a virtual DOM and does the DOM manipulation for you. Also you have an IIFE in your JSX and in JSX you need to wrap all of your javascript in curly braces.
I recommend finding a React solution for this instead of trying to use vanilla JS in your JSX. Here is an open source react component that will likely solve your problem or get you started.
React-disqus-thread
import React from 'react'
import ReactDisqusThread from 'react-disqus-thread'
// in your class you can add this:
handleNewComment: function(comment) {
console.log(comment.text);
}
render: function () {
// and put a ReactDisqusThread in your JSX
return (
<ReactDisqusThread
shortname="example"
identifier="something-unique-12345"
title="Example Thread"
url="http://www.example.com/example-thread"
category_id="123456"
onNewComment={this.handleNewComment}/>
);
}
});