Questions tagged [reactjs]

React is a JavaScript library for building user interfaces. It uses a declarative, component-based paradigm and aims to be efficient and flexible.

Example using a class component

class HelloWorldWidget extends React.Component {
  render() {
      return (
          <div>
              Hello World!
          </div>
      );
  }
};

ReactDOM.render(
  <HelloWorldWidget />,
  document.body
);

Example using function component

function HelloWorldWidget() {
  return <div>Hello World!</div>;
}

ReactDOM.render(
  <HelloWorldWidget />,
  document.body
);

Getting started

npx create-react-app my_app

Advantages

  • React creates a virtual DOM so that all the components can be re-rendered individually without the need for the whole page to be repainted by the browser

  • A user can update a particular content of the page just by re-rendering only that component

  • In React, data flows from the owner to the child. You can think of it as "one-way data binding."

  • React's view logic means it can quickly render on the server, in the browser or native components

  • React can be used in conjunction with frameworks like and

  • Separating the declarative view () and logically making projects easier to read and maintain


Resources:


Books:


Related tags:


Official Logo:

React logo


Versions:

Note: The table below only summarises changes for each version. A comprehensive list of changes for each version can be found here.

Version Release Date Changes
18.2.0 14 June 2022 React DOM:
Provide a component stack as a second argument to onRecoverableError.
Fix hydrating into document causing a blank page on mismatch.
Fix false positive hydration errors with Suspense.
Fix ignored setState in Safari when adding an iframe.
React DOM Server:
Pass information about server errors to the client.
Allow to provide a reason when aborting the HTML stream.
Disallow complex children inside <title> elements to match the browser constraints.
Fix buffering in some worker environments by explicitly setting highWaterMark to 0.
Server Components (Experimental):
Add support for useId() inside Server Components.
18.1.0 26 April 2022 Fix the false positive warning about react-dom/client when using UMD bundle.
Fix suppressHydrationWarning to work in production too.
Fix componentWillUnmount firing twice inside of Suspense.
Fix some transition updates being ignored.
Fix useDeferredValue causing an infinite loop when passed an unmemoized value.
Fix throttling of revealing Suspense fallbacks.
Fix an inconsistency in whether the props object is the same between renders.
Fix a missing warning about a setState loop in useEffect.
Fix a spurious hydration error.
Warn when calling setState in useInsertionEffect.
Ensure the reason for hydration errors is always displayed.
18.0.0 29 March 2022 Transitions
Automatic Batching
Concurrent rendering
New Suspense Features
New Client and Server Rendering APIs
New Strict Mode Behaviors
17.0.2 22 March 2021 Remove unused dependency to address the SharedArrayBuffer cross-origin isolation warning.
17.0.1 22 October 2020 React DOM - Fix a crash in IE11.
17.0.0 20 October 2020 React - Add react/jsx-runtime and react/jsx-dev-runtime for the new JSX transform.Build component stacks from native error frames. Allow specifying displayName on context for improved stacks. Prevent "use strict" from leaking in the UMD bundles. Stop using fb.me for redirects.... React DOM - Delegate events to roots instead of document. Clean up all effects before running any next effects. Run useEffect cleanup functions asynchronously.
16.14.1 14 October 2020 Add support for the new JSX transform.
16.13.1 19 March 2020 Fix bug in legacy mode Suspense where effect clean-up functions are not fired. Revert warning for cross-component updates that happen inside class render lifecycles.
16.13.0 26 February 2020 Features added in React Concurrent mode. Fix regressions in React core library and React Dom.
16.12.0 14 November 2019 React DOM - Fix passive effects (useEffect) not being fired in a multi-root app. React Is - Fix lazy and memo types considered elements instead of components
16.11.0 22 October 2019 Fix mouseenter handlers from firing twice inside nested React containers. Remove unstable_createRoot and unstable_createSyncRoot experimental APIs. (These are available in the Experimental channel as createRoot and createSyncRoot.)
16.10.2 3 October 2019 Fix regression in react-native-web by restoring the order of arguments in event plugin extractors
16.10.1 28 September 2019 Fix regression in Next.js apps by allowing Suspense mismatch during hydration to silently proceed.
16.10.0 27 September 2019 Fix edge case where a hook update wasn't being memoized. Fix the heuristic for determining when to hydrate so we don't incorrectly hydrate during an update. Clear additional fibre fields during unmount to save memory. Fix bug with required text fields in Firefox. I prefer Object.is instead of inline polyfill when available. Fix bugs when mixing Suspense and error handling.
16.9.0 9 August 2019 Add <React.Profiler> API for gathering performance measurements programmatically. Remove unstable_ConcurrentMode in favor of unstable_createRoot.
16.8.6 27 March 2019 Fix an incorrect bailout in useReducer(), Fix iframe warnings in Safari DevTools, Warn if contextType is set to Context.Consumer instead of Context, Warn if contextType is set to invalid values.
16.8.0 06 February 2019 Add Hooks, Add ReactTestRenderer.act() and ReactTestUtils.act() for batching updates, Support synchronous thenables passed to React.lazy(), Improve useReducer Hook lazy initialization API.
16.7.0 20 December 2018 Fix performance of React.lazy for lazily-loaded components, Clear fields on unmount to avoid memory leaks, Fix bug with SSR, and Fix a performance regression.
16.6.0 23 October 2018 Add support for contextType, Support priority levels, continuations, and wrapped callbacks, Improve the fallback mechanism, Fix grey overlay on iOS Safari, and Add React.lazy() for code splitting components.
16.5.0 05 September 2018 Add support for React DevTools Profiler, Handle errors in more edge cases gracefully, Add react-dom/profiling, Add onAuxClick event for browsers, Add movementX and movementY fields to mouse events, Add tangentialPressure and twist fields to pointer event.
16.4.0 24 May 2018 Add support for Pointer Events specification, Add the ability to specify propTypes, Fix reading context, Fix the getDerivedStateFromProps() support, Fix a testInstance.parent crash, Add React.unstable_Profiler component for measuring performance, Change internal event names.
16.3.2 16 April 2018 Fix an IE crash, Fix labels in User Timing measurements, Add a UMD build, and Improve the performance of unstable_observedBits API with nesting.
16.3.1 03 April 2018 Prefix private API, Fix performance regression and error handling bugs in development mode, Add peer dependency, and Fix a false positive warning in IE11 when using Fragment.
16.3.0 29 March 2018 Add a new officially supported context API, Add new packagePrevent an infinite loop when attempting to render portals with SSR, Fix an issue with this.state, and Fix an IE/Edge issue.
16.1.0 9 November 2017 Discontinuing Bower Releases, Fix an accidental extra global variable in the UMD builds, Fix onMouseEnter and onMouseLeave firing, Fix <textarea> placeholder, Remove unused code, Add a missing package.json dependency, Add support for React DevTools.
16.0.0 26 September 2017 Improved error handling with introduction of "error boundaries", React DOM allows passing non-standard attributes, Minor changes to setState behavior, remove react-with-addons.js build, Add React.createClass as create-react-class, React.PropTypes as prop-types, React.DOM as react-dom-factories, changes to the behavior of scheduling and lifecycle methods.
15.6.0 13 June 2017 Add support for CSS variables in style attribute and Grid style properties, Fix AMD support for add-ons depending on react, Remove unnecessary dependency, Add a deprecation warning for React.createClass and React.DOM factory helpers.
15.5.4 11 April 2017 Fix compatibility with Enzyme by exposing batchedUpdates on shallow renderer, Update version of prop-types, Fix react-addons-create-fragment package to include loose-envify transform.
15.5.0 07 April 2017 Added react-dom/test-utils, Removed peerDependencies, Fixed issue with Closure Compiler, Added a deprecation warning for React.createClass and React.PropTypes, Fixed Chrome bug.
15.4.2 06 January 2017 Fixed build issues, Added missing package dependencies, and Improved error messages.
15.4.1 23 November 2016 Restructure variable assignment, Fixed event handling, Fixed compatibility of browser build with AMD environments.
15.4.0 16 November 2016 React package and browser build no longer includes React DOM, Improved development performance, Fixed occasional test failures, update batchedUpdates API, React Perf, and ReactTestRenderer.create().
15.3.1 19 August 2016 Improve performance of development builds, Cleanup internal hooks, Upgrade fbjs, Improve the startup time of React, Fix memory leak in server rendering, fix React Test Renderer, Change trackedTouchCount invariant into a console.error.
15.3.0 30 July 2016 Add React.PureComponent, Fix issue with nested server rendering, Add xmlns, xmlnsXlink to support SVG attributes and referrerPolicy to HTML attributes, updates React Perf Add-on, Fixed issue with ref.
15.2.0 01 July 2016 Include component stack information, Stop validating props at mount time, Add React.PropTypes.symbol, Add onLoad handling to <link> and onError handling to <source> element, Add isRunning() API, Fix performance regression.
15.1.0 20 May 2016 Fix a batching bug, Ensure use of the latest object-assign, Fix regression, Remove use of merge utility, and Renamed some modules.
15.0.0 07 April 2016 Initial render now uses document.createElement instead of generating HTML, No more extra <span>s, Improved SVG support, ReactPerf.getLastMeasurements() is opaque, New deprecations introduced with a warning, Fixed multiple small memory leaks, React DOM now supports the cite and profile HTML attributes and cssFloat, gridRow and gridColumn CSS properties.
0.14.1 29 October 2015 Added support for srcLang, default, kind attributes, and color attribute, Ensured legacy .props access on DOM nodes, Fixed scryRenderedDOMComponentsWithClass, Added react-dom.js.
0.13.0 10 March 2015 Deprecated patterns that warned in 0.12 no longer work, ref resolution order has changed, Removed properties this._pendingState and this._rootNodeID, Support ES6 classes, Added API React.findDOMNode(component), Support for iterators and immutable-js sequences, Added new features React.addons.createFragment, deprecated React.addons.classSet.
0.12.0 21 November 2014 Added new features Spread operator ({...}) introduced to deprecate this.transferPropsTo, Added support for acceptCharset, classID, manifest HTML attributes, React.addons.batchedUpdates added to API, @jsx React.DOM no longer required, Fixed issues with CSS Transitions.
0.11.0 17 July 2014 Improved SVG support, Normalized e.view event, Update $apply command, Added support for namespaces, Added new transformWithDetails API, includes pre-built packages under dist/, MyComponent() now returns a descriptor, not an instance.
0.10.0 21 March 2014 Added support for srcSet and textAnchor attributes, add update function for immutable data, Ensure all void elements don't insert a closing tag.
0.9.0 20 February 2014 Added support for crossOrigin, download and hrefLang, mediaGroup and muted, sandbox, seamless, and srcDoc, scope attributes, Added any, arrayOf, component, oneOfType, renderable, shape to React.PropTypes, Added support for onMouseOver and onMouseOut event, Added support for onLoad and onError on <img> elements.
0.8.0 20 December 2013 Added support for rows & cols, defer & async, loop for <audio> & <video>, autoCorrect attributes. Added onContextMenu events, Upgraded jstransform and esprima-fb tools, Upgraded browserify.
0.5.0 20 October 2013 Improve Memory usage, Support for Selection and Composition events, Support for getInitialState and getDefaultProps in mixins, Added React.version and React.isValidClass, Improved compatibility for Windows.
0.4.0 20 July 2013 Support for comment nodes <div>{/* */}</div>, Improved server-side rendering APIs, Removed React.autoBind, Support for the key prop, Improvements to forms, Fixed bugs.
0.3.0 29 May 2013 Initial Public Release

465710 questions
690
votes
26 answers

What is the type of the 'children' prop?

I have a very simple functional component as follows: import * as React from 'react'; export interface AuxProps { children: React.ReactNode } const aux = (props: AuxProps) => props.children; export default aux; And another…
Asool
  • 13,031
  • 7
  • 35
  • 49
685
votes
38 answers

Hide keyboard in react-native

If I tap onto a textinput, I want to be able to tap somewhere else in order to dismiss the keyboard again (not the return key though). I haven't found the slightest piece of information concerning this in all the tutorials and blog posts that I…
TurboFish
  • 7,789
  • 4
  • 18
  • 27
684
votes
49 answers

How to perform debounce?

How do you perform debounce in React.js? I want to debounce the handleOnChange. I tried with debounce(this.handleOnChange, 200) but it doesn't work. function debounce(fn, delay) { var timer = null; return function() { var context = this, …
Chetan Ankola
  • 6,915
  • 3
  • 14
  • 6
654
votes
40 answers

How to add multiple classes to a ReactJS Component?

I am new to ReactJS and JSX and I am having a little problem with the code below. I am trying to add multiple classes to the className attribute on each li:
  • My React component…
    Hector
    • 6,625
    • 3
    • 16
    • 18
    654
    votes
    10 answers

    What's the difference between "super()" and "super(props)" in React when using es6 classes?

    When is it important to pass props to super(), and why? class MyComponent extends React.Component { constructor(props) { super(); // or super(props) ? } }
    Misha Moroshko
    • 166,356
    • 226
    • 505
    • 746
    652
    votes
    10 answers

    ReactJS - Does render get called any time "setState" is called?

    Does React re-render all components and sub components every time setState() is called? If so, why? I thought the idea was that React only rendered as little as needed - when state changed. In the following simple example, both classes render again…
    Brad Parks
    • 66,836
    • 64
    • 257
    • 336
    649
    votes
    23 answers

    Error: 'node-sass' version 5.0.0 is incompatible with ^4.0.0

    I've created a blank React project, using the command: npx create-react-app on npm v7.0.7 and Node.js v15.0.1 Installed: React v17.0.1, node-sass v5.0.0, Then I tried to import a blank .scss file to the App component: File App.js import…
    JDKot
    • 6,643
    • 2
    • 10
    • 12
    634
    votes
    20 answers

    React.js inline style best practices

    I'm aware that you can specify styles within React classes, like this: const MyDiv = React.createClass({ render: function() { const style = { color: 'white', fontSize: 200 }; return
    Have a good and…
    eye_mew
    • 8,855
    • 7
    • 30
    • 50
    620
    votes
    37 answers

    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 }); doesn't work. How can this be done correctly?
    Alex Yong
    • 7,425
    • 8
    • 24
    • 41
    609
    votes
    19 answers

    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 modifying the array in-place with push might cause…
    fadedbee
    • 42,671
    • 44
    • 178
    • 308
    577
    votes
    16 answers

    Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

    I am trying to set up my React.js app so that it only renders if a variable I have set is true. The way my render function is set up looks like: render: function() { var text = this.state.submitted ? 'Thank you! Expect a follow up at…
    user1072337
    • 12,615
    • 37
    • 116
    • 195
    576
    votes
    11 answers

    Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

    There is a lot of talk about the latest kid in redux town right now, redux-saga/redux-saga. It uses generator functions for listening to/dispatching actions. Before I wrap my head around it, I would like to know the pros/cons of using redux-saga…
    hampusohlsson
    • 10,109
    • 5
    • 33
    • 50
    572
    votes
    25 answers

    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 props are immutable, I can't simply save its…
    Wojciech Kulma
    • 6,186
    • 3
    • 18
    • 27
    568
    votes
    11 answers

    ReactJS - .JS vs .JSX

    There is something I find very confusing when working in React.js. There are plenty of examples available on internet which use .js files with React but many others use .jsx files. I have read about JSX files and my understanding is that they just…
    ConfusedDeveloper
    • 6,389
    • 4
    • 21
    • 36