How to add react-hooks on the ready site? [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I know how to add only react and react-Dom , but if we will write some text on the react-hooks as the code:
const state = useState('name')
We will receive an error :
Uncaught ReferenceError: useState is not defined
ITS ISNT APP , Its just a ready site i know how to add hooks on the app , but dont know how on the ready site

you need to import useState from React as shown on https://reactjs.org/docs/hooks-state.html
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}```

Related

I want to create a Javascript Compiler in my React Blog [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 months ago.
Improve this question
I have just started my front end web developer career and I have recently created my own blog. The blog is created using react. Now, I wanted to add a functionality where users can write and execute javascript code in my blog.
For example, they should be able to run console.log and get the output. Now, I don't know how to add that functionality. For example, should I need to learn node and add server side development for that or should I add server less functions??? How can I add that functionality??.
Note: I'm well versed with HTML and CSS that's why I have started the blog.
PS: Will it be costly to implement that??? Is there a cheaper option?
You will want to use a code editor package from npm
I have found this one Monaco and looks like what you are asking for.
You can find a full tutorial here
A basic implementation would look like:
import React, { useState } from "react";
import Editor from "#monaco-editor/react";
const CodeEditorWindow = ({ onChange, language, code, theme }) => {
const [value, setValue] = useState(code || "");
const handleEditorChange = (value) => {
setValue(value);
onChange("code", value);
};
return (
<div className="overlay rounded-md overflow-hidden w-full h-full shadow-4xl">
<Editor
height="85vh"
width={`100%`}
language={language || "javascript"}
value={value}
theme={theme}
defaultValue="// some comment"
onChange={handleEditorChange}
/>
</div>
);
};
export default CodeEditorWindow;

State variable React Class component [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am new to react. And I'm having problem understanding why cannot we access a state variable from document.addEventListener in class component?
And if that is possible how it is possible?
I'm not sure what you mean. You can both access and set state in a callback from addEventListener:
class Example extends React.Component {
state = {
clickCount: 0,
}
componentDidMount() {
document.addEventListener('click', () => {
console.log('old clicks', this.state.clickCount);
this.setState(prev => ({
clickCount: prev.clickCount + 1,
}));
});
}
// ...
}

How to map over and return items in localStorage? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I currently have items in local storage, the console.log of data currently in local storage looks like this:
I want to simply map through these items and render the titles. I thought the below code would work, but nothing is being displayed, and I have no error messages. Do you know what I am doing wrong? Thank you.
import React, { useState, useEffect } from 'react';
import './../App.css';
import * as ReactBootStrap from 'react-bootstrap';
import {Link} from 'react-router-dom';
function Cart() {
const storageItems = JSON.parse(localStorage.getItem('product'));
console.log(storageItems)
return (
<div className="App">
{storageItems.map((item) => {
<p>item.title</p>
})}
</div>
);
}
export default Cart;
Try out :
{storageItems.map((item) => (<p>{item.title}</p>))}
because you missed to return the jsx

How can I call React hooks inside a condition? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have an object as a state with some properties. I want to update the state in a condition with a hook.
But it causes an infinite loop.
Can I update the state directly like this?
const [info, setInfo] = useState({name: '' })
if (info.name === '') {
info.name = 'empty'
}
Is this ok to do?
you should use useState as said in the following way:
const [info, setInfo] = useState({name: '' })
if (info.name === '') {
setInfo({...info, name = 'empty'});
}
this will set info with only the change of the name property
A hook is something that starts with use like useState. setState is not a hook - it's a setter/updater. It can be used inside of a conditional statement. If it's done properly there shouldn't be any infinite loops.
In React Functional Components, useState hook is used as an alternate to state in class components. The correct way to use the useState hook is
const [ variable, setVariable ] = React.useState( //default value );
The default value can be null, " string ", { object } , true / false, or 0, 1, 2 .......
And just like this.setState() in class components, you set the state with the
setVariable( newValue );
Never ever try to change the state variables like you change the normal variables. They are immutable for one render and hence cause re-render when called setState.
And for the infinite loop, please copy paste your component

How does this useState hook work in React? [duplicate]

This question already has an answer here:
Why does useState cause the component to render twice on each update?
(1 answer)
Closed 2 years ago.
const App = () => {
const [ counter, setCounter ] = useState(0)
console.log(counter)
return (
<>
<div>You clicked {counter} times.</div>
<button onClick={ () => setCounter(counter+1) }>Click me!</button>
</>
)
}
Here's my react component. My question is when I run this, I see 0 two times in the console. Then when I click on the button, I see 1 two times in the console. Can anyone explain why does that happen? I was expecting 0, 1, 2 to be printed only once in the console whenever I click on the button.
Please forgive if this question has already been answered or my title of the question is not related with what I'm asking as this is my first question here.
It is because of React.StrictMode
If you go to your index.js , you will find that your App component is wrapped with <React.StrictMode>. If you strip off the StrictMode you will notice that your App component will render only once.
Refer the below doc to understand StrictMode
Strict mode can’t automatically detect side effects for you, but it
can help you spot them by making them a little more deterministic.
This is done by intentionally double-invoking the following functions:
Class component constructor, render, and shouldComponentUpdate methods
Class component static getDerivedStateFromProps method Function
component bodies State updater functions (the first argument to
setState) Functions passed to useState, useMemo, or useReducer
Please refer: https://reactjs.org/docs/strict-mode.html
return (<React.StrictMode><App /><React.StrictMode>)
This would solve your problem.

Categories