React.js: понятное руководство для начинающих

styled(Component)(styles, [options]) => Component

Link a style sheet with a function component using the styled components pattern.


Arguments

  1. : The component that will be wrapped.
  2. (Function | Object): A function generating the styles or a styles object. It will be linked to the component. Use the function signature if you need to have access to the theme. It’s provided as property of the first argument.
  3. (Object ):
    • (Object ): The default theme to use if a theme isn’t supplied through a Theme Provider.
    • (Boolean ): Defaults to . Provide the object to the component as a property.
    • (String ): The name of the style sheet. Useful for debugging. If the value isn’t provided, it will try to fallback to the name of the component.
    • (Boolean ): When set to , this sheet will opt-out the transformation. When set to , the styles are inversed. When set to , it follows .
    • The other keys are forwarded to the options argument of .

Prior art

synthesizes ideas & APIs from several different sources:

  • Tachyons was one of the first (2014) CSS libraries to promote the Atomic CSS pattern (or Functional CSS).
  • Tachyons was later on (2017) followed by Tailwind CSS. They have made Atomic CSS more popular.
  • Twitter Bootstrap has slowly introduced atomic class names in v2, v3, and v4. The way they group their «Helper classes» was used as inspiration.
  • In the React world, Styled System was one of the first (2017) to promote the style functions. It can be used as a generic Box component replacing the atomic CSS helpers as well as helpers to write new components.
  • Large companies such as Pinterest, GitHub, and Segment.io are using the same approach in different flavours:
    • Evergreen Box
    • Primer Box
  • The actual implementation and the object responsive API was inspired by the Smooth-UI’s system.

Learn React

People come to React from different backgrounds and with different learning styles. Whether you prefer a more theoretical or a practical approach, we hope you’ll find this section helpful.

  • If you prefer to learn by doing, start with our practical tutorial.
  • If you prefer to learn concepts step by step, start with our guide to main concepts.

Like any unfamiliar technology, React does have a learning curve. With practice and some patience, you will get the hang of it.

First Examples

The React homepage contains a few small React examples with a live editor. Even if you don’t know anything about React yet, try changing their code and see how it affects the result.

React for Beginners

If you feel that the React documentation goes at a faster pace than you’re comfortable with, check out this overview of React by Tania Rascia. It introduces the most important React concepts in a detailed, beginner-friendly way. Once you’re done, give the documentation another try!

JavaScript Resources

The React documentation assumes some familiarity with programming in the JavaScript language. You don’t have to be an expert, but it’s harder to learn both React and JavaScript at the same time.

We recommend going through this JavaScript overview to check your knowledge level. It will take you between 30 minutes and an hour but you will feel more confident learning React.

Practical Tutorial

If you prefer to learn by doing, check out our practical tutorial. In this tutorial, we build a tic-tac-toe game in React. You might be tempted to skip it because you’re not into building games — but give it a chance. The techniques you’ll learn in the tutorial are fundamental to building any React apps, and mastering it will give you a much deeper understanding.

Step-by-Step Guide

If you prefer to learn concepts step by step, our guide to main concepts is the best place to start. Every next chapter in it builds on the knowledge introduced in the previous chapters so you won’t miss anything as you go along.

Thinking in React

Many React users credit reading Thinking in React as the moment React finally “clicked” for them. It’s probably the oldest React walkthrough but it’s still just as relevant.

Recommended Courses

Sometimes people find third-party books and video courses more helpful than the official documentation. We maintain a list of commonly recommended resources, some of which are free.

Advanced Concepts

Once you’re comfortable with the main concepts and played with React a little bit, you might be interested in more advanced topics. This section will introduce you to the powerful, but less commonly used React features like context and refs.

API Reference

This documentation section is useful when you want to learn more details about a particular React API. For example, API reference can provide you with details on how works, and what different lifecycle methods are useful for.

Glossary and FAQ

The glossary contains an overview of the most common terms you’ll see in the React documentation. There is also a FAQ section dedicated to short questions and answers about common topics, including making AJAX requests, component state, and file structure.

Props

Name Type Required Default Description
defaultValue string no undefined The default value for a single select*
defaultValues string[] no undefined The default value for a multiple select*
id string no undefined The id assigned to the input field and referenced by label
onChange (value: string | string[], SelectOption | SelectOption[] | undefined) => void yes The callback function called when the option is changed
options string[] | SelectOption[] yes The selectable options
SelectProps SelectProps no undefined The props for react-select component
value string no undefined The value for a single select*
values string[] no undefined The value for a multiple select*

* The order of the evaluated fields for deciding which is the selected value (take attention to the presence or not of the «s» after «value»):

  • single: value, defaultValue (values, defaultValues)
  • multiple: values, defaultValues (value, defaultValue)
Name Type Required Default Description
isClearable boolean no false Set to true to allow remove of selection with backspace or clicking on the x of the value(s)
isCreatable boolean no false Set to true to allow creation of new values based on the input string
msgNoOptionsAvailable string no No more options are available The message displayed when all options are already selected
msgNoOptionsMatchFilter string no No options match the filter The message displayed when no options match case-insensitive the input value
msgNoValidValue string no The new value is not valid (contains space) The message displayed when the input value is not accepted by a Creatable for creating a new value
  • placeholder (if there is set prop ‘label’, as they can overlap)
  • variant (as it is implemented only ‘standard’)
  • noOptionsMessage
  • placeholder
Name Type Required Description
label string yes The text displayed as option or value
value any yes The value associated to this option and returned by onChange

It does not accept by default new options containing space.

(inputValuestring)=> inputvalue !=="";

The format for a new options is: ‘INPUTED_TEXT (new)’.

(valuestring)=>`${value} (New Label)`;

The new option will be at start of options list.

Label: inputLabelProps.style

Subcomponents

SingleSelect — a component for selecting a single value. It can be imported with:

import{SingleSelect}from"react-select-material-ui";
import*asReactfrom"react";importMaterialUiCreatable,{MaterialUiCreatableProps}from"./MaterialUiCreatable";constSingleSelect=(propsMaterialUiCreatableProps)=>(<MaterialUiCreatable{...props}    SelectProps={{Without helper text...props.SelectProps,      isMultifalse}}    fullWidth={true}>);exportdefaultSingleSelect;

MultipleSelect — a component for selecting multiple values. It can be imported with:

import{MultipleSelect}from"react-select-material-ui";

Setting SelectProps.isClearable to true will display the clearable button only if there are more then one selected value.

import*asReactfrom"react";import MaterialUiCreatable,{MaterialUiCreatableProps,}from"./MaterialUiCreatable";constMultipleSelect=(propsMaterialUiCreatableProps)=>(<MaterialUiCreatable{...props}    SelectProps={{...props.SelectProps,      isMultitrue,      isClearabletrue,}}    fullWidth={true}>);exportdefaultMultipleSelect;

TagsSelect — a component for selecting multiple tag based on MultipleSelect. It can be imported with:

import{TagsSelect}from"react-select-material-ui";

ColorsSelect — a component for selecting multiple HTML colors (with preview) based on MultipleSelect. It can be imported with:

import{ColorsSelect}from"react-select-material-ui";

MaterialUI

MaterialUI is a set of React Components that Implement the Google’s Material Design Guidelines. There are 2 projects that you can look at to get started. They can be found in the examples folder. These projects are basic examples that show how to consume material-ui components in your own project. The first project uses browserify for module bundling and gulp for JS task automation, while the second project uses webpack for module bundling and building. You can include Material-UI in your project by simply running from your project’s directory, and then using the components of Material-UI that you need.

Content Security Policy (CSP)

What is CSP and why is it useful?

Basically, CSP mitigates cross-site scripting (XSS) attacks by requiring developers to whitelist the sources their assets are retrieved from. This list is returned as a header from the server. For instance, say you have a site hosted at the CSP header will allow all assets that are located at and deny all others. If there is a section of your website that is vulnerable to XSS where unescaped user input is displayed, an attacker could input something like:

This vulnerability would allow the attacker to execute anything. However, with a secure CSP header, the browser will not load this script.

You can read more about CSP on the MDN Web Docs.

How does one implement CSP?

In order to use CSP with Material-UI (and JSS), you need to use a nonce. A nonce is a randomly generated string that is only used once, therefore you need to add server middleware to generate one on each request. JSS has a great tutorial on how to achieve this with Express and React Helmet. For a basic rundown, continue reading.

A CSP nonce is a Base 64 encoded string. You can generate one like this:

It is very important that you use UUID version 4, as it generates an unpredictable string. You then apply this nonce to the CSP header. A CSP header might look like this with the nonce applied:

If you are using Server-Side Rendering (SSR), you should pass the nonce in the tag on the server.

Then, you must pass this nonce to JSS so it can add it to subsequent tags.

The way that you do this is by passing a tag in the of your HTML. JSS will then, by convention, look for a tag and use the value as the nonce.

You must include this header regardless of whether or not SSR is used. Here is an example of what a fictional header could look like:

StylesProvider

This component allows you to change the behavior of the styling solution. It makes the options available down the React tree thanks to the context.

It should preferably be used at the root of your component tree.

Props

Name Type Default Description
children * node Your component tree.
disableGeneration bool false You can disable the generation of the styles with this option. It can be useful when traversing the React tree outside of the HTML rendering step on the server. Let’s say you are using react-apollo to extract all the queries made by the interface server-side. You can significantly speed up the traversal with this property.
generateClassName func JSS’s class name generator.
injectFirst bool false By default, the styles are injected last in the element of the page. As a result, they gain more specificity than any other style sheet. If you want to override Material-UI’s styles, set this prop.
jss object JSS’s instance.

Versions

ReactSelectMaterialUi uses React-select Material-ui React
1.0.x 2.1.0 3.2.0 16.5.2
1.1.x 2.1.2 3.6.0 16.6.3
1.2.x 2.3.0 3.9.2 16.8.1
1.3.x 2.4.2 3.9.3 16.8.6
2.0.x 2.4.2 3.9.3 16.8.6
2.1.x 2.4.3 3.9.3 16.8.6
3.0.x 3.0.3 4.0.1 16.8.6
4.0.x 2.4.4 4.0.2 16.8.6
4.1.x 2.4.4 4.1.3 16.8.6
4.2.x 2.4.4 4.2.0 16.8.6
4.3.x 2.4.4 4.3.3 16.9.0
5.0.x 2.4.4 4.4.1 16.9.0
6.0.x 2.4.4 4.4.2 16.9.0
6.1.x 2.4.4 4.5.1 16.9.0
6.2.x 2.4.4 4.6.1 16.9.0
6.3.x 2.4.4 4.9.0 16.9.0
6.4.x 3.1.0 4.9.7 16.9.0
6.5.x 3.1.0 4.9.13 16.9.0
6.6.x 3.1.0 4.10.12 16.9.0
6.7.x 3.1.0 4.11.0 16.9.0
  • Major — it will be increased if any major version of any dependat package changes or there are breaking changes in this package
  • Minor — it will be increased if any minor or patch version of any dependat package changes or there is added functionality in a backwards compatible manner
  • Patch — it will be increased if there are backwards compatible bug fixes

Class names

The class names are generated by .

Default

By default, the class names generated by are non-deterministic; you can’t rely on them to stay the same. Let’s take the following style as an example:

This will generate a class name such as .

You have to use the prop of a component to override the styles. The non-deterministic nature of the class names enables style isolation.

In development, the class name is: .makeStyles-root-123, following this logic:

In production, the class name is: .jss123, following this logic:

With

The generated class names of the components behave differently. When the following conditions are met, the class names are deterministic:

  • Only one theme provider is used (No theme nesting)
  • The style sheet has a name that starts with (all Material-UI components).
  • The option of the is (the default).

These conditions are met with the most common use cases of . For instance, this style sheet:

generates the following class names that you can override:


This is a simplification of the component’s style sheet.

Customization of the TextField can be cumbersome with the , where you have to define the the classes prop. It’s easier to use the default values, as described above. For example:

Priorities

Here are the top priorities:

  • 1.0 — More components. This is challenging to address, as developing a fully-fledged component takes a considerable amount of time. We are going to try the following strategy:
    • Identify frequently needed components. There are many resources we can leverage for this: the developer survey answers, GitHub issue upvotes, Algolia search volume, Google search volume, documentation usage, npm downloads, etc.
      • Prioritize the creation of frequently needed components.
      • Encourage the usage of third-party components if they already exist and are well maintained.
      • Offer an option to the highly used and well maintained components to move to the official organization: mui-org/x on GitHub, @material-ui/x on npm and x.material-ui.com for the documentation.
  • 0.5 — Better customization. We want to make our component customization intuitive, no matter if you are using global CSS or styled-components:
    • Use styled-components by default: #6115.
    • Allow the use of the Box props in all the core components: #15561.
    • Allow the usage of dynamic theme variants and colors: #15573 & #13875.
    • Allow the use of the components without any styles: #6218.
    • Improve the support of custom breakpoints: #11649
    • Explore the integration with theme-specification, by @jxnblk.
  • 0.3 — Better documentation. This is a broad topic. The focus is on the following areas:
    • Page documentation rating . We will integrate a rating module in all our documentation pages. This way, we can collect high-quality data points and prioritize the pages that need the most to be improved.
    • Templates. They get people started really quickly, we need more of them!
    • Beginner tutorials & Video lessons.
  • 0.3 — TypeScript. There are two dimensions to this problem:
    • The documentation. We want to provide a TypeScript variant of most of our demos. You can help us out in #14897, we have already covered +90% of them.
    • The definitions. We are continuously improving them. For instance, we are working on moving the props descriptions to TypeScript, so you can access them directly from your IDE. The codebase is written in JavaScript, we don’t plan on migrating it to TypeScript in the near future. Upvote #15984 if you want us to rewrite the core in a future version.
  • 0.3 — Performance. React abstraction has a cost. The more components you render, the slower your page will be. You will notice stark differences when rendering a large table or list. Performance is all about doing less work. We can leverage the following:
    • Make the core faster.
    • Avoid re-rendering. It’s the responsibility of the user to prune the React rendering tree efficiently, as most of our APIs are too low level to implement efficient memoization (React.useMemo, React.memo). If you find a good opportunity for it, let us know, and we will be happy to work with you on the problem.
    • Avoid rendering. We have documented for the Table components. It’s important to consider it above 100 items.
  • 0.2 — Bundle size. You can keep track of our progress following bundlephobia.com report. It’s a continuous effort – v4 was 18% smaller than v3, while adding new features. We are eager to find new bundle size reduction opportunities. We hope we can leverage these two in the future:
    • A JSS to styled-component migration should help. Compare JSS v10.0.0-alpha.24 with styled-components v5.0.0-beta.8. We could save ~6 kB gzipped.
    • Popper.js is working on a smaller v2 version. We could save ~4 kB gzipped.
  • 0.2 — Accessibility. ️ We have relatively few accessibility issues, but we are eager to address them all. We would appreciate the help of accessibility experts.
  • 0.2 — Material Design Update. We are relatively up-to-date but the material design specification is evolving, so should we.

Versioning strategy

Stability ensures that reusable components and libraries, tutorials, tools, and learned practices don’t become obsolete unexpectedly. Stability is essential for the ecosystem around Material-UI to thrive.

This document contains the practices that are followed to provide you with a leading-edge UI library, balanced with stability, ensuring that future changes are always introduced in a predictable way.

Material-UI follows Semantic Versioning 2.0.0. Material-UI version numbers have three parts: . The version number is incremented based on the level of change included in the release.

  • Major releases contain significant new features, some but minimal developer assistance is expected during the update. When updating to a new major release, you may need to run update scripts, refactor code, run additional tests, and learn new APIs.
  • Minor releases contain important new features. Minor releases are fully backward-compatible; no developer assistance is expected during update, but you can optionally modify your apps and libraries to begin using new APIs, features, and capabilities that were added in the release.
  • Patch releases are low risk, contain bug fixes and small new features. No developer assistance is expected during update.

Changelog

  • Improved README.md
  • Changed the code to be conform to the behaviour described in Readme

Added subcomponents for: TagsSelect and ColorsSelect

Made SelectProps to accept also the props of Creatable besides of the normal ReactSelect

When adding a new value, it must be different than the existing values and options

Fixed a low severity vulnerability

Updated the react and material-ui packages

  • Hide the remove option in multiple select when it is disabled
  • Setting disabled or SelectProps.isDisabled to true will make the select disabled

Handle the case when the user removes the selected value and react-select returns null as selected value

Updated packages

Implemented support for placeholder when there is no label set

Added subcomponents for: TagSelect and ColorSelect (the single select versions of TagsSelect and ColorsSelect)

Updated packages

Fixed the display of values when using SelectOption instead of string

Breaking changes:

SelectOption accepts only strings for value

props in 1.x is … for react-select in 2.x is … for react-select
defaultValue/defaultValues ignored defaultValue
value/values defaultValue value

Enabled SelectOption.value to be of type any instead of string

  • Fixed bug related to: setting value to undefined displays the label over the previously selected value
  • If options are provided as SelectOption and there is one option having the value set to undefined, we will display its label if value is set to undefined

Fixed bug introduced with 2.1.0 related to: a selected value is not displayed when using the uncontrolled mode

Added the possibility to style the label using InputLabelProps.className (position and color will be overridden) or InputLabelProps.style

  • Reverted package react-select from v3 to v2 because of the mismatch between its types and structure of distributed package
  • Fixed using defaultValue(s) and value(s)
  • Added a storybook for this component
  • Change on behavior of onChange when value(s) is set. Before no call was triggered. Now it is called with the new selection. The component is controlled so there is no change in the visual if value(s) keep(s) the previous value
  • Updated packages

Fixed bug related to component not updating the selected value in the controlled mode


Updated packages

  • onChange returns as second argument the selected option(s)
  • corrected in index.d.ts the type of the value for onChange

Fixed the bug related to defaultValue(s) behaves as value(s)

  • Fixed the bug related to a new value(s) is ignored
  • Added more demo in storybook for controlled components
  • Updated the documentation
  • Added a storybook for styling the component
  • Updated packages
  • Starting with this version, react and react-dom are no longer dependencies, which means they will no longer be installed in node_modules of this component
  • Updated the packages

Fixed the dependency version of react

Removed the source maps from generated package

Added support for group of options

  • Setting SelectProps.isClearable to true will display the clear button also when the value is set via value(s) prop
  • Fixed the remove of the selected option(s) when the provided value(s) prop is null or values prop is an empty array
  • When the component is disabled, there is no clear button displayed
  • Fixed index.d.ts to include onBlur and onFocus

Fixed bug related to clear button not correctly displayed when the values of a multi select are changed

  • Fixed missing tslint package
  • Keep only the lock file for installing packages via npm
  • Improved the storybook
  • Updated packages
  • Added a storybook for keeping or not open at add time the multiple select options menu

Updated packages

  • Updated packages
  • Moved from npm to yarn

Fixed the typescript definition

Fixed the association between label and input field using the provided id

  • Fixed the selection of (default)value(s) based on the select type (single/multi)
  • Updated packages

Updated packages

Fixed the use of an empty string as initial value, value which matches a value defined in an option

Fixed the broken index.js produced by typescript 3.9.5 because of the «export *»

Fixed the issue when the value is not matched by any option

Updated packages

Office UI Fabric

Fabric is the official front-end framework for building experiences that fit seamlessly into Office and Office 365. Fabric is the official UX design framework for Office Add-ins. With Fabric, add-ins blend seamlessly with Word, Excel, PowerPoint, and Outlook. Fabric’s robust, up-to-date components are built with the React framework. Look through the component list to see the building blocks that are available using Fabric React. Fabric’s components help you get buttons, navigation, and more that look like Office quickly and easily. They also contain extra functionality that helps your app act like Office too.

Переопределение стилей — classes prop

The (hook generator) and (HOC) APIs allow the creation of multiple style rules per style sheet. Each style rule has its own class name. The class names are provided to the component with the variable. This is particularly useful when styling nested elements in a component.

However, the class names are often non-deterministic. How can a parent component override the style of a nested element?

This is the simplest case. the wrapped component accepts a prop, it simply merges the class names provided with the style sheet.

The hook API requires a bit more work. You have to forward the parent props to the hook as a first argument.

Props

Name Type Default Description
autoWidth bool false If true, the width of the popover will automatically be set according to the items inside the menu, otherwise it will be at least the width of the select input.
children node The option elements to populate the select with. Can be some when is false and when is true.
classes object Override or extend the styles applied to the component. See below for more details.
displayEmpty bool false If , the selected item is displayed even if its value is empty. You can only use it when the property is (default).
IconComponent union: string | func | object ArrowDropDownIcon The icon that displays the arrow.
input element <Input /> An element; does not have to be a material-ui specific .
inputProps object Attributes applied to the element. When is , the attributes are applied on the element.
MenuProps object Properties applied to the element.
multiple bool false If true, must be an array and the menu will support multiple selections. You can only use it when the property is (default).
native bool false If , the component will be using a native element.
onChange func Callback function fired when a menu item is selected.Signature:event: The event source of the callback. You can pull out the new value by accessing .child: The react element that was selected when is (default).
onClose func Callback fired when the component requests to be closed. Use in controlled mode (see open).Signature:event: The event source of the callback
onOpen func Callback fired when the component requests to be opened. Use in controlled mode (see open).Signature:event: The event source of the callback
open bool Control open state. You can only use it when the property is (default).
renderValue func Render the selected value. You can only use it when the property is (default).Signature:value: The provided to the component.
SelectDisplayProps object Properties applied to the clickable div element.
value union: string | number | bool | arrayOf The input value. This property is required when the property is (default).

Any other properties supplied will be spread to the root element (Input).

withStyles(styles, [options]) => higher-order component

Link a style sheet with a component using the higher-order component pattern. It does not modify the component passed to it; instead, it returns a new component with a property. This object contains the name of the class names injected in the DOM.

Some implementation details that might be interesting to being aware of:

  • It adds a property so you can override the injected class names from the outside.
  • It forwards refs to the inner component.
  • The prop is deprecated. Use instead.
  • It does not copy over statics. For instance, it can be used to defined a static method (next.js).

Arguments

  1. (Function | Object): A function generating the styles or a styles object. It will be linked to the component. Use the function signature if you need to have access to the theme. It’s provided as the first argument.
  2. (Object ):
    • (Object ): The default theme to use if a theme isn’t supplied through a Theme Provider.
    • (Boolean ): Defaults to . Provide the object to the component as a property.
    • (String ): The name of the style sheet. Useful for debugging. If the value isn’t provided, it will try to fallback to the name of the component.
    • (Boolean ): When set to , this sheet will opt-out the transformation. When set to , the styles are inversed. When set to , it follows .
    • The other keys are forwarded to the options argument of .

С этим читают