Update onClick ReactJs - javascript

Im making a click speed test, but the counter doesn't update even tho the value does change, i think it is a problem with the useState hook but im not sure.
Here's the code
import React, { useState } from 'react';
import './app.css';
let contador = 0;
function hasClicked() {
contador++;
console.log(contador);
}
function App() {
return (
<div className="App">
<body>
<h1>Click Speed Test</h1>
<h2>{contador}</h2>
<button onClick={hasClicked}>Click on Me</button>
</body>
</div>
);
}
export default App;
I need the H2 that displays the number to update every click.

React is reactive, in that once you change its state, it will re-render the component and reflect changes in your state. Keep in mind, React does not know when you alter any variable. React will only know if you update a state value, which you must manually create. You're in the right direction by importing useState. Also, keep in mind that your state must only be inside a component, not in a global scope. Here's what your code should look something like:
import React, { useState } from 'react';
import './app.css';
function App() {
const [contador, setContador] = useState(0); // declare our state
function hasClicked() {
setContador(contador + 1); // update state
// calling this function also tells React to re-render the component
}
return (
<div className="App">
<body>
<h1>Click Speed Test</h1>
{/* each time the component renders it displays
the value of 'contador', which is altered on each click */}
<h2>{contador}</h2>
<button onClick={hasClicked}>Click on Me</button>
</body>
</div>
);
}
export default App;

Related

Why is my JS function only applying CSS to a single instance of my React component?

I have a component named "ProjectCard" and a component named "Work". In the component Work, I have created a function get_width() that gets the width of the screen and I am running that function in the useEffect Hook. I am also using useState hook that gets set inside the useEffect Hook and I am passing the state as a prop the ProjectCard Component that I am calling inside the Work Components , I have 6 of them. In the ProjectCard components, I have a function changeStyle(dType) that gets the prop and checks if it is 'Mobile'. If the condition becomes true, It gets the html element by ID and apply the CSS to it.
Now, the problem is that I have 6 ProjectCard Components inside my Work Component , but the CSS is being applied to only one of them. Can someone kindly explain this?
Work.js
import React , {useState , useEffect} from 'react';
import Navbar from './Navbar';
import ProjectCard from './ProjectCard';
import './Work.css';
function get_width()
{
var width = window.screen.availWidth;
console.log(width);
return width;
}
function Work()
{
const [device , setDevice] = useState('Desktop');
useEffect(()=>{
if(get_width() <= 450)
{
setDevice('Mobile');
}
} , [setDevice])
return(
<>
<Navbar/>
<div id="workMain">
<h1>Our Work</h1>
<div id="workButtons">
<button>All</button>
<button>Website</button>
<button>Mobile App</button>
</div>
<div id="cards">
<ProjectCard Device = {device}/>
<ProjectCard Device = {device}/>
<ProjectCard Device = {device}/>
<ProjectCard Device = {device}/>
<ProjectCard Device = {device}/>
<ProjectCard Device = {device}/>
</div>
</div>
</>
);
}
export default Work;
ProjectCard.js
import React , {useEffect} from 'react';
import './ProjectCard.css';
function changeStyle(dType)
{
if(dType === 'Mobile')
{
var card = document.getElementById("card");
card.style.marginLeft = 0;
}
console.log(dType);
}
function ProjectCard(props)
{
useEffect(()=>{
changeStyle(props.Device);
})
return(
<>
<div id="card">
<p>Website</p>
<p>RA Traders</p>
</div>
</>
);
}
export default ProjectCard;
This statement is causing the undesired behaviour:
var card = document.getElementById("card");
With getElementById Javascript looks for an element with id "card", inside your document. This is not confined to the react component, mind you. The whole DOM is searched and the first matching instance is returned. The first matching element will be the same no matter which component the function is called from). Note, ideally id should be unique in the document.
You can use refs here (React's recommended way for DOM manipulation). With hooks you have to use useRef
function changeStyle(dType, divElement)
{
if(dType === 'Mobile')
{
divElement.current.style.marginLeft = 0;
}
console.log(dType);
}
function ProjectCard(props)
{
const divRef = useRef();
useEffect(()=>{
changeStyle(props.Device,divRef);
})
return(
<>
<div ref={divRef}>
<p>Website</p>
<p>RA Traders</p>
</div>
</>
);
}
export default ProjectCard;
divRef.current will hold the value of the DOM node and you can make changes accordingly

Gitpod automatically adds semicolon when saving a component (React)

When I try to save my component in React the following happens:
import React from "react";
const Product = () => {
return;
<div>
<h1>hello i'm testing</h1>
</div>;
};
export default Product;
Everytime I save my component it automatically adds a semicolon at the end of each line, even if I don't need them. Expected result would be:
import React from "react";
const Product = () => {
return
<div>
<h1>hello i'm testing</h1>
</div>
}
export default Product
This is the first time that happens to me and I don't have a clue. I'm a noob here.

should I use state in addling a new component on click React?

I am new to react and trying to refactor some es6 js code in to react I have a component that I need to create once I click on an icon similar to insert adjacent html is vanilla js any idea how can I achieve this.
import React, {useState} from 'react'
import Item from './Item';
import { icon, library } from '#fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { faPlusCircle} from '#fortawesome/free-solid-svg-icons';
library.add(faPlusCircle)
function row(props) {
const [item] = useState(<Item />)
return (
<ul className="global">
item
<FontAwesomeIcon onClick={()=>{return <ChangeableItem/>}} con={["fas", "plus-circle"]}/>
<ul/>
)
}
This doesn't do anything:
onClick={()=>{return <ChangeableItem/>}}
The click handler isn't expecting a returned React node and won't do anything with it.
should I use state
Yes. Track in state whether or not this component is displayed. For example:
const [showChangeableItem, setShowChangeableItem] = useState(false);
The state now says not to show the "changeable item". Within the rendering, conditionally render that element based on state. For example:
{ showChangeableItem ? <ChangeableItem/> : null }
Then in your click handler you'd just update the state:
<FontAwesomeIcon onClick={() => setShowChangeableItem(true)} con={["fas", "plus-circle"]}/>
Basically, don't think of it as trying to add elements. All of the elements you need should already be specified in the render, some can just be wrapped in conditional logic. State drives the rendering. Events update state.
You would use a state variable for that.
import React, {useState} from 'react'
import Item from './Item';
import { icon, library } from '#fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { faPlusCircle} from '#fortawesome/free-solid-svg-icons';
library.add(faPlusCircle)
function row(props) {
const [showItem, set_showItem] = useState
return (
<> // use react fragment here, otherwise you will get an error if you try to return several React Elements
<ul className="global">
{showItem? <Item> : null} // return the Item if you want to show it, otherwise return null
<FontAwesomeIcon
onClick={()=> set_showItem(true)}
con={["fas", "plus-circle"]}
/>
<ul/>
</> //ent of React fragment
)
}

React Hook "useState" is called in function "increaseCounter" that is neither a React function component nor a custom React Hook function

This is my Count component, I am new to react, using hooks I create a function inside a function, but it gives this error
import React, { useState } from "react";
const style = {
color: "#1B9CFC",
};
function Counter(props) {
const [count, setCount] = useState(0);
function increaseCounter() {
useState(setCount());
}
return (
<div>
<h1 className="ms-5" style={style}>
{count}
</h1>
<div className="m-2 p-4">
<button className="btn btn-success m-2" onClick={increaseCounter}>
+
</button>
<button className="btn btn-danger">-</button>
</div>
</div>
);
}
export default Counter;
This is the full error message
src\component\Counter.jsx
Line 11:5: React Hook "useState" is called in function "increaseCounter" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter react-hooks/rules-of-hooks
Search for the keywords to learn more about each error.
useState(setCount()); is not the way to change state.To change state, call the setCount() and set a value inside it.
Here is your code :
function increaseCounter() {
setCount(count => count + 1);
}
You should write in this way:
function increaseCounter() {
setCount(count+1)
}
In the react, setState event is async. useState allows you to initialize react hook with state. So you cannot use useState to update the state.
There are two points we need to check if we are getting this error.
The function name "Counter" .It must start from the capital latter.
function increaseCounter() {
setCount(count+1)
} useSatate will increase the count value as per clicking the button.

React context between unrelated components

For learning purposes I'm just trying to render this dumb example where Component A has a variable that creates a random number and another (unrelated) Component B can render it with useContext. I don't know how to make the provider of the context to know that the value is the variable from Component A.
I created another file to do the React.createContext()... but still don't know how to make the random number to reach there or the App Component to do the Provider. I know I could create the random number in App component and provide whatever component I want with that value, but I just want the value to be generated in Component A and reach Component B. Any ideas? Maybe its so simple I can't see it.
What I have at the moment:
Component A:
import React from'react';
export default function RandomNumGenerator() {
const randomNum = Math.random();
return(
<h2>Your random number is:</h2>
)
}
Component B:
import React from'react';
export default function RandomNumRenderizator() {
return(
<h2></h2> //Want to render the random num here
)
}
App Component:
import React from 'react';
import RandomNumGenerator from "./FunctionalComponents/RandomNumGenerator/RandomNumGenerator";
import RandomNumRenderizator from "./FunctionalComponents/RandomNumRenderizator/RandomNumRenderizator";
import RandomNumContext from "./contexts/RandomNumContext";
export default function App() {
return (
<div>
<RandomNumGenerator/>
<RandomNumContext.Provider value={}> //Empty value as I don't know what to send
<RandomNumRenderizator/>
</RandomNumContext.Provider>
</div>
);
}
And the Context:
import React from "react";
const RandomNumContext = React.createContext(); //Don't know if there should be anything as defaultValue
export default RandomNumContext;
As data flows down in React, the value you wish to pass have to be in scope with the context provider, then you just need to read the context value using a hook:
export default function App() {
const randomNum = Math.random();
return (
<>
<RandomNumDisplay num={randomNum} />
<RandomNumContext.Provider value={randomNum}>
<RandomNumRenderizator />
</RandomNumContext.Provider>
</>
);
}
export default function RandomNumRenderizator() {
const randomNum = useContext(RandomNumContext);
return <h2>{randomNum}</h2>;
}

Categories

Resources