Socket
Socket
Sign inDemoInstall

react

Package Overview
Dependencies
41
Maintainers
4
Versions
1774
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    react

React is a JavaScript library for building user interfaces.


Version published
Maintainers
4
Install size
8.52 MB
Created

Package description

What is react?

The react npm package is a JavaScript library for building user interfaces, particularly for single-page applications. It allows developers to create reusable UI components and manage the state of their applications efficiently.

What are react's main functionalities?

Component-Based Architecture

React allows developers to encapsulate UI logic and design into components, which can then be composed to build complex user interfaces.

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
ReactDOM.render(<Welcome name='Jane' />, document.getElementById('root'));

State Management

React provides a way to manage the state within components, enabling dynamic and interactive user interfaces.

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };
  render() {
    return (
      <div>
        <p>{this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

Lifecycle Methods

React components come with lifecycle methods that are invoked at specific points in a component's lifecycle, allowing developers to hook into the component's creation, updating, and destruction processes.

class Timer extends React.Component {
  componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000);
  }
  componentWillUnmount() {
    clearInterval(this.timerID);
  }
  tick() {
    this.setState({
      date: new Date()
    });
  }
  render() {
    return (
      <div>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

Hooks

Hooks are functions that let developers 'hook into' React state and lifecycle features from function components. They provide a way to use stateful logic without writing a class.

import { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Other packages similar to react

Changelog

Source

0.14.0 (October 7, 2015)

Major changes

  • Split the main react package into two: react and react-dom. This paves the way to writing components that can be shared between the web version of React and React Native. This means you will need to include both files and some functions have been moved from React to ReactDOM.
  • Addons have been moved to separate packages (react-addons-clone-with-props, react-addons-create-fragment, react-addons-css-transition-group, react-addons-linked-state-mixin, react-addons-perf, react-addons-pure-render-mixin, react-addons-shallow-compare, react-addons-test-utils, react-addons-transition-group, react-addons-update, ReactDOM.unstable_batchedUpdates).
  • Stateless functional components - React components were previously created using React.createClass or using ES6 classes. This release adds a new syntax where a user defines a single stateless render function (with one parameter: props) which returns a JSX element, and this function may be used as a component.
  • Refs to DOM components as the DOM node itself. Previously the only useful thing you can do with a DOM component is call getDOMNode() to get the underlying DOM node. Starting with this release, a ref to a DOM component is the actual DOM node. Note that refs to custom (user-defined) components work exactly as before; only the built-in DOM components are affected by this change.

Breaking changes

  • React.initializeTouchEvents is no longer necessary and has been removed completely. Touch events now work automatically.
  • Add-Ons: Due to the DOM node refs change mentioned above, TestUtils.findAllInRenderedTree and related helpers are no longer able to take a DOM component, only a custom component.
  • The props object is now frozen, so mutating props after creating a component element is no longer supported. In most cases, React.cloneElement should be used instead. This change makes your components easier to reason about and enables the compiler optimizations mentioned above.
  • Plain objects are no longer supported as React children; arrays should be used instead. You can use the createFragment helper to migrate, which now returns an array.
  • Add-Ons: classSet has been removed. Use classnames instead.
  • Web components (custom elements) now use native property names. Eg: class instead of className.

Deprecations

  • this.getDOMNode() is now deprecated and ReactDOM.findDOMNode(this) can be used instead. Note that in the common case, findDOMNode is now unnecessary since a ref to the DOM component is now the actual DOM node.
  • setProps and replaceProps are now deprecated. Instead, call ReactDOM.render again at the top level with the new props.
  • ES6 component classes must now extend React.Component in order to enable stateless function components. The ES3 module pattern will continue to work.
  • Reusing and mutating a style object between renders has been deprecated. This mirrors our change to freeze the props object.
  • Add-Ons: cloneWithProps is now deprecated. Use React.cloneElement instead (unlike cloneWithProps, cloneElement does not merge className or style automatically; you can merge them manually if needed).
  • Add-Ons: To improve reliability, CSSTransitionGroup will no longer listen to transition events. Instead, you should specify transition durations manually using props such as transitionEnterTimeout={500}.

Notable enhancements

  • Added React.Children.toArray which takes a nested children object and returns a flat array with keys assigned to each child. This helper makes it easier to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down. In addition, React.Children.map now returns plain arrays too.
  • React uses console.error instead of console.warn for warnings so that browsers show a full stack trace in the console. (Our warnings appear when you use patterns that will break in future releases and for code that is likely to behave unexpectedly, so we do consider our warnings to be “must-fix” errors.)
  • Previously, including untrusted objects as React children could result in an XSS security vulnerability. This problem should be avoided by properly validating input at the application layer and by never passing untrusted objects around your application code. As an additional layer of protection, React now tags elements with a specific ES2015 (ES6) Symbol in browsers that support it, in order to ensure that React never considers untrusted JSON to be a valid element. If this extra security protection is important to you, you should add a Symbol polyfill for older browsers, such as the one included by Babel’s polyfill.
  • When possible, React DOM now generates XHTML-compatible markup.
  • React DOM now supports these standard HTML attributes: capture, challenge, inputMode, is, keyParams, keyType, minLength, summary, wrap. It also now supports these non-standard attributes: autoSave, results, security.
  • React DOM now supports these SVG attributes, which render into namespaced attributes: xlinkActuate, xlinkArcrole, xlinkHref, xlinkRole, xlinkShow, xlinkTitle, xlinkType, xmlBase, xmlLang, xmlSpace.
  • The image SVG tag is now supported by React DOM.
  • In React DOM, arbitrary attributes are supported on custom elements (those with a hyphen in the tag name or an is="..." attribute).
  • React DOM now supports these media events on audio and video tags: onAbort, onCanPlay, onCanPlayThrough, onDurationChange, onEmptied, onEncrypted, onEnded, onError, onLoadedData, onLoadedMetadata, onLoadStart, onPause, onPlay, onPlaying, onProgress, onRateChange, onSeeked, onSeeking, onStalled, onSuspend, onTimeUpdate, onVolumeChange, onWaiting.
  • Many small performance improvements have been made.
  • Many warnings show more context than before.
  • Add-Ons: A shallowCompare add-on has been added as a migration path for PureRenderMixin in ES6 classes.
  • Add-Ons: CSSTransitionGroup can now use custom class names instead of appending -enter-active or similar to the transition name.

New helpful warnings

  • React DOM now warns you when nesting HTML elements invalidly, which helps you avoid surprising errors during updates.
  • Passing document.body directly as the container to ReactDOM.render now gives a warning as doing so can cause problems with browser extensions that modify the DOM.
  • Using multiple instances of React together is not supported, so we now warn when we detect this case to help you avoid running into the resulting problems.

Notable bug fixes

  • Click events are handled by React DOM more reliably in mobile browsers, particularly in Mobile Safari.
  • SVG elements are created with the correct namespace in more cases.
  • React DOM now renders <option> elements with multiple text children properly and renders <select> elements on the server with the correct option selected.
  • When two separate copies of React add nodes to the same document (including when a browser extension uses React), React DOM tries harder not to throw exceptions during event handling.
  • Using non-lowercase HTML tag names in React DOM (e.g., React.createElement('DIV')) no longer causes problems, though we continue to recommend lowercase for consistency with the JSX tag name convention (lowercase names refer to built-in components, capitalized names refer to custom components).
  • React DOM understands that these CSS properties are unitless and does not append “px” to their values: animationIterationCount, boxOrdinalGroup, flexOrder, tabSize, stopOpacity.
  • Add-Ons: When using the test utils, Simulate.mouseEnter and Simulate.mouseLeave now work.
  • Add-Ons: ReactTransitionGroup now correctly handles multiple nodes being removed simultaneously.

React Tools / Babel

Breaking Changes
  • The react-tools package and JSXTransformer.js browser file have been deprecated. You can continue using version 0.13.3 of both, but we no longer support them and recommend migrating to Babel, which has built-in support for React and JSX.
New Features
  • Babel 5.8.24 introduces Inlining React elements: The optimisation.react.inlineElements transform converts JSX elements to object literals like {type: 'div', props: ...} instead of calls to React.createElement. This should only be enabled in production, since it disables some development warnings/checks.
  • Babel 5.8.24 introduces Constant hoisting for React elements: The optimisation.react.constantElements transform hoists element creation to the top level for subtrees that are fully static, which reduces calls to React.createElement and the resulting allocations. More importantly, it tells React that the subtree hasn’t changed so React can completely skip it when reconciling. This should only be enabled in production, since it disables some development warnings/checks.

Readme

Source

react

An npm package to get you immediate access to React, without also requiring the JSX transformer. This is especially useful for cases where you want to browserify your module using React.

Note: by default, React will be in development mode. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages.

To use React in production mode, set the environment variable NODE_ENV to production. A minifier that performs dead-code elimination such as UglifyJS is recommended to completely remove the extra code present in development mode.

Example Usage

var React = require('react');

// Addons can be accessed individually from the "addons" directory.
var createFragment = require('react/addons/createFragment');
var immutabilityHelpers = require('react/addons/update');
var CSSTransitionGroup = require('react/addons/CSSTransitionGroup');

For a complete list of addons visit the addons documentation page.

Keywords

FAQs

Last updated on 07 Oct 2015

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc