How to use ref method in storybook-root

Best JavaScript code snippet using storybook-root

forwardRef-test.js

Source:forwardRef-test.js Github

copy

Full Screen

1/**2 * Copyright (c) Facebook, Inc. and its affiliates.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 *7 * @emails react-core8 */9'use strict';10describe('forwardRef', () => {11 let PropTypes;12 let React;13 let ReactNoop;14 beforeEach(() => {15 jest.resetModules();16 PropTypes = require('prop-types');17 React = require('react');18 ReactNoop = require('react-noop-renderer');19 });20 it('should update refs when switching between children', () => {21 function FunctionComponent({forwardedRef, setRefOnDiv}) {22 return (23 <section>24 <div ref={setRefOnDiv ? forwardedRef : null}>First</div>25 <span ref={setRefOnDiv ? null : forwardedRef}>Second</span>26 </section>27 );28 }29 const RefForwardingComponent = React.forwardRef((props, ref) => (30 <FunctionComponent {...props} forwardedRef={ref} />31 ));32 const ref = React.createRef();33 ReactNoop.render(<RefForwardingComponent ref={ref} setRefOnDiv={true} />);34 ReactNoop.flush();35 expect(ref.current.type).toBe('div');36 ReactNoop.render(<RefForwardingComponent ref={ref} setRefOnDiv={false} />);37 ReactNoop.flush();38 expect(ref.current.type).toBe('span');39 });40 it('should support rendering null', () => {41 const RefForwardingComponent = React.forwardRef((props, ref) => null);42 const ref = React.createRef();43 ReactNoop.render(<RefForwardingComponent ref={ref} />);44 ReactNoop.flush();45 expect(ref.current).toBe(null);46 });47 it('should support rendering null for multiple children', () => {48 const RefForwardingComponent = React.forwardRef((props, ref) => null);49 const ref = React.createRef();50 ReactNoop.render(51 <div>52 <div />53 <RefForwardingComponent ref={ref} />54 <div />55 </div>,56 );57 ReactNoop.flush();58 expect(ref.current).toBe(null);59 });60 it('should support propTypes and defaultProps', () => {61 function FunctionComponent({forwardedRef, optional, required}) {62 return (63 <div ref={forwardedRef}>64 {optional}65 {required}66 </div>67 );68 }69 const RefForwardingComponent = React.forwardRef(function NamedFunction(70 props,71 ref,72 ) {73 return <FunctionComponent {...props} forwardedRef={ref} />;74 });75 RefForwardingComponent.propTypes = {76 optional: PropTypes.string,77 required: PropTypes.string.isRequired,78 };79 RefForwardingComponent.defaultProps = {80 optional: 'default',81 };82 const ref = React.createRef();83 ReactNoop.render(84 <RefForwardingComponent ref={ref} optional="foo" required="bar" />,85 );86 ReactNoop.flush();87 expect(ref.current.children).toEqual([88 {text: 'foo', hidden: false},89 {text: 'bar', hidden: false},90 ]);91 ReactNoop.render(<RefForwardingComponent ref={ref} required="foo" />);92 ReactNoop.flush();93 expect(ref.current.children).toEqual([94 {text: 'default', hidden: false},95 {text: 'foo', hidden: false},96 ]);97 expect(() =>98 ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />),99 ).toWarnDev(100 'Warning: Failed prop type: The prop `required` is marked as required in ' +101 '`ForwardRef(NamedFunction)`, but its value is `undefined`.\n' +102 ' in ForwardRef(NamedFunction) (at **)',103 );104 });105 it('should warn if not provided a callback during creation', () => {106 expect(() => React.forwardRef(undefined)).toWarnDev(107 'forwardRef requires a render function but was given undefined.',108 {withoutStack: true},109 );110 expect(() => React.forwardRef(null)).toWarnDev(111 'forwardRef requires a render function but was given null.',112 {withoutStack: true},113 );114 expect(() => React.forwardRef('foo')).toWarnDev(115 'forwardRef requires a render function but was given string.',116 {withoutStack: true},117 );118 });119 it('should warn if no render function is provided', () => {120 expect(React.forwardRef).toWarnDev(121 'forwardRef requires a render function but was given undefined.',122 {withoutStack: true},123 );124 });125 it('should warn if the render function provided has propTypes or defaultProps attributes', () => {126 function renderWithPropTypes(props, ref) {127 return null;128 }129 renderWithPropTypes.propTypes = {};130 function renderWithDefaultProps(props, ref) {131 return null;132 }133 renderWithDefaultProps.defaultProps = {};134 expect(() => React.forwardRef(renderWithPropTypes)).toWarnDev(135 'forwardRef render functions do not support propTypes or defaultProps. ' +136 'Did you accidentally pass a React component?',137 {withoutStack: true},138 );139 expect(() => React.forwardRef(renderWithDefaultProps)).toWarnDev(140 'forwardRef render functions do not support propTypes or defaultProps. ' +141 'Did you accidentally pass a React component?',142 {withoutStack: true},143 );144 });145 it('should not warn if the render function provided does not use any parameter', () => {146 const arityOfZero = () => <div ref={arguments[1]} />;147 React.forwardRef(arityOfZero);148 });149 it('should warn if the render function provided does not use the forwarded ref parameter', () => {150 const arityOfOne = props => <div {...props} />;151 expect(() => React.forwardRef(arityOfOne)).toWarnDev(152 'forwardRef render functions accept exactly two parameters: props and ref. ' +153 'Did you forget to use the ref parameter?',154 {withoutStack: true},155 );156 });157 it('should not warn if the render function provided use exactly two parameters', () => {158 const arityOfTwo = (props, ref) => <div {...props} ref={ref} />;159 React.forwardRef(arityOfTwo);160 });161 it('should warn if the render function provided expects to use more than two parameters', () => {162 const arityOfThree = (props, ref, x) => <div {...props} ref={ref} x={x} />;163 expect(() => React.forwardRef(arityOfThree)).toWarnDev(164 'forwardRef render functions accept exactly two parameters: props and ref. ' +165 'Any additional parameter will be undefined.',166 {withoutStack: true},167 );168 });169 it('should honor a displayName if set on the forwardRef wrapper in warnings', () => {170 const Component = props => <div {...props} />;171 const RefForwardingComponent = React.forwardRef((props, ref) => (172 <Component {...props} forwardedRef={ref} />173 ));174 RefForwardingComponent.displayName = 'Foo';175 RefForwardingComponent.propTypes = {176 optional: PropTypes.string,177 required: PropTypes.string.isRequired,178 };179 RefForwardingComponent.defaultProps = {180 optional: 'default',181 };182 const ref = React.createRef();183 expect(() =>184 ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />),185 ).toWarnDev(186 'Warning: Failed prop type: The prop `required` is marked as required in ' +187 '`Foo`, but its value is `undefined`.\n' +188 ' in Foo (at **)',189 );190 });191 it('should not bailout if forwardRef is not wrapped in memo', () => {192 const Component = props => <div {...props} />;193 let renderCount = 0;194 const RefForwardingComponent = React.forwardRef((props, ref) => {195 renderCount++;196 return <Component {...props} forwardedRef={ref} />;197 });198 const ref = React.createRef();199 ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />);200 ReactNoop.flush();201 expect(renderCount).toBe(1);202 ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />);203 ReactNoop.flush();204 expect(renderCount).toBe(2);205 });206 it('should bailout if forwardRef is wrapped in memo', () => {207 const Component = props => <div ref={props.forwardedRef} />;208 let renderCount = 0;209 const RefForwardingComponent = React.memo(210 React.forwardRef((props, ref) => {211 renderCount++;212 return <Component {...props} forwardedRef={ref} />;213 }),214 );215 const ref = React.createRef();216 ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />);217 ReactNoop.flush();218 expect(renderCount).toBe(1);219 expect(ref.current.type).toBe('div');220 ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />);221 ReactNoop.flush();222 expect(renderCount).toBe(1);223 const differentRef = React.createRef();224 ReactNoop.render(225 <RefForwardingComponent ref={differentRef} optional="foo" />,226 );227 ReactNoop.flush();228 expect(renderCount).toBe(2);229 expect(ref.current).toBe(null);230 expect(differentRef.current.type).toBe('div');231 ReactNoop.render(<RefForwardingComponent ref={ref} optional="bar" />);232 ReactNoop.flush();233 expect(renderCount).toBe(3);234 });235 it('should custom memo comparisons to compose', () => {236 const Component = props => <div ref={props.forwardedRef} />;237 let renderCount = 0;238 const RefForwardingComponent = React.memo(239 React.forwardRef((props, ref) => {240 renderCount++;241 return <Component {...props} forwardedRef={ref} />;242 }),243 (o, p) => o.a === p.a && o.b === p.b,244 );245 const ref = React.createRef();246 ReactNoop.render(<RefForwardingComponent ref={ref} a="0" b="0" c="1" />);247 ReactNoop.flush();248 expect(renderCount).toBe(1);249 expect(ref.current.type).toBe('div');250 // Changing either a or b rerenders251 ReactNoop.render(<RefForwardingComponent ref={ref} a="0" b="1" c="1" />);252 ReactNoop.flush();253 expect(renderCount).toBe(2);254 // Changing c doesn't rerender255 ReactNoop.render(<RefForwardingComponent ref={ref} a="0" b="1" c="2" />);256 ReactNoop.flush();257 expect(renderCount).toBe(2);258 const ComposedMemo = React.memo(259 RefForwardingComponent,260 (o, p) => o.a === p.a && o.c === p.c,261 );262 ReactNoop.render(<ComposedMemo ref={ref} a="0" b="0" c="0" />);263 ReactNoop.flush();264 expect(renderCount).toBe(3);265 // Changing just b no longer updates266 ReactNoop.render(<ComposedMemo ref={ref} a="0" b="1" c="0" />);267 ReactNoop.flush();268 expect(renderCount).toBe(3);269 // Changing just a and c updates270 ReactNoop.render(<ComposedMemo ref={ref} a="2" b="2" c="2" />);271 ReactNoop.flush();272 expect(renderCount).toBe(4);273 // Changing just c does not update274 ReactNoop.render(<ComposedMemo ref={ref} a="2" b="2" c="3" />);275 ReactNoop.flush();276 expect(renderCount).toBe(4);277 // Changing ref still rerenders278 const differentRef = React.createRef();279 ReactNoop.render(<ComposedMemo ref={differentRef} a="2" b="2" c="3" />);280 ReactNoop.flush();281 expect(renderCount).toBe(5);282 expect(ref.current).toBe(null);283 expect(differentRef.current.type).toBe('div');284 });285 it('warns on forwardRef(memo(...))', () => {286 expect(() => {287 React.forwardRef(288 React.memo((props, ref) => {289 return null;290 }),291 );292 }).toWarnDev(293 [294 'Warning: forwardRef requires a render function but received a `memo` ' +295 'component. Instead of forwardRef(memo(...)), use ' +296 'memo(forwardRef(...)).',297 ],298 {withoutStack: true},299 );300 });...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1'use strict';2var resolve = require('./resolve')3 , util = require('./util')4 , errorClasses = require('./error_classes')5 , stableStringify = require('fast-json-stable-stringify');6var validateGenerator = require('../dotjs/validate');7/**8 * Functions below are used inside compiled validations function9 */10var ucs2length = util.ucs2length;11var equal = require('fast-deep-equal');12// this error is thrown by async schemas to return validation errors via exception13var ValidationError = errorClasses.Validation;14module.exports = compile;15/**16 * Compiles schema to validation function17 * @this Ajv18 * @param {Object} schema schema object19 * @param {Object} root object with information about the root schema for this schema20 * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution21 * @param {String} baseId base ID for IDs in the schema22 * @return {Function} validation function23 */24function compile(schema, root, localRefs, baseId) {25 /* jshint validthis: true, evil: true */26 /* eslint no-shadow: 0 */27 var self = this28 , opts = this._opts29 , refVal = [ undefined ]30 , refs = {}31 , patterns = []32 , patternsHash = {}33 , defaults = []34 , defaultsHash = {}35 , customRules = [];36 root = root || { schema: schema, refVal: refVal, refs: refs };37 var c = checkCompiling.call(this, schema, root, baseId);38 var compilation = this._compilations[c.index];39 if (c.compiling) return (compilation.callValidate = callValidate);40 var formats = this._formats;41 var RULES = this.RULES;42 try {43 var v = localCompile(schema, root, localRefs, baseId);44 compilation.validate = v;45 var cv = compilation.callValidate;46 if (cv) {47 cv.schema = v.schema;48 cv.errors = null;49 cv.refs = v.refs;50 cv.refVal = v.refVal;51 cv.root = v.root;52 cv.$async = v.$async;53 if (opts.sourceCode) cv.source = v.source;54 }55 return v;56 } finally {57 endCompiling.call(this, schema, root, baseId);58 }59 /* @this {*} - custom context, see passContext option */60 function callValidate() {61 /* jshint validthis: true */62 var validate = compilation.validate;63 var result = validate.apply(this, arguments);64 callValidate.errors = validate.errors;65 return result;66 }67 function localCompile(_schema, _root, localRefs, baseId) {68 var isRoot = !_root || (_root && _root.schema == _schema);69 if (_root.schema != root.schema)70 return compile.call(self, _schema, _root, localRefs, baseId);71 var $async = _schema.$async === true;72 var sourceCode = validateGenerator({73 isTop: true,74 schema: _schema,75 isRoot: isRoot,76 baseId: baseId,77 root: _root,78 schemaPath: '',79 errSchemaPath: '#',80 errorPath: '""',81 MissingRefError: errorClasses.MissingRef,82 RULES: RULES,83 validate: validateGenerator,84 util: util,85 resolve: resolve,86 resolveRef: resolveRef,87 usePattern: usePattern,88 useDefault: useDefault,89 useCustomRule: useCustomRule,90 opts: opts,91 formats: formats,92 logger: self.logger,93 self: self94 });95 sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)96 + vars(defaults, defaultCode) + vars(customRules, customRuleCode)97 + sourceCode;98 if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);99 // console.log('\n\n\n *** \n', JSON.stringify(sourceCode));100 var validate;101 try {102 var makeValidate = new Function(103 'self',104 'RULES',105 'formats',106 'root',107 'refVal',108 'defaults',109 'customRules',110 'equal',111 'ucs2length',112 'ValidationError',113 sourceCode114 );115 validate = makeValidate(116 self,117 RULES,118 formats,119 root,120 refVal,121 defaults,122 customRules,123 equal,124 ucs2length,125 ValidationError126 );127 refVal[0] = validate;128 } catch(e) {129 self.logger.error('Error compiling schema, function code:', sourceCode);130 throw e;131 }132 validate.schema = _schema;133 validate.errors = null;134 validate.refs = refs;135 validate.refVal = refVal;136 validate.root = isRoot ? validate : _root;137 if ($async) validate.$async = true;138 if (opts.sourceCode === true) {139 validate.source = {140 code: sourceCode,141 patterns: patterns,142 defaults: defaults143 };144 }145 return validate;146 }147 function resolveRef(baseId, ref, isRoot) {148 ref = resolve.url(baseId, ref);149 var refIndex = refs[ref];150 var _refVal, refCode;151 if (refIndex !== undefined) {152 _refVal = refVal[refIndex];153 refCode = 'refVal[' + refIndex + ']';154 return resolvedRef(_refVal, refCode);155 }156 if (!isRoot && root.refs) {157 var rootRefId = root.refs[ref];158 if (rootRefId !== undefined) {159 _refVal = root.refVal[rootRefId];160 refCode = addLocalRef(ref, _refVal);161 return resolvedRef(_refVal, refCode);162 }163 }164 refCode = addLocalRef(ref);165 var v = resolve.call(self, localCompile, root, ref);166 if (v === undefined) {167 var localSchema = localRefs && localRefs[ref];168 if (localSchema) {169 v = resolve.inlineRef(localSchema, opts.inlineRefs)170 ? localSchema171 : compile.call(self, localSchema, root, localRefs, baseId);172 }173 }174 if (v === undefined) {175 removeLocalRef(ref);176 } else {177 replaceLocalRef(ref, v);178 return resolvedRef(v, refCode);179 }180 }181 function addLocalRef(ref, v) {182 var refId = refVal.length;183 refVal[refId] = v;184 refs[ref] = refId;185 return 'refVal' + refId;186 }187 function removeLocalRef(ref) {188 delete refs[ref];189 }190 function replaceLocalRef(ref, v) {191 var refId = refs[ref];192 refVal[refId] = v;193 }194 function resolvedRef(refVal, code) {195 return typeof refVal == 'object' || typeof refVal == 'boolean'196 ? { code: code, schema: refVal, inline: true }197 : { code: code, $async: refVal && !!refVal.$async };198 }199 function usePattern(regexStr) {200 var index = patternsHash[regexStr];201 if (index === undefined) {202 index = patternsHash[regexStr] = patterns.length;203 patterns[index] = regexStr;204 }205 return 'pattern' + index;206 }207 function useDefault(value) {208 switch (typeof value) {209 case 'boolean':210 case 'number':211 return '' + value;212 case 'string':213 return util.toQuotedString(value);214 case 'object':215 if (value === null) return 'null';216 var valueStr = stableStringify(value);217 var index = defaultsHash[valueStr];218 if (index === undefined) {219 index = defaultsHash[valueStr] = defaults.length;220 defaults[index] = value;221 }222 return 'default' + index;223 }224 }225 function useCustomRule(rule, schema, parentSchema, it) {226 if (self._opts.validateSchema !== false) {227 var deps = rule.definition.dependencies;228 if (deps && !deps.every(function(keyword) {229 return Object.prototype.hasOwnProperty.call(parentSchema, keyword);230 }))231 throw new Error('parent schema must have all required keywords: ' + deps.join(','));232 var validateSchema = rule.definition.validateSchema;233 if (validateSchema) {234 var valid = validateSchema(schema);235 if (!valid) {236 var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);237 if (self._opts.validateSchema == 'log') self.logger.error(message);238 else throw new Error(message);239 }240 }241 }242 var compile = rule.definition.compile243 , inline = rule.definition.inline244 , macro = rule.definition.macro;245 var validate;246 if (compile) {247 validate = compile.call(self, schema, parentSchema, it);248 } else if (macro) {249 validate = macro.call(self, schema, parentSchema, it);250 if (opts.validateSchema !== false) self.validateSchema(validate, true);251 } else if (inline) {252 validate = inline.call(self, it, rule.keyword, schema, parentSchema);253 } else {254 validate = rule.definition.validate;255 if (!validate) return;256 }257 if (validate === undefined)258 throw new Error('custom keyword "' + rule.keyword + '"failed to compile');259 var index = customRules.length;260 customRules[index] = validate;261 return {262 code: 'customRule' + index,263 validate: validate264 };265 }266}267/**268 * Checks if the schema is currently compiled269 * @this Ajv270 * @param {Object} schema schema to compile271 * @param {Object} root root object272 * @param {String} baseId base schema ID273 * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)274 */275function checkCompiling(schema, root, baseId) {276 /* jshint validthis: true */277 var index = compIndex.call(this, schema, root, baseId);278 if (index >= 0) return { index: index, compiling: true };279 index = this._compilations.length;280 this._compilations[index] = {281 schema: schema,282 root: root,283 baseId: baseId284 };285 return { index: index, compiling: false };286}287/**288 * Removes the schema from the currently compiled list289 * @this Ajv290 * @param {Object} schema schema to compile291 * @param {Object} root root object292 * @param {String} baseId base schema ID293 */294function endCompiling(schema, root, baseId) {295 /* jshint validthis: true */296 var i = compIndex.call(this, schema, root, baseId);297 if (i >= 0) this._compilations.splice(i, 1);298}299/**300 * Index of schema compilation in the currently compiled list301 * @this Ajv302 * @param {Object} schema schema to compile303 * @param {Object} root root object304 * @param {String} baseId base schema ID305 * @return {Integer} compilation index306 */307function compIndex(schema, root, baseId) {308 /* jshint validthis: true */309 for (var i=0; i<this._compilations.length; i++) {310 var c = this._compilations[i];311 if (c.schema == schema && c.root == root && c.baseId == baseId) return i;312 }313 return -1;314}315function patternCode(i, patterns) {316 return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';317}318function defaultCode(i) {319 return 'var default' + i + ' = defaults[' + i + '];';320}321function refValCode(i, refVal) {322 return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';323}324function customRuleCode(i) {325 return 'var customRule' + i + ' = customRules[' + i + '];';326}327function vars(arr, statement) {328 if (!arr.length) return '';329 var code = '';330 for (var i=0; i<arr.length; i++)331 code += statement(i, arr);332 return code;...

Full Screen

Full Screen

forwardRef-test.internal.js

Source:forwardRef-test.internal.js Github

copy

Full Screen

1/**2 * Copyright (c) Facebook, Inc. and its affiliates.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 *7 * @emails react-core8 */9'use strict';10describe('forwardRef', () => {11 let React;12 let ReactFeatureFlags;13 let ReactNoop;14 beforeEach(() => {15 jest.resetModules();16 ReactFeatureFlags = require('shared/ReactFeatureFlags');17 ReactFeatureFlags.debugRenderPhaseSideEffectsForStrictMode = false;18 ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false;19 React = require('react');20 ReactNoop = require('react-noop-renderer');21 });22 it('should work without a ref to be forwarded', () => {23 class Child extends React.Component {24 render() {25 ReactNoop.yield(this.props.value);26 return null;27 }28 }29 function Wrapper(props) {30 return <Child {...props} ref={props.forwardedRef} />;31 }32 const RefForwardingComponent = React.forwardRef((props, ref) => (33 <Wrapper {...props} forwardedRef={ref} />34 ));35 ReactNoop.render(<RefForwardingComponent value={123} />);36 expect(ReactNoop.flush()).toEqual([123]);37 });38 it('should forward a ref for a single child', () => {39 class Child extends React.Component {40 render() {41 ReactNoop.yield(this.props.value);42 return null;43 }44 }45 function Wrapper(props) {46 return <Child {...props} ref={props.forwardedRef} />;47 }48 const RefForwardingComponent = React.forwardRef((props, ref) => (49 <Wrapper {...props} forwardedRef={ref} />50 ));51 const ref = React.createRef();52 ReactNoop.render(<RefForwardingComponent ref={ref} value={123} />);53 expect(ReactNoop.flush()).toEqual([123]);54 expect(ref.current instanceof Child).toBe(true);55 });56 it('should forward a ref for multiple children', () => {57 class Child extends React.Component {58 render() {59 ReactNoop.yield(this.props.value);60 return null;61 }62 }63 function Wrapper(props) {64 return <Child {...props} ref={props.forwardedRef} />;65 }66 const RefForwardingComponent = React.forwardRef((props, ref) => (67 <Wrapper {...props} forwardedRef={ref} />68 ));69 const ref = React.createRef();70 ReactNoop.render(71 <div>72 <div />73 <RefForwardingComponent ref={ref} value={123} />74 <div />75 </div>,76 );77 expect(ReactNoop.flush()).toEqual([123]);78 expect(ref.current instanceof Child).toBe(true);79 });80 it('should maintain child instance and ref through updates', () => {81 class Child extends React.Component {82 constructor(props) {83 super(props);84 }85 render() {86 ReactNoop.yield(this.props.value);87 return null;88 }89 }90 function Wrapper(props) {91 return <Child {...props} ref={props.forwardedRef} />;92 }93 const RefForwardingComponent = React.forwardRef((props, ref) => (94 <Wrapper {...props} forwardedRef={ref} />95 ));96 let setRefCount = 0;97 let ref;98 const setRef = r => {99 setRefCount++;100 ref = r;101 };102 ReactNoop.render(<RefForwardingComponent ref={setRef} value={123} />);103 expect(ReactNoop.flush()).toEqual([123]);104 expect(ref instanceof Child).toBe(true);105 expect(setRefCount).toBe(1);106 ReactNoop.render(<RefForwardingComponent ref={setRef} value={456} />);107 expect(ReactNoop.flush()).toEqual([456]);108 expect(ref instanceof Child).toBe(true);109 expect(setRefCount).toBe(1);110 });111 it('should not break lifecycle error handling', () => {112 class ErrorBoundary extends React.Component {113 state = {error: null};114 componentDidCatch(error) {115 ReactNoop.yield('ErrorBoundary.componentDidCatch');116 this.setState({error});117 }118 render() {119 if (this.state.error) {120 ReactNoop.yield('ErrorBoundary.render: catch');121 return null;122 }123 ReactNoop.yield('ErrorBoundary.render: try');124 return this.props.children;125 }126 }127 class BadRender extends React.Component {128 render() {129 ReactNoop.yield('BadRender throw');130 throw new Error('oops!');131 }132 }133 function Wrapper(props) {134 ReactNoop.yield('Wrapper');135 return <BadRender {...props} ref={props.forwardedRef} />;136 }137 const RefForwardingComponent = React.forwardRef((props, ref) => (138 <Wrapper {...props} forwardedRef={ref} />139 ));140 const ref = React.createRef();141 ReactNoop.render(142 <ErrorBoundary>143 <RefForwardingComponent ref={ref} />144 </ErrorBoundary>,145 );146 expect(ReactNoop.flush()).toEqual([147 'ErrorBoundary.render: try',148 'Wrapper',149 'BadRender throw',150 // React retries one more time151 'ErrorBoundary.render: try',152 'Wrapper',153 'BadRender throw',154 // Errored again on retry. Now handle it.155 'ErrorBoundary.componentDidCatch',156 'ErrorBoundary.render: catch',157 ]);158 expect(ref.current).toBe(null);159 });160 it('should not re-run the render callback on a deep setState', () => {161 let inst;162 class Inner extends React.Component {163 render() {164 ReactNoop.yield('Inner');165 inst = this;166 return <div ref={this.props.forwardedRef} />;167 }168 }169 function Middle(props) {170 ReactNoop.yield('Middle');171 return <Inner {...props} />;172 }173 const Forward = React.forwardRef((props, ref) => {174 ReactNoop.yield('Forward');175 return <Middle {...props} forwardedRef={ref} />;176 });177 function App() {178 ReactNoop.yield('App');179 return <Forward />;180 }181 ReactNoop.render(<App />);182 expect(ReactNoop.flush()).toEqual(['App', 'Forward', 'Middle', 'Inner']);183 inst.setState({});184 expect(ReactNoop.flush()).toEqual(['Inner']);185 });...

Full Screen

Full Screen

AddressForm.js

Source:AddressForm.js Github

copy

Full Screen

1import axios from 'axios';2import React, { useRef, useContext } from 'react';3import { AuthContext } from '../context/AuthContext';4import { Button, Card, Col, Form, Row } from 'react-bootstrap';5const AddressForm = ({ getNewAddress }) => {6 const { user } = useContext(AuthContext);7 const cityRef = useRef();8 const commentRef = useRef();9 const countryRef = useRef();10 const lastNameRef = useRef();11 const postCodeRef = useRef();12 const extensionRef = useRef();13 const firstNameRef = useRef();14 const streetNameRef = useRef();15 const buildingNumberRef = useRef();16 const addToLocalStorage = (id) => {17 const userData = JSON.parse(localStorage.user);18 userData.addresses.push(id);19 localStorage.setItem('user', JSON.stringify(userData));20 };21 const handleClick = async (e) => {22 e.preventDefault();23 const newAddress = {24 user: user._id,25 city: cityRef.current.value || null,26 last_name: lastNameRef.current.value,27 extension: extensionRef.current.value,28 first_name: firstNameRef.current.value,29 comment: commentRef.current.value || '',30 country: countryRef.current.value || null,31 post_code: postCodeRef.current.value || null,32 street_name: streetNameRef.current.value || null,33 building_number: buildingNumberRef.current.value || null,34 };35 const isValid = () => {36 for (const key in newAddress) if (newAddress[key] === null) return false;37 return true;38 };39 if (isValid()) {40 const response = await axios.post(41 `${process.env.REACT_APP_API_URL}/addresses/create`,42 newAddress,43 );44 getNewAddress(response.data.address);45 addToLocalStorage(response.data.address._id);46 }47 };48 return (49 <>50 <Card style={cardStyles}>51 <Card.Header>Shipping Address</Card.Header>52 <Card.Body>53 <Row>54 <Col md={6}>55 <Form.Control56 type="text"57 ref={firstNameRef}58 style={inputStyles}59 placeholder="First Name"60 />61 </Col>62 <Col md={6}>63 <Form.Control64 type="text"65 ref={lastNameRef}66 style={inputStyles}67 placeholder="Last Name"68 />69 </Col>70 </Row>71 <Row>72 <Col md={6}>73 <Form.Control74 type="text"75 style={inputStyles}76 ref={streetNameRef}77 placeholder="Street Name *"78 />79 </Col>80 <Col md={4}>81 <Form.Control82 type="text"83 style={inputStyles}84 ref={buildingNumberRef}85 placeholder="Building Number *"86 />87 </Col>88 <Col md={2}>89 <Form.Control90 type="text"91 ref={extensionRef}92 style={inputStyles}93 placeholder="Ext. (Optional)"94 />95 </Col>96 </Row>97 <Row>98 <Col md={4}>99 <Form.Control100 type="text"101 ref={postCodeRef}102 style={inputStyles}103 placeholder="Post Code *"104 />105 </Col>106 <Col md={4}>107 <Form.Control type="text" ref={cityRef} placeholder="City *" style={inputStyles} />108 </Col>109 <Col md={4}>110 <Form.Control111 type="text"112 ref={countryRef}113 style={inputStyles}114 placeholder="Country *"115 />116 </Col>117 </Row>118 <Row>119 <Col>120 <Form.Control121 type="text"122 ref={commentRef}123 style={inputStyles}124 placeholder="Comment (Optional)"125 />126 </Col>127 </Row>128 <Row>129 <Col md={12}>130 <Button131 value="Add"132 type="submit"133 style={btnStyles}134 onClick={handleClick}135 className="btn btn-primary"136 >137 Add138 </Button>139 </Col>140 </Row>141 </Card.Body>142 </Card>143 <br />144 <br />145 </>146 );147};148const cardStyles = {149 marginBottom: '10px',150 borderColor: 'var(--color-main)',151};152const inputStyles = {153 width: '100%',154 marginBottom: '10px',155};156const btnStyles = {157 marginTop: '10px',158 background: 'var(--color-main)',159};...

Full Screen

Full Screen

setAndForwardRef-test.js

Source:setAndForwardRef-test.js Github

copy

Full Screen

1/**2 * Copyright (c) Facebook, Inc. and its affiliates.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 *7 * @flow8 * @format9 * @emails oncall+react_native10 */11'use strict';12const React = require('react');13const ReactTestRenderer = require('react-test-renderer');14const setAndForwardRef = require('../setAndForwardRef');15describe('setAndForwardRef', () => {16 let innerFuncCalled = false;17 let outerFuncCalled = false;18 class ForwardedComponent extends React.Component<{||}> {19 testFunc() {20 innerFuncCalled = true;21 return true;22 }23 render() {24 return null;25 }26 }27 type Props = $ReadOnly<{|28 callFunc?: ?boolean,29 forwardedRef: React.Ref<typeof ForwardedComponent>,30 |}>;31 class TestComponent extends React.Component<Props> {32 _nativeRef: ?React.ElementRef<typeof ForwardedComponent> = null;33 _setNativeRef = setAndForwardRef({34 getForwardedRef: () => this.props.forwardedRef,35 setLocalRef: ref => {36 this._nativeRef = ref;37 },38 });39 componentDidMount() {40 if (this.props.callFunc) {41 outerFuncCalled = this._nativeRef && this._nativeRef.testFunc();42 }43 }44 render() {45 return <ForwardedComponent ref={this._setNativeRef} />;46 }47 }48 const TestComponentWithRef = React.forwardRef((props, ref) => (49 <TestComponent {...props} forwardedRef={ref} />50 ));51 beforeEach(() => {52 innerFuncCalled = false;53 outerFuncCalled = false;54 });55 it('should forward refs (function-based)', () => {56 let testRef: ?React.ElementRef<typeof ForwardedComponent> = null;57 ReactTestRenderer.create(58 <TestComponentWithRef59 ref={ref => {60 testRef = ref;61 }}62 />,63 );64 const val = testRef && testRef.testFunc();65 expect(innerFuncCalled).toBe(true);66 expect(val).toBe(true);67 });68 it('should forward refs (createRef-based)', () => {69 const createdRef = React.createRef<typeof ForwardedComponent>();70 /* $FlowFixMe(>=0.89.0 site=react_native_fb) This comment suppresses an71 * error found when Flow v0.89 was deployed. To see the error, delete this72 * comment and run Flow. */73 ReactTestRenderer.create(<TestComponentWithRef ref={createdRef} />);74 /* $FlowFixMe(>=0.87.0 site=react_native_fb) This comment suppresses an75 * error found when Flow v0.87 was deployed. To see the error, delete this76 * comment and run Flow. */77 const val = createdRef.current && createdRef.current.testFunc();78 expect(innerFuncCalled).toBe(true);79 expect(val).toBe(true);80 });81 it('should forward refs (string-based)', () => {82 class Test extends React.Component<{||}> {83 refs: $ReadOnly<{|84 stringRef?: ?React.ElementRef<typeof ForwardedComponent>,85 |}>;86 componentDidMount() {87 /* eslint-disable react/no-string-refs */88 this.refs.stringRef && this.refs.stringRef.testFunc();89 /* eslint-enable react/no-string-refs */90 }91 render() {92 /**93 * Can't directly pass the test component to `ReactTestRenderer.create`,94 * otherwise it will throw. See:95 * https://reactjs.org/warnings/refs-must-have-owner.html#strings-refs-outside-the-render-method96 */97 /* eslint-disable react/no-string-refs */98 return <TestComponentWithRef ref="stringRef" />;99 /* eslint-enable react/no-string-refs */100 }101 }102 ReactTestRenderer.create(<Test />);103 expect(innerFuncCalled).toBe(true);104 });105 it('should be able to use the ref from inside of the forwarding class', () => {106 expect(() =>107 ReactTestRenderer.create(<TestComponentWithRef callFunc={true} />),108 ).not.toThrow();109 expect(innerFuncCalled).toBe(true);110 expect(outerFuncCalled).toBe(true);111 });...

Full Screen

Full Screen

RootRef.js

Source:RootRef.js Github

copy

Full Screen

1import * as React from 'react';2import * as ReactDOM from 'react-dom';3import PropTypes from 'prop-types';4import { exactProp, refType } from '@material-ui/utils';5import setRef from '../utils/setRef';6let warnedOnce = false;7/**8 * ⚠️⚠️⚠️9 * If you want the DOM element of a Material-UI component check out10 * [FAQ: How can I access the DOM element?](/getting-started/faq/#how-can-i-access-the-dom-element)11 * first.12 *13 * This component uses `findDOMNode` which is deprecated in React.StrictMode.14 *15 * Helper component to allow attaching a ref to a16 * wrapped element to access the underlying DOM element.17 *18 * It's highly inspired by https://github.com/facebook/react/issues/11401#issuecomment-340543801.19 * For example:20 * ```jsx21 * import React from 'react';22 * import RootRef from '@material-ui/core/RootRef';23 *24 * function MyComponent() {25 * const domRef = React.useRef();26 *27 * React.useEffect(() => {28 * console.log(domRef.current); // DOM node29 * }, []);30 *31 * return (32 * <RootRef rootRef={domRef}>33 * <SomeChildComponent />34 * </RootRef>35 * );36 * }37 * ```38 *39 * @deprecated40 */41class RootRef extends React.Component {42 componentDidMount() {43 this.ref = ReactDOM.findDOMNode(this);44 setRef(this.props.rootRef, this.ref);45 }46 componentDidUpdate(prevProps) {47 const ref = ReactDOM.findDOMNode(this);48 if (prevProps.rootRef !== this.props.rootRef || this.ref !== ref) {49 if (prevProps.rootRef !== this.props.rootRef) {50 setRef(prevProps.rootRef, null);51 }52 this.ref = ref;53 setRef(this.props.rootRef, this.ref);54 }55 }56 componentWillUnmount() {57 this.ref = null;58 setRef(this.props.rootRef, null);59 }60 render() {61 if (process.env.NODE_ENV !== 'production') {62 if (!warnedOnce) {63 warnedOnce = true;64 console.warn(['Material-UI: The RootRef component is deprecated.', 'The component relies on the ReactDOM.findDOMNode API which is deprecated in React.StrictMode.', 'Instead, you can get a reference to the underlying DOM node of the components via the `ref` prop.'].join('/n'));65 }66 }67 return this.props.children;68 }69}70process.env.NODE_ENV !== "production" ? RootRef.propTypes = {71 /**72 * The wrapped element.73 */74 children: PropTypes.element.isRequired,75 /**76 * A ref that points to the first DOM node of the wrapped element.77 */78 rootRef: refType.isRequired79} : void 0;80if (process.env.NODE_ENV !== 'production') {81 process.env.NODE_ENV !== "production" ? RootRef.propTypes = exactProp(RootRef.propTypes) : void 0;82}...

Full Screen

Full Screen

ReactRef.js

Source:ReactRef.js Github

copy

Full Screen

...10var ReactOwner = require('./ReactOwner');11var ReactRef = {};12function attachRef(ref, component, owner) {13 if (typeof ref === 'function') {14 ref(component.getPublicInstance());15 } else {16 // Legacy ref17 ReactOwner.addComponentAsRefTo(component, ref, owner);18 }19}20function detachRef(ref, component, owner) {21 if (typeof ref === 'function') {22 ref(null);23 } else {24 // Legacy ref25 ReactOwner.removeComponentAsRefFrom(component, ref, owner);26 }27}28ReactRef.attachRefs = function (instance, element) {29 if (element === null || typeof element !== 'object') {30 return;31 }32 var ref = element.ref;33 if (ref != null) {34 attachRef(ref, instance, element._owner);35 }36};...

Full Screen

Full Screen

setAndForwardRef.js

Source:setAndForwardRef.js Github

copy

Full Screen

1/**2 * Copyright (c) Facebook, Inc. and its affiliates.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 *7 * @format8 * @flow9 */10'use strict';11import type {ElementRef, Ref} from 'react';12type Args = $ReadOnly<{|13 getForwardedRef: () => ?Ref<any>,14 setLocalRef: (ref: ElementRef<any>) => mixed,15|}>;16/**17 * This is a helper function for when a component needs to be able to forward a ref18 * to a child component, but still needs to have access to that component as part of19 * its implementation.20 *21 * Its main use case is in wrappers for native components.22 *23 * Usage:24 *25 * class MyView extends React.Component {26 * _nativeRef = null;27 *28 * _setNativeRef = setAndForwardRef({29 * getForwardedRef: () => this.props.forwardedRef,30 * setLocalRef: ref => {31 * this._nativeRef = ref;32 * },33 * });34 *35 * render() {36 * return <View ref={this._setNativeRef} />;37 * }38 * }39 *40 * const MyViewWithRef = React.forwardRef((props, ref) => (41 * <MyView {...props} forwardedRef={ref} />42 * ));43 *44 * module.exports = MyViewWithRef;45 */46function setAndForwardRef({47 getForwardedRef,48 setLocalRef,49}: Args): (ref: ElementRef<any>) => void {50 return function forwardRef(ref: ElementRef<any>) {51 const forwardedRef = getForwardedRef();52 setLocalRef(ref);53 // Forward to user ref prop (if one has been specified)54 if (typeof forwardedRef === 'function') {55 // Handle function-based refs. String-based refs are handled as functions.56 forwardedRef(ref);57 } else if (typeof forwardedRef === 'object' && forwardedRef != null) {58 // Handle createRef-based refs59 forwardedRef.current = ref;60 }61 };62}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { action } from '@storybook/addon-actions';4import { linkTo } from '@storybook/addon-links';5import { Button, Welcome } from '@storybook/react/demo';6storiesOf('Welcome', module).add('to Storybook', () => <Welcome showApp={linkTo('Button')} />);7storiesOf('Button', module)8 .add('with text', () => (9 <Button onClick={action('clicked')}>Hello Button</Button>10 .add('with some emoji', () => (11 <Button onClick={action('clicked')}><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>12 ));13storiesOf('Button', module)14 .add('with text', () => (15 <Button onClick={action('clicked')}>Hello Button</Button>16 .add('with some emoji', () => (17 <Button onClick={action('clicked')}><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>18 ));19storiesOf('Button', module)20 .add('with text', () => (21 <Button onClick={action('clicked')}>Hello Button</Button>22 .add('with some emoji', () => (23 <Button onClick={action('clicked')}><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>24 ));25storiesOf('Button', module)26 .add('with text', () => (27 <Button onClick={action('clicked')}>Hello Button</Button>28 .add('with some emoji', () => (29 <Button onClick={action('clicked')}><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>30 ));31storiesOf('Button', module)32 .add('with text', () => (33 <Button onClick={action('clicked')}>Hello Button</Button>34 .add('with some emoji', () => (35 <Button onClick={action('clicked')}><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>36 ));37storiesOf('Button', module)38 .add('with text', () =>

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { action } from '@storybook/addon-actions';4import { linkTo } from '@storybook/addon-links';5import { withInfo } from '@storybook/addon-info';6import Button from './Button';7import Welcome from './Welcome';8storiesOf('Welcome', module).add('to Storybook', () => <Welcome showApp={linkTo('Button')} />);9storiesOf('Button', module)10 .add('with text', () => (11 <Button onClick={action('clicked')}>Hello Button</Button>12 .add('with some emoji', () => (13 <Button onClick={action('clicked')}>😀 😎 👍 💯</Button>14 .add('with some emoji and info', withInfo('This is a cool button')(() => (15 <Button onClick={action('clicked')}>😀 😎 👍 💯</Button>16 .add('with some emoji and info and ref', withInfo('This is a cool button')(() => (17 <Button onClick={action('clicked')} ref={ref => console.log(ref)}>😀 😎 👍 💯</Button>18 )));19import React from 'react';20import PropTypes from 'prop-types';21const Button = ({ onClick, children }) => (22 <button onClick={onClick} type="button">23 {children}24);25Button.propTypes = {26};27export default Button;28import React from 'react';29import PropTypes from 'prop-types';30const Welcome = ({ showApp }) => (31 <button onClick={showApp}>Show App</button>32);33Welcome.propTypes = {34};35export default Welcome;36html, body {37 height: 100%;38 font-family: 'Source Sans Pro', sans-serif;39 font-size: 14px;

Full Screen

Using AI Code Generation

copy

Full Screen

1import { storybookRoot } from 'storybook-root';2storybookRoot('storybook');3import { storybookRoot } from 'storybook-root';4storybookRoot('storybook');5import { storybookRoot } from 'storybook-root';6storybookRoot('storybook');7import { storybookRoot } from 'storybook-root';8storybookRoot('storybook');9import { storybookRoot } from 'storybook-root';10storybookRoot('storybook');11import { storybookRoot } from 'storybook-root';12storybookRoot('storybook');13import { storybookRoot } from 'storybook-root';14storybookRoot('storybook');15import { storybookRoot } from 'storybook-root';16storybookRoot('storybook');17import { storybookRoot } from 'storybook-root';18storybookRoot('storybook');19import { storybookRoot } from 'storybook-root';20storybookRoot('storybook');21import { storybookRoot } from 'storybook-root';22storybookRoot('storybook');23import { storybookRoot } from 'storybook-root';24storybookRoot('storybook');25import { storybookRoot } from 'storybook-root';26storybookRoot('storybook');27import { storybookRoot } from 'storybook-root';28storybookRoot('storybook');29import { storybookRoot } from 'storybook-root';30storybookRoot('storybook');31import { storybookRoot } from 'storybook-root';32storybookRoot('storybook');33import { storybookRoot } from 'storybook-root';34storybookRoot('storybook');

Full Screen

Using AI Code Generation

copy

Full Screen

1import { ref } from 'storybook-root';2ref('someComponent', { prop: 'value' });3import { ref } from 'storybook-react';4ref('someComponent', { prop: 'value' });5import { ref } from 'storybook-vue';6ref('someComponent', { prop: 'value' });7import { ref } from 'storybook-angular';8ref('someComponent', { prop: 'value' });9import { ref } from 'storybook-html';10ref('someComponent', { prop: 'value' });11import { ref } from 'storybook-svelte';12ref('someComponent', { prop: 'value' });13import { ref } from 'storybook-web-components';14ref('someComponent', { prop: 'value' });15import { ref } from 'storybook-preact';16ref('someComponent', { prop: 'value' });17import { ref } from 'storybook-riot';18ref('someComponent', { prop: 'value' });19import { ref } from 'storybook-aurelia';20ref('someComponent', { prop: 'value' });21import { ref } from 'storybook-marko';22ref('someComponent', { prop: 'value' });23import { ref } from 'storybook-ember';24ref('someComponent', { prop: 'value' });25import { ref } from 'storybook-inferno';26ref('someComponent', { prop: 'value' });27import { ref } from 'storybook-mithril';28ref('someComponent', { prop: 'value' });29import { ref } from 'storybook-blaze';30ref('someComponent', { prop: 'value' });

Full Screen

Using AI Code Generation

copy

Full Screen

1const ref = useRef();2const { storybookRoot } = useStorybookRoot();3const { storybookRoot } = useStorybookRoot(ref);4const { storybookRoot } = useStorybookRoot();5const { storybook } = useStorybook();6const { storybookIframe } = useStorybookIframe();7const { storybookIframeDoc } = useStorybookIframeDoc();8const { storybookIframeHead } = useStorybookIframeHead();9const { storybookIframeBody } = useStorybookIframeBody();

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful