How to use react

Comprehensive react code examples:

How to use react.useId:

1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
        return [true, null];
    const { isPresent, onExitComplete, register } = context;
    // It's safe to call the following hooks conditionally (after an early return) because the context will always
    // either be null or non-null for the lifespan of the component.
    // Replace with useId when released in React
    const id = React.useId();
    React.useEffect(() => register(id), []);
    const safeToRemove = () => onExitComplete && onExitComplete(id);
    return !isPresent && onExitComplete ? [false, safeToRemove] : [true];
}

How to use react.js:

3
4
5
6
7
8
9
10
11
12
var Requirement = require('./Requirement');

var React = require('react');
var html = require('html');

// Takem from React.js
var _uppercasePattern = /([A-Z])/g;
function hyphenate(string) {
  return string.replace(_uppercasePattern, '-$1').toLowerCase();
}

How to use react.unstable_act:

1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
var getInstanceFromNode = EventInternals[0];
var getNodeFromInstance = EventInternals[1];
var getFiberCurrentPropsFromNode = EventInternals[2];
var enqueueStateRestore = EventInternals[3];
var restoreStateIfNeeded = EventInternals[4];
var act = React.unstable_act;


function Event(suffix) {}


var hasWarnedAboutDeprecatedMockComponent = false;

How to use react.renderToString:

40
41
42
43
44
45
46
47
48
49
    child = React.createElement(page, props, child);
    _.extend(props, page.defaultProps);
    React.renderToString(React.createElement(page, props, child));
    page = layout;
  }
  return React.renderToString(React.createElement(page, props, child));
}

/**
 * Just produce static markup without data-react-* attributes

How to use react.Fragment:

-2
-1
  return <Layout {...props}>{element}</Layout>
}

How to use react.useImperativeHandle:

62
63
64
65
66
67
68
69
70
71
            // eslint-disable-next-line no-console
            console.error(videoRef.current.constructor.manifest.name, error);
        }
    }
}, []);
React.useImperativeHandle(ref, () => ({ dispatch }), []);
React.useEffect(() => {
    return () => {
        dispatch({ type: 'command', commandName: 'destroy' });
    };

How to use react.useReducer:

38
39
40
41
42
43
44
45
46
47
const setImmersedDebounced = React.useCallback(debounce(setImmersed, 3000), []);
const [subtitlesMenuOpen, , closeSubtitlesMenu, toggleSubtitlesMenu] = useBinaryState(false);
const [infoMenuOpen, , closeInfoMenu, toggleInfoMenu] = useBinaryState(false);
const [videosMenuOpen, , closeVideosMenu, toggleVideosMenu] = useBinaryState(false);
const [error, setError] = React.useState(null);
const [videoState, setVideoState] = React.useReducer(
    (videoState, nextVideoState) => ({ ...videoState, ...nextVideoState }),
    {
        manifest: null,
        stream: null,

How to use react.renderToStaticMarkup:

1
2
3
4
5
6
7
8
9
10
var React = require('react')
var Cog = require('./Cog')

var build = function(name, props) {

  var svg = React.renderToStaticMarkup(React.createElement(Cog, props))
  
  fs.writeFileSync('icons/' + name + '.svg', svg)

}

How to use react.memo:

116
117
118
119
120
121
122
123
124
* * *

### `React.memo` {#reactmemo}

```javascript
const MyComponent = React.memo(function MyComponent(props) {
  /* props를 사용하여 렌더링 */
});
```

How to use react.useLayoutEffect:

26
27
28
29
30
31
32
33
34
35
    setSlidingVolume(volume);
    if (typeof onVolumeChangeRequested === 'function') {
        onVolumeChangeRequested(volume);
    }
}, [onVolumeChangeRequested]);
React.useLayoutEffect(() => {
    if (!routeFocused || disabled) {
        resetVolumeDebounced.cancel();
        setSlidingVolume(null);
    }

How to use react.isValidElement:

11
12
13
14
15
16
17
18
19
20
        return children;
}

// Insert separators
var separator = props.separator;
var separatorIsElement = React.isValidElement(separator);
var items = [children.shift()];
children.forEach(function(item, index) {
        if (separatorIsElement) {
                var key = 'separator-' + (item.key || index);

How to use react.cloneElement:

120
121
122
123
124
125
126
127
128
129
  function() {
    _this.setDropdown(false);
  }
) : onClick;

return React.cloneElement(
  child,
  assign({}, child.props, {
    key: `dropdownItem-${index}`,
    onClick: handleClick

How to use react.DOM:

163
164
165
166
167
168
169
170
171
  helloWorld: 'Hello world!'
});
var HelloWorld = React.createClass({
  mixins: [backboneMixin],
  render: function () {
    return React.DOM.div({}, this.state.model.helloWorld);
  }
});
var HelloWorldFactory = React.createFactory(HelloWorld);

How to use react.PureComponent:

4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
if (typeof instance.componentShouldUpdate === 'function') {
  error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);
}

if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
  error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component');
}

if (typeof instance.componentDidUnmount === 'function') {
  error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);

How to use react.forwardRef:

2
3
4
5
6
7
8
9
10
11
const React = require('react');
const PropTypes = require('prop-types');
const classnames = require('classnames');
const styles = require('./styles');

const Button = React.forwardRef(({ className, href, disabled, children, ...props }, ref) => {
    const onKeyDown = React.useCallback((event) => {
        if (typeof props.onKeyDown === 'function') {
            props.onKeyDown(event);
        }

How to use react.Component:

5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
{
  if (Component.prototype && typeof Component.prototype.render === 'function') {
    var componentName = getComponentNameFromType(Component) || 'Unknown';

    if (!didWarnAboutBadClass[componentName]) {
      error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);

      didWarnAboutBadClass[componentName] = true;
    }
  }

How to use react.unmountComponentAtNode:

266
267
268
269
270
271
272
273
274
},

clearExample() {
  const mountNode = React.findDOMNode(this.refs.mount);
  try {
    React.unmountComponentAtNode(mountNode);
  } catch (e) {
    console.error(e); // eslint-disable-line no-console
  }

How to use react.findDOMNode:

98
99
100
101
102
103
104
105
106
107
},
handleResize: function() {
        this.update(this.getTableWidth());
},
getTableWidth: function() {
        var n = React.findDOMNode(this.refs.table);
        var w = window.innerWidth - n.offsetLeft;
        return { tableWidth: w };
},
componentDidMount: function() {

How to use react.createFactory:

How to use react.createRef:

54
55
56
57
58
59
60
61
62
63

const wrappedFooComponent = forwardRef((props, ref) => {
  return <FooComponent theref={ref} {...props} />
})

const r = createRef()
ReactDOM.render(<wrappedFooComponent ref={r} />)
```

中间使用了 `props.theref` 做中转, 在 FooComponent 这里也可以 forwardRef, 避免 `theref` 取名

How to use react.Children:

109
110
111
112
113
114
115
116
117
118
},

renderChildren: function() {
  var _this = this;

  return React.Children.map(this.props.children, (child, index) => {
    if (React.isValidElement(child)) {
      var closeOnClick = child.props.closeOnClick;
      var onClick = child.props.onClick;
      var handleClick = closeOnClick ? createChainedFunction(

How to use react.render:

173
174
175
176
177
178
179
180
181
182
componentWillMount() {
  // For the initial render, we can hijack React.render to intercept the
  // example element and render it normally. This is safe because it's code
  // that we supply, so we can ensure ahead of time that it won't throw an
  // exception while rendering.
  const originalReactRender = React.render;
  React.render = (element) => this._initialExample = element;

  // Stub out mountNode for the example code.
  const mountNode = null;  // eslint-disable-line no-unused-vars

How to use react.useContext:

111
112
113
114
115
116
117
118
119
120
}

const DataGridDefaultComponentsContext = /*#__PURE__*/react.createContext(undefined);
const DataGridDefaultComponentsProvider = DataGridDefaultComponentsContext.Provider;
function useDefaultComponents() {
  return react.useContext(DataGridDefaultComponentsContext);
}

function SelectCellFormatter({
  value,

How to use react.createContext:

How to use react.useMemo:

14
15
16
17
18
19
20
21
22
23
const MetaDetails = ({ urlParams, queryParams }) => {
    const { core } = useServices();
    const metaDetails = useMetaDetails(urlParams);
    const [season, setSeason] = useSeason(urlParams, queryParams);
    const [tabs, metaExtension, clearMetaExtension] = useMetaExtensionTabs(metaDetails.metaExtensions);
    const [metaPath, streamPath] = React.useMemo(() => {
        return metaDetails.selected !== null ?
            [metaDetails.selected.metaPath, metaDetails.selected.streamPath]
            :
            [null, null];

How to use react.useRef:

1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
  viewScroll = _ref$viewScroll === void 0 ? 'initial' : _ref$viewScroll,
  portal = _ref.portal,
  theming = _ref.theming,
  onItemClick = _ref.onItemClick,
  restProps = _objectWithoutPropertiesLoose(_ref, _excluded$8);
var containerRef = react.useRef(null);
var scrollNodesRef = react.useRef({});
var anchorRef = restProps.anchorRef,
  state = restProps.state,
  onClose = restProps.onClose;

How to use react.createClass:

160
161
162
163
164
165
166
167
168
169
var React = require('react');

var model = new Backbone.Model({
  helloWorld: 'Hello world!'
});
var HelloWorld = React.createClass({
  mixins: [backboneMixin],
  render: function () {
    return React.DOM.div({}, this.state.model.helloWorld);
  }

How to use react.useEffect:

94
95
96
97
98
99
100
101
102
103
      ref.setDestinations = setDestinations;
    }
  },
});

React.useEffect(() => {
  if (destinationsProp != null) {
    setDestinations(destinationsProp);
  }
}, [setDestinations, destinationsProp]);

How to use react.useState:

178
179
180
181
182
183
184
185
186
187
188
});
Accordion.displayName = 'Accordion';


let current = 0;
const useIdShim = () => {
  const [id, setId] = react.useState();
  react.useEffect(() => setId(++current), []);
  return id && `${ACCORDION_PREFIX}-${id}`;
};
const _useId = react.useId || useIdShim;