react#Component JavaScript Examples

The following examples show how to use react#Component. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PrivateRoute.js    From Merch-Dropper-fe with MIT License 6 votes vote down vote up
PrivateRoute = ({component: Component, ...rest})=>{
    return (
        <Route {...rest} render={props => {
            if (localStorage.getItem('token')){
                return <Component {...props} />
            } else {
                return <Redirect exact path='/redirect' />
            }
        }} />
    )
}
Example #2
Source File: create-theme-listener.test.js    From cybsec with GNU Affero General Public License v3.0 6 votes vote down vote up
getTrap = themeListener => {
  return class ThemeListenerTrap extends Component {
    static propTypes = {
      intercept: PropTypes.func.isRequired,
    };
    static contextTypes = themeListener.contextTypes;
    constructor(props, context) {
      super(props, context);
      this.props.intercept(themeListener.initial(context))
    }
    componentDidMount() {
      this.unsubscribe = themeListener.subscribe(this.context, this.props.intercept)
    }
    componentWillUnmount() {
      if (typeof this.unsubscribe === 'function') {
        this.unsubscribe()
      }
    }
    // eslint-disable-next-line
    render() {
      return <div />;
    }
  };
}
Example #3
Source File: withErrorHandler.js    From ReactJS-Projects with MIT License 6 votes vote down vote up
withErrorHandler = ( WrappedComponent, axios ) => {
    return class extends Component {
        state = {
            error: null
        }

        componentWillMount () {
            this.reqInterceptor = axios.interceptors.request.use( req => {
                this.setState( { error: null } );
                return req;
            } );
            this.resInterceptor = axios.interceptors.response.use( res => res, error => {
                this.setState( { error: error } );
            } );
        }

        componentWillUnmount () {
            axios.interceptors.request.eject( this.reqInterceptor );
            axios.interceptors.response.eject( this.resInterceptor );
        }

        errorConfirmedHandler = () => {
            this.setState( { error: null } );
        }

        render () {
            return (
                <Aux>
                    <Modal
                        show={this.state.error}
                        modalClosed={this.errorConfirmedHandler}>
                        {this.state.error ? this.state.error.message : null}
                    </Modal>
                    <WrappedComponent {...this.props} />
                </Aux>
            );
        }
    }
}
Example #4
Source File: withTheme.js    From frontend-course with MIT License 6 votes vote down vote up
withTheme = (WrappedComponent) => {
  
  return class extends Component {

    static contextType = ThemeContext;

    render () {
      return (
        <WrappedComponent
          theme={themes[this.context]}
          test={42}
        />
      )
    }
  }
}
Example #5
Source File: PrivateRoute.js    From Full-Stack-React-Projects-Second-Edition with MIT License 6 votes vote down vote up
PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    auth.isAuthenticated() ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/signin',
        state: { from: props.location }
      }}/>
    )
  )}/>
)
Example #6
Source File: flexbox.js    From react-custom-scrollbars-2 with MIT License 6 votes vote down vote up
export default function createTests() {
    let node;
    beforeEach(() => {
        node = document.createElement('div');
        document.body.appendChild(node);
    });
    afterEach(() => {
        unmountComponentAtNode(node);
        document.body.removeChild(node);
    });
    describe('when scrollbars are in flexbox environment', () => {
        it('should still work', done => {
            class Root extends Component {
                render() {
                    return (
                        <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, display: 'flex', flexDirection: 'column' }}>
                            <Scrollbars ref={(ref) => { this.scrollbars = ref; }}>
                                <div style={{ width: 10000, height: 10000 }}/>
                            </Scrollbars>
                        </div>
                    );
                }
            }
            render(<Root/>, node, function callback() {
                setTimeout(() => {
                    const { scrollbars } = this;
                    const $scrollbars = findDOMNode(scrollbars);
                    const $view = scrollbars.view;
                    expect($scrollbars.clientHeight).toBeGreaterThan(0);
                    expect($view.clientHeight).toBeGreaterThan(0);
                    done();
                }, 100);
            });
        });
    });
}
Example #7
Source File: App.js    From FRCScout2020 with MIT License 6 votes vote down vote up
ProtectedRoute = ({ component: Component, ...rest }) => {
  const authContext = useContext(AuthContext);

  return (
    <Route
      {...rest}
      render={props =>
        authContext.isLoggedIn === true ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: '/login',
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );
}
Example #8
Source File: App.js    From AzureEats-Website with MIT License 6 votes vote down vote up
render() {
        const { quantity } = this.state;

        const PrivateRoute = ({ component: Component, ...rest }) => (
            <Route {...rest} render={(props) => (
                this.props.userInfo.loggedIn === true
                    ? <Component {...props} {...rest} />
                    : <Redirect to='/' />
            )} />
        )

        return (
            <div className="App">
                <Router history={history}>
                    <Fragment>
                        <DebugHeader />
                        <Header quantity={quantity} />
                        <Route exact path="/" component={Home} />
                        <Route exact path="/list" component={List} />
                        <Route exact path="/list/:code" component={List} />
                        <Route path="/suggested-products-list" component={SuggestedProductsList} />
                        <Route path="/product/detail/:productId" render={(props) => <Detail sumProductInState={this.sumProductInState} {...props} />} />
                        <PrivateRoute path='/coupons' component={MyCoupons} />
                        <PrivateRoute path='/profile' component={Profile} />
                        <PrivateRoute path='/shopping-cart' component={ShoppingCart} ShoppingCart={this.ShoppingCart} quantity={this.state.quantity} />
                        <Footer />
                    </Fragment>
                </Router>
            </div>
        );
    }
Example #9
Source File: InfiniteScroll.js    From VTour with MIT License 6 votes vote down vote up
Ref =
/*#__PURE__*/
function (_Component) {
  _inheritsLoose(Ref, _Component);

  function Ref() {
    return _Component.apply(this, arguments) || this;
  }

  var _proto = Ref.prototype;

  _proto.render = function render() {
    var children = this.props.children;
    return children;
  };

  return Ref;
}(Component)
Example #10
Source File: asyncComponent.js    From surveillance-forms with MIT License 6 votes vote down vote up
ComponentType<Props> {
  class AsyncComponent extends Component<Props, State> {
    constructor(props: Props) {
      super(props);

      this.state = {
        component: null
      };
    }

    componentDidMount() {
      this.fetchComponent();
    }

    async fetchComponent() {
      const { default: component } = await loadComponent();

      this.setState({ component });
    }

    render() {
      const C = this.state.component;

      return C ? <C {...this.props} /> : null;
    }
  }
Example #11
Source File: AdminRoute.jsx    From Blockchain-based-Certificate-Authentication-System with GNU General Public License v3.0 6 votes vote down vote up
AdminRoute = ({ component: Component, ...rest }) => (
    <Route
        {...rest}
        render={props =>
            isAuth() && isAuth().role === 'admin' ? (
                <Component {...props} />
            ) : (
                <Redirect
                    to={{
                        pathname: '/signin',
                        state: { from: props.location }
                    }}
                />
            )
        }
    ></Route>
)
Example #12
Source File: AdminRoute.js    From mern-ecommerce with MIT License 6 votes vote down vote up
AdminRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={(props) =>
      isAuthenticated() && isAuthenticated().user.role === 1 ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: '/signin',
            state: { from: props.location },
          }}
        />
      )
    }
  />
)
Example #13
Source File: App.js    From Lambda with MIT License 6 votes vote down vote up
componentDidMount() {
    const { error, feature } = this.props;

    if (error) {
      this.handleError(error);
      return;
    }

    // Class components must call this.props.onReady when they're ready for the test.
    // We will assume functional components are ready immediately after mounting.
    if (!Component.isPrototypeOf(feature)) {
      this.handleReady();
    }
  }
Example #14
Source File: MessageInput.jsx    From chat-ui-kit-react with MIT License 6 votes vote down vote up
// Because container depends on fancyScroll
// it must be wrapped in additional container
function editorContainer() {
  class Container extends Component {
    render() {
      const {
        props: { fancyScroll, children, forwardedRef, ...rest },
      } = this;

      return (
        <>
          {fancyScroll === true && (
            <PerfectScrollbar
              ref={(elRef) => (forwardedRef.current = elRef)}
              {...rest}
              options={{ suppressScrollX: true }}
            >
              {children}
            </PerfectScrollbar>
          )}
          {fancyScroll === false && (
            <div ref={forwardedRef} {...rest}>
              {children}
            </div>
          )}
        </>
      );
    }
  }

  return React.forwardRef((props, ref) => {
    return <Container forwardedRef={ref} {...props} />;
  });
}
Example #15
Source File: Nav.react.js    From spring-boot-ecommerce with Apache License 2.0 6 votes vote down vote up
Nav = function (_Component) {
  _inherits(Nav, _Component);

  function Nav() {
    _classCallCheck(this, Nav);

    return _possibleConstructorReturn(this, _Component.apply(this, arguments));
  }

  Nav.prototype.render = function render() {
    var props = this.props;

    return React.createElement('div', props);
  };

  return Nav;
}(Component)
Example #16
Source File: StatelessSelect.js    From Nemesis with GNU General Public License v3.0 6 votes vote down vote up
StatelessSelect = class extends Component {
  render() {
    return (
      <FCConfigContext.Consumer>
        {config => {
          let item = config[this.props.id];
          this.props.onUpdate && this.props.onUpdate(item);
          return (
            <HelperSelect
              style={item && item.style}
              id={item.id}
              className={item.id}
              key={item.id}
              label={item.id}
              value={item.current}
              disabled={!!item.isDirty}
              onUpdate={this.props.onUpdate}
              name_type={this.props.name_type}
              onChange={event => {
                let payload = event.target.value;
                let isDirty = item.current !== payload;
                if (isDirty) {
                  item.current = payload;
                  this.props.notifyDirty(isDirty, item, payload);
                  this.setState({ current: payload, isDirty: isDirty });
                  FCConnector.setValue(item.id, payload).then(() => {
                    this.setState({ isDirty: false });
                  });
                }
              }}
              items={item.values}
            />
          );
        }}
      </FCConfigContext.Consumer>
    );
  }
}
Example #17
Source File: withMeta.js    From light-blue-react-template with MIT License 6 votes vote down vote up
function withMeta(ComposedComponent) {
  class WithMeta extends Component {
    componentWillMount() {
      if (ComposedComponent.meta) {
        Object.keys(ComposedComponent.meta).forEach((metaKey) => {
          if (metaKey === 'title') {
            document.title = `${ComposedComponent.meta[metaKey]} - ${defaultMeta[metaKey]}`;
            return;
          }
          updateMeta(metaKey, ComposedComponent.meta[metaKey]);
        });
      }
    }

    componentWillUnmount() {
      Object.keys(defaultMeta).forEach((metaKey) => {
        if (metaKey === 'title') {
          document.title = defaultMeta[metaKey];
          return;
        }
        updateMeta(metaKey, defaultMeta[metaKey]);
      });
    }

    render() {
      return <ComposedComponent {...this.props} />;
    }
  }

  WithMeta.ComposedComponent = ComposedComponent;
  return hoistStatics(WithMeta, ComposedComponent);
}
Example #18
Source File: create-hoc.jsx    From mixbox with GNU General Public License v3.0 6 votes vote down vote up
createAjaxHoc = sxAjax => ({propName = 'ajax'} = {}) => WrappedComponent => {
    class WithAjax extends Component {
        constructor(props) {
            super(props);
            this._$ajax = {};
            this._$ajaxTokens = [];
            const methods = ['get', 'post', 'put', 'patch', 'del', 'singleGet'];

            for (let method of methods) {
                this._$ajax[method] = (...args) => {
                    const ajaxToken = sxAjax[method](...args);
                    this._$ajaxTokens.push(ajaxToken);
                    return ajaxToken;
                };
            }
        }

        static displayName = `WithAjax(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;

        componentWillUnmount() {
            this._$ajaxTokens.forEach(item => item.cancel());
        }

        render() {
            const injectProps = {
                [propName]: this._$ajax,
            };
            return <WrappedComponent {...injectProps} {...this.props}/>;
        }
    }

    return WithAjax;
}
Example #19
Source File: AsyncComponent.js    From discern with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
export default function asyncComponent(importComponent) {
  class AsyncComponent extends Component {
    constructor(props) {
      super(props)

      this.state = {
        component: null
      }
    }

    async componentDidMount() {
      const {default: component} = await importComponent()

      this.setState({
        component: component
      })
    }

    render() {
      const C = this.state.component

      return C ? <C {...this.props} /> : null
    }
  }

  return AsyncComponent
}
Example #20
Source File: UncontrolledAlert.js    From Rick-and-Morty-React-App-Card-API with MIT License 6 votes vote down vote up
UncontrolledAlert =
/*#__PURE__*/
function (_Component) {
  _inheritsLoose(UncontrolledAlert, _Component);

  function UncontrolledAlert(props) {
    var _this;

    _this = _Component.call(this, props) || this;
    _this.state = {
      isOpen: true
    };
    _this.toggle = _this.toggle.bind(_assertThisInitialized(_this));
    return _this;
  }

  var _proto = UncontrolledAlert.prototype;

  _proto.toggle = function toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  };

  _proto.render = function render() {
    return React.createElement(Alert, _extends({
      isOpen: this.state.isOpen,
      toggle: this.toggle
    }, this.props));
  };

  return UncontrolledAlert;
}(Component)
Example #21
Source File: create-theme-provider.test.js    From cybsec with GNU Affero General Public License v3.0 5 votes vote down vote up
test(`createThemeProvider's result instance type`, t => {
  const ThemeProvider = createThemeProvider();
  const actual = Component.isPrototypeOf(ThemeProvider);
  t.true(actual, `createThemeProvider() should be a React Component`);
});
Example #22
Source File: BorderedTable.js    From Designer-Client with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param {{container: Component, size: number, headers: string[], rows: Object[]}} props
 */
export default function BorderedTable({ container, size, headers, rows }) {
  const classes = useStyles();

  return (
    <TableContainer component={container}>
      <Table size={size}>
        {headers && (
          <TableHead>
            <TableRow>
              {headers.map((header) => {
                return (
                  <TableCell key={`table-header-cell-${header}`} className={classes.borderedCell}>
                    {header}
                  </TableCell>
                );
              })}
            </TableRow>
          </TableHead>
        )}

        <TableBody>
          {rows.map((row) => {
            return (
              <TableRow key={`table-row-${row[0]}`}>
                {row.map((col) => {
                  return (
                    <TableCell className={classes.borderedCell} key={`table-cell-${col}`}>
                      {col}
                    </TableCell>
                  );
                })}
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
    </TableContainer>
  );
}
Example #23
Source File: frontauth.js    From React-Messenger-App with MIT License 5 votes vote down vote up
export default function withAuths(ComponentToProtect) {
  return class extends Component {
    constructor() {
      super();
      this.state = {
        loading: true,
        redirect: false
      };
    }
    componentDidMount() {
      fetch("/api/checkToken")
        .then(res => {
          if (res.status === 200) {
            this.setState({ loading: false });
          } else {
            const error = new Error(res.error);
            throw error;
          }
        })
        .catch(err => {
          console.error(err);
          this.setState({ loading: false, redirect: true });
        });
    }
    render() {
      const { loading, redirect } = this.state;
      if (loading) {
        return null;
      }
      if (redirect) {
        return <Redirect to="/api/signin" />;
      }
      return (
        <React.Fragment>
          <ComponentToProtect />
        </React.Fragment>
      );
    }
  };
}
Example #24
Source File: Dashboard.js    From ehr with GNU Affero General Public License v3.0 5 votes vote down vote up
getWidgets() {
        const widgets = [];

        // Get widget modules from plugins
        PluginManager.plugins.forEach(plugin => {
            const { path, modules } = plugin;
            const widgetModule = modules[ModuleTypeEnum.WidgetModule];
            if (!widgetModule) {
                return;
            }
            widgets.push({
                path,
                ...widgetModule,
            });
        });

        // Sort by priority (high priority comes first)
        widgets.sort((i1, i2) => (i1.priority < i2.priority ? 1 : -1));

        return widgets.map((widget, index) => {
            const { Component: WidgetComponent, name, icon, path } = widget;

            // Render a widget with custom component
            if (WidgetComponent) {
                return (
                    <Grid key={index} item>
                        <DashboardWidget>
                            <WidgetComponent key={index} />
                        </DashboardWidget>
                    </Grid>
                );
            }

            // Render a widget with name and icon redirecting user to a page
            return (
                <Grid key={index} item>
                    <DashboardWidget onClick={() => this.onRedirectWidgetClick(path)} icon={icon} name={name} />
                </Grid>
            );
        });
    }
Example #25
Source File: App.js    From gnosis-safe-delegate-dapp with MIT License 5 votes vote down vote up
function withUseWeb3React(Component) {
    return function WrappedComponent(props) {
        const values = useWeb3React();
        return <Component {...props} web3ReactHookValue={values} />;
    }
}
Example #26
Source File: SocketConnect.js    From flatris-LAB_V1 with MIT License 5 votes vote down vote up
export function withSocket(
  CompType: ComponentType<*>,
  syncActions: {
    [propName: string]: (...args: any) => JoinGameAction | ThunkAction
  } = {}
) {
  class SocketConnect extends Component<Props> {
    static displayName = `SocketConnect(${CompType.displayName ||
      CompType.name ||
      'UnnamedComponent'})`;

    static contextTypes = {
      subscribe: func.isRequired,
      keepGameAlive: func.isRequired,
      broadcastGameAction: func.isRequired,
      onGameKeepAlive: func.isRequired,
      offGameKeepAlive: func.isRequired
    };

    createActionHandler = (actionName: string) => async (...args: any) => {
      const { broadcastGameAction } = this.context;
      const actionCreator = syncActions[actionName];

      // NOTE: This must only run on the client!
      return broadcastGameAction(actionCreator(...args));
    };

    getBoundHandlers() {
      return Object.keys(syncActions).reduce((acc, actionName) => {
        return {
          ...acc,
          [actionName]: this.createActionHandler(actionName)
        };
      }, {});
    }

    render() {
      return (
        <CompType
          {...this.props}
          {...this.context}
          {...this.getBoundHandlers()}
        />
      );
    }
  }

  return SocketConnect;
}
Example #27
Source File: Digital.js    From VTour with MIT License 5 votes vote down vote up
Digit =
/*#__PURE__*/
function (_Component) {
  _inheritsLoose(Digit, _Component);

  function Digit() {
    var _this;

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _Component.call.apply(_Component, [this].concat(args)) || this;

    _defineProperty(_assertThisInitialized(_this), "state", {});

    return _this;
  }

  Digit.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
    var number = nextProps.number;

    if (number !== prevState.number) {
      return {
        previous: prevState.number,
        number: number
      };
    }

    return null;
  };

  var _proto = Digit.prototype;

  _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
    var _this2 = this;

    var previous = this.state.previous;

    if (prevState.previous === undefined && previous !== undefined) {
      clearTimeout(this.timer);
      this.timer = setTimeout(function () {
        _this2.setState({
          previous: undefined
        });
      }, 900);
    }
  };

  _proto.componentWillUnmount = function componentWillUnmount() {
    clearTimeout(this.timer);
  };

  _proto.render = function render() {
    /* eslint-disable-next-line react/prop-types */
    var _this$props = this.props,
        run = _this$props.run,
        size = _this$props.size;
    var _this$state = this.state,
        number = _this$state.number,
        previous = _this$state.previous;

    if (previous !== undefined) {
      var direction = run === 'backward' ? 'down' : 'up';
      return React.createElement(StyledDigitalDigit, {
        size: size
      }, React.createElement(StyledDigitalPrevious, {
        direction: direction
      }, Math.floor(previous)), React.createElement(StyledDigitalNext, {
        direction: direction
      }, Math.floor(number)));
    }

    return React.createElement(StyledDigitalDigit, {
      size: size
    }, Math.floor(number));
  };

  return Digit;
}(Component)
Example #28
Source File: Confirm.js    From smart-contracts with MIT License 5 votes vote down vote up
Confirm = /*#__PURE__*/function (_Component) {
  _inheritsLoose(Confirm, _Component);

  function Confirm() {
    var _this;

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _Component.call.apply(_Component, [this].concat(args)) || this;

    _this.handleCancel = function (e) {
      _invoke(_this.props, 'onCancel', e, _this.props);
    };

    _this.handleCancelOverrides = function (predefinedProps) {
      return {
        onClick: function onClick(e, buttonProps) {
          _invoke(predefinedProps, 'onClick', e, buttonProps);

          _this.handleCancel(e);
        }
      };
    };

    _this.handleConfirmOverrides = function (predefinedProps) {
      return {
        onClick: function onClick(e, buttonProps) {
          _invoke(predefinedProps, 'onClick', e, buttonProps);

          _invoke(_this.props, 'onConfirm', e, _this.props);
        }
      };
    };

    return _this;
  }

  var _proto = Confirm.prototype;

  _proto.render = function render() {
    var _this$props = this.props,
        cancelButton = _this$props.cancelButton,
        confirmButton = _this$props.confirmButton,
        content = _this$props.content,
        header = _this$props.header,
        open = _this$props.open,
        size = _this$props.size;
    var rest = getUnhandledProps(Confirm, this.props); // `open` is auto controlled by the Modal
    // It cannot be present (even undefined) with `defaultOpen`
    // only apply it if the user provided an open prop

    var openProp = {};
    if (_has(this.props, 'open')) openProp.open = open;
    return /*#__PURE__*/React.createElement(Modal, _extends({}, rest, openProp, {
      size: size,
      onClose: this.handleCancel
    }), Modal.Header.create(header, {
      autoGenerateKey: false
    }), Modal.Content.create(content, {
      autoGenerateKey: false
    }), /*#__PURE__*/React.createElement(Modal.Actions, null, Button.create(cancelButton, {
      autoGenerateKey: false,
      overrideProps: this.handleCancelOverrides
    }), Button.create(confirmButton, {
      autoGenerateKey: false,
      defaultProps: {
        primary: true
      },
      overrideProps: this.handleConfirmOverrides
    })));
  };

  return Confirm;
}(Component)
Example #29
Source File: App.js    From Lambda with MIT License 5 votes vote down vote up
checkAuthenticated(component, path) {
    const Component = component;
    return this.props.isAuthenticated ? (
      <Redirect to="/dashboard" />
    ) : (
      <Component to={path} />
    );
  }