26,523 questions
907
votes
21
answers
925k
views
The useState set method is not reflecting a change immediately
I am trying to learn hooks and the useState method has made me confused. I am assigning an initial value to a state in the form of an array. The set method in useState is not working for me, both with ...
27
votes
7
answers
38k
views
How to create a protected route with react-router-dom?
How to create a protected route with react-router-dom and storing the response in localStorage, so that when a user tries to open next time they can view their details again. After login, they should ...
172
votes
6
answers
121k
views
Why useEffect running twice and how to handle it well in React?
I have a counter and a console.log() in an useEffect to log every change in my state, but the useEffect is getting called two times on mount. I am using React 18. Here is a CodeSandbox of my project ...
432
votes
10
answers
266k
views
Why does calling react setState method not mutate the state immediately?
I'm reading Forms section of reactjs documentation and just tried this code to demonstrate onChange usage (JSBIN).
var React= require('react');
var ControlledForm= React.createClass({
...
1095
votes
32
answers
1.4m
views
Understanding unique keys for array children in React.js
I'm building a React component that accepts a JSON data source and creates a sortable table.
Each of the dynamic data rows has a unique key assigned to it but I'm still getting an error of:
Each ...
1306
votes
63
answers
916k
views
React-router URLs don't work when refreshing or writing manually
I'm using React-router and it works fine while I'm clicking on link buttons, but when I refresh my webpage it does not load what I want.
For instance, I am in localhost/joblist and everything is fine ...
2375
votes
51
answers
1.8m
views
How can I programmatically navigate using React Router?
With React Router, I can use the Link element to create links which are natively handled by React Router.
I see internally it calls this.context.transitionTo(...).
I want to do navigation. Not from a ...
14
votes
5
answers
22k
views
How to pass data from a page to another page using react router
Please I need help on react-router-dom, I am new to the library and can seem to find any solution since. I am getting three results from an api call, in which I map over the data to render it on UI, ...
147
votes
7
answers
87k
views
Why can't I directly modify a component's state, really?
I understand that React tutorials and documentation warn in no uncertain terms that state should not be directly mutated and that everything should go through setState.
I would like to understand why, ...
176
votes
15
answers
217k
views
setState doesn't update the state immediately [duplicate]
I would like to ask why my state is not changing when I do an onClick event. I've search a while ago that I need to bind the onClick function in constructor but still the state is not updating.
Here's ...
218
votes
11
answers
492k
views
React setState not updating state
So I have this:
let total = newDealersDeckTotal.reduce(function(a, b) {
return a + b;
},
0);
console.log(total, 'tittal'); //outputs correct total
setTimeout(() => {
this.setState({ ...
642
votes
36
answers
503k
views
How to update nested state properties in React
I'm trying to organize my state by using nested property like this:
this.state = {
someProperty: {
flag:true
}
}
But updating state like this,
this.setState({ someProperty.flag: false });...
626
votes
19
answers
942k
views
Correct modification of state arrays in React.js
I want to add an element to the end of a state array, is this the correct way to do it?
this.state.arrayvar.push(newelement);
this.setState({ arrayvar:this.state.arrayvar });
I'm concerned that ...
193
votes
9
answers
199k
views
Why is setState in reactjs Async instead of Sync?
I have just found that in react this.setState() function in any component is asynchronous or is called after the completion of the function that it was called in.
Now I searched and found this blog (...
886
votes
24
answers
1.2m
views
How to fix missing dependency warning when using useEffect React Hook
With React 16.8.6 (it was good on previous version 16.8.3), I get this error when I attempt to prevent an infinite loop on a fetch request:
./src/components/BusinessesList.js
Line 51: React Hook ...
2099
votes
88
answers
2.2m
views
Loop inside React JSX
I'm trying to do something like the following in React JSX (where ObjectRow is a separate component):
<tbody>
for (var i=0; i < numrows; i++) {
<ObjectRow/>
}
</...
547
votes
13
answers
1.3m
views
Trying to use fetch and pass in mode: no-cors
I can hit this endpoint, http://catfacts-api.appspot.com/api/facts?number=99 via Postman and it returns JSON
Additionally I am using create-react-app and would like to avoid setting up any server ...
16
votes
3
answers
11k
views
Link tag inside BrowserRouter changes only the URL, but doesn't render the component
I am building a Netflix clone application, and I am using react-router-dom v5 to switch between different pages. However, when I click the Link tag in Navbar.jsx, the URL changes, but the ...
244
votes
19
answers
90k
views
Unable to access React instance (this) inside event handler [duplicate]
I am writing a simple component in ES6 (with BabelJS), and functions this.setState is not working.
Typical errors include something like
Cannot read property 'setState' of undefined
or
this....
748
votes
7
answers
188k
views
What do multiple arrow functions mean in JavaScript?
I have been reading a bunch of React code and I see stuff like this that I don't understand:
handleChange = field => e => {
e.preventDefault();
/// Do something here
}
976
votes
24
answers
891k
views
Call child method from parent
I have two components:
Parent component
Child component
I was trying to call Child's method from Parent, I tried this way but couldn't get a result:
class Parent extends Component {
render() {
...
443
votes
21
answers
762k
views
How to pass data from child component to its parent in ReactJS?
I'm trying to send data from a child component to its parent as follow:
const ParentComponent = React.createClass({
getInitialState() {
return {
language: '',
};
},
...
283
votes
7
answers
210k
views
My component is rendering twice because of Strict Mode
My React Component is rendering twice. So, I decided to do a line-by-line debug, and the problem is here:
if ( workInProgress.mode & StrictMode) {
instance.render();
}
React-dom....
25
votes
4
answers
67k
views
Cannot build frontend using Vite, TailwindCSS with PostCSS
10:04:32 PM [vite] Internal server error: [postcss] It looks like you're trying to use tailwindcss directly as a PostCSS plugin. The PostCSS plugin has moved to a separate package, so to continue ...
23
votes
2
answers
22k
views
How do I render components with different layouts/elements using react-router-dom v6
I am having trouble writing code to render a login page with no navbar and sidebar. I have come across some pages that ask similar questions but none seem to pertain to my current situation.
How to ...
1465
votes
33
answers
1.0m
views
How to pass props to {this.props.children}
I'm trying to find the proper way to define some components which could be used in a generic way:
<Parent>
<Child value="1">
<Child value="2">
</Parent>
There is a logic ...
2567
votes
72
answers
3.5m
views
Error message "error:0308010C:digital envelope routines::unsupported"
I created the default IntelliJ IDEA React project and got this:
Error: error:0308010C:digital envelope routines::unsupported
at new Hash (node:internal/crypto/hash:67:19)
at Object.createHash (...
593
votes
20
answers
916k
views
React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing
I was trying the useEffect example something like below:
useEffect(async () => {
try {
const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
const json = ...
47
votes
3
answers
14k
views
Why calling setState method doesn't mutate the state immediately?
Ok, i'll try and make this quick because it SHOULD be an easy fix...
I've read a bunch of similar questions, and the answer seems to be quite obvious. Nothing I would ever have to look up in the ...
559
votes
26
answers
1.0m
views
Adding script tag to React/JSX
I have a relatively straightforward issue of trying to add inline scripting to a React component. What I have so far:
'use strict';
import '../../styles/pages/people.scss';
import React, { Component ...
308
votes
7
answers
556k
views
When to use React setState callback
When a react component state changes, the render method is called. Hence for any state change, an action can be performed in the render methods body. Is there a particular use case for the setState ...
184
votes
6
answers
97k
views
ReactJS component names must begin with capital letters?
I am playing around with the ReactJS framework on JSBin.
I have noticed that if my component name starts with a lowercase letter it does not work.
For instance the following does not render:
var ...
1499
votes
21
answers
661k
views
What are these three dots in React doing?
What does the ... do in this React (using JSX) code and what is it called?
<Modal {...this.props} title='Modal heading' animation={false}>
471
votes
22
answers
1.2m
views
axios post request to send form data
axios POST request is hitting the url on the controller but setting null values to my POJO class, when I go through developer tools in chrome, the payload contains data. What am I doing wrong?
Axios ...
330
votes
30
answers
659k
views
Window is not defined in Next.js React app
In my Next.js app I can't seem to access window:
Unhandled Rejection (ReferenceError): window is not defined
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
55
votes
9
answers
31k
views
Programmatically Navigate using react-router
I am developing an application in which I check if the user is not loggedIn. I have to display the login form, else dispatch an action that would change the route and load other component. Here is my ...
0
votes
1
answer
3k
views
Unexpected token CloseSquareBracket error with TailwindCSS v4 and Parcel
I followed all the steps mentioned in the Tailwind v4 docs, to setup TailwindCSS v4 with parcel . After setup when i am running local server then i got this error.
Server running at http://localhost:...
700
votes
49
answers
527k
views
How can I perform a debounce?
How do you perform debounce in React?
I want to debounce the handleOnChange function.
I tried with debounce(this.handleOnChange, 200), but it doesn't work.
function debounce(fn, delay) {
var timer = ...
807
votes
26
answers
592k
views
useEffect() is called twice even if an empty array is used as an argument
I am writing code so that before the data is loaded from DB, it will show loading message, and then after it is loaded, render components with the loaded data. To do this, I am using both useState ...
495
votes
24
answers
1.0m
views
How to push to History in React Router v4?
In the current version of React Router (v3) I can accept a server response and use browserHistory.push to go to the appropriate response page. However, this isn't available in v4, and I'm not sure ...
435
votes
33
answers
773k
views
Can't perform a React state update on an unmounted component
Problem
I am writing an application in React and was unable to avoid a super common pitfall, which is calling setState(...) after componentWillUnmount(...).
I looked very carefully at my code and ...
285
votes
16
answers
163k
views
State not updating when using React state hook within setInterval
I'm trying out the new React Hooks and have a Clock component with a time value which is supposed to increase every second. However, the value does not increase beyond one.
function Clock() {
...
366
votes
40
answers
1.8m
views
"SyntaxError: Unexpected token < in JSON at position 0"
In a React app component which handles Facebook-like content feeds, I am running into an error:
Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0
I ran ...
224
votes
12
answers
177k
views
React: "this" is undefined inside a component function
class PlayerControls extends React.Component {
constructor(props) {
super(props)
this.state = {
loopActive: false,
shuffleActive: false,
}
}
render() {
var ...
600
votes
26
answers
665k
views
How can I update the parent's state in React?
My structure looks as follows:
Component 1
- |- Component 2
- - |- Component 4
- - - |- Component 5
Component 3
Component 3 should display some data depending on state of Component 5.
Since ...
200
votes
14
answers
227k
views
Why is my React component is rendering twice?
I don't know why my React component is rendering twice. So I am pulling a phone number from params and saving it to state so I can search through Firestore. Everything seems to be working fine except ...
123
votes
9
answers
49k
views
Arrow function without curly braces
I'm new to both ES6 and React and I keep seeing arrow functions. Why is it that some arrow functions use curly braces after the fat arrow and some use parentheses?
For example:
const foo = (params) =&...
937
votes
57
answers
1.0m
views
Detect click outside React component
I'm looking for a way to detect if a click event happened outside of a component, as described in this article. jQuery closest() is used to see if the target from a click event has the dom element as ...
357
votes
8
answers
958k
views
How to access a DOM element in React? What is the equilvalent of document.getElementById() in React
How do I select certain bars in react.js?
This is my code:
var Progressbar = React.createClass({
getInitialState: function () {
return { completed: this.props.completed };
},
...
114
votes
4
answers
216k
views
Whats the best way to update an object in an array in ReactJS?
If you have an array as part of your state, and that array contains objects, whats an easy way to update the state with a change to one of those objects?
Example, modified from the tutorial on react:
...