react#PureComponent TypeScript Examples

The following examples show how to use react#PureComponent. 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: index.tsx    From hive with MIT License 6 votes vote down vote up
class Carousel extends PureComponent<Props> {
    render() {
        const { children } = this.props;

        return (
            <div className={styles.wrap}>
                {React.Children.map(children, (child, i) => {
                    if (
                        !child ||
                        typeof child === 'string' ||
                        typeof child === 'number' ||
                        typeof child === 'boolean'
                    )
                        return child;
                    return React.cloneElement(child as any, { index: i });
                })}
            </div>
        );
    }
}
Example #2
Source File: BestArtistsBar.tsx    From your_spotify with GNU General Public License v3.0 6 votes vote down vote up
class ImageAxisTick extends PureComponent<{
  x: number;
  y: number;
  payload: {
    index: number;
  };
  artists: Artist[];
}> {
  render() {
    const { x, y, payload, artists } = this.props;

    const artist = artists[payload.index];

    if (!artist) {
      return null;
    }

    return (
      <Link to={`/artist/${artist.id}`}>
        <Tooltip title={artist.name}>
          <g transform={`translate(${x - svgImgSize / 2},${y})`}>
            <clipPath id="yoyo">
              <circle r={svgImgSize / 2} cx={svgImgSize / 2} cy={svgImgSize / 2} />
            </clipPath>
            <image
              width={svgImgSize}
              height={svgImgSize}
              href={getImage(artist)}
              clipPath="url(#yoyo)"
            />
          </g>
        </Tooltip>
      </Link>
    );
  }
}
Example #3
Source File: Identicon.tsx    From celo-web-wallet with MIT License 6 votes vote down vote up
export class Identicon extends PureComponent<Props> {
  render() {
    const { address, size: _size, styles } = this.props
    const size = _size ?? 34

    if (!isValidAddress(address)) return null

    const jazziconResult = jazzicon(size, addressToSeed(address))

    return (
      <div
        css={{ height: size, ...styles }}
        ref={(nodeElement) => {
          if (nodeElement) {
            nodeElement.innerHTML = ''
            nodeElement.appendChild(jazziconResult)
          }
        }}
      ></div>
    )
  }
}
Example #4
Source File: ExamplePage1.tsx    From grafana-starter-app with Apache License 2.0 6 votes vote down vote up
export class ExamplePage1 extends PureComponent<Props> {
  constructor(props: Props) {
    super(props);
  }

  render() {
    const { query } = this.props;

    return (
      <div>
        11111111111111111111111111111111
        <pre>{JSON.stringify(query)}</pre>
        11111111111111111111111111111111
      </div>
    );
  }
}
Example #5
Source File: Component.tsx    From react-bmapgl with MIT License 6 votes vote down vote up
export default class Component<P = {}, S = {}, SS = any> extends PureComponent<P, S, SS> {

    registeredEvents?: any;
    map: BMapGL.Map;
    instance: MapInstance;
    options: Options = [];

    getMap() {
        // @ts-ignore
        return this.props.map || this.context.map;
    }

    getInstance(component: Component): MapInstance {
        return component.instance;
    }

    getOptions(props: P = this.props): InstanceOptions {
        let options = {};
        this.options.map((key: string) => {
            if (props[key] !== undefined) {
                options[key] = props[key];
            }
        });
        return options;
    }

}
Example #6
Source File: Todo.tsx    From icejs with MIT License 6 votes vote down vote up
class Todo extends PureComponent {
  componentDidMount() {
    throw new Error('test error boundary');
  }

  render() {
    return (
      <div>
        TODO Component
      </div>
    );
  }
}
Example #7
Source File: autoHide.tsx    From jetlinks-ui-antd with MIT License 6 votes vote down vote up
export default class AutoHide extends PureComponent {
  static propTypes = {
    title: PropTypes.any,
    style: PropTypes.any,
  };

  render() {
    const { title, style } = this.props;
    return (
      <Tooltip placement="topLeft" title={title} style={{ lineHeight: 17 }}>
        <span className={Styles.col} style={style}>
          {title}
        </span>
      </Tooltip>
    );
  }
}
Example #8
Source File: ErrorBoundary.tsx    From mitojs with MIT License 6 votes vote down vote up
class ErrorBoundaryWrapped extends PureComponent<ErrorBoundaryProps, ErrorBoundaryState> {
  readonly state: ErrorBoundaryState
  constructor(props: any) {
    super(props)
    this.state = {
      hasError: false
    }
  }
  componentDidCatch(error: Error, { componentStack }: ErrorInfo) {
    // error and componentStack are what we need
    const { onError, MitoInstance } = this.props
    const reactError = extractErrorStack(error, Severity.Normal) as ReportDataType
    reactError.type = ErrorTypes.REACT
    onError?.(error, componentStack)
    // mito handler -> collected react render error
    const breadcrumbStack = MitoInstance?.breadcrumb.push({
      type: BaseBreadcrumbTypes.REACT,
      data: reactError,
      category: BREADCRUMBCATEGORYS.EXCEPTION,
      level: Severity.Error
    })
    MitoInstance?.transport.send(reactError, breadcrumbStack)
    this.setState({
      hasError: true
    })
  }
  render() {
    return (this.state.hasError ? this.props.fallback : this.props.children) ?? null
  }
}
Example #9
Source File: User.tsx    From react-js-tutorial with MIT License 6 votes vote down vote up
class UserComponent extends PureComponent<Props> {
  logout = () => {
    const { logout } = this.props;
    logout();
  };
  render() {
    const { username } = this.props;
    return isEmpty(username) ? (
      <h3>
        Nice to see you! Lets <Link to="/login">login</Link> to the game!
      </h3>
    ) : (
      <div>
        <h3>Hello, {username}!</h3>
        <button onClick={this.logout}>Logout</button>
      </div>
    );
  }
}
Example #10
Source File: ErrorBoundary.tsx    From Riakuto-StartingReact-ja3.1 with Apache License 2.0 6 votes vote down vote up
class ErrorBoundary extends PureComponent<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError = (error: Error): State => ({
    hasError: true,
    error,
  });

  componentDidCatch = (error: Error, info: ErrorInfo): void => {
    console.error(error, info); // eslint-disable-line no-console
  };

  render = (): ReactNode => {
    const { children, statusMessages = {} } = this.props;
    const { hasError, error } = this.state;
    const messages = { ...DEFAULT_MESSAGES, ...statusMessages };

    if (hasError) {
      const statusCode = (error as HTTPError)?.response?.status;

      if (statusCode && Object.keys(messages).includes(String(statusCode))) {
        return <Message warning>{messages[statusCode]}</Message>;
      }

      return <Message error>{messages[0]}</Message>;
    }

    return children;
  };
}
Example #11
Source File: OutsideClick.tsx    From app-stormkit-io with GNU General Public License v3.0 6 votes vote down vote up
class OutsideClick extends PureComponent<Props, any> {
  componentDidMount() {
    document.addEventListener("click", this.handleClick);
  }

  componentWillUnmount() {
    if (typeof document !== "undefined") {
      document.removeEventListener("click", this.handleClick);
    }
  }

  handleClick = (event: any) => {
    const root = ReactDOM.findDOMNode(this);
    const { handler } = this.props;

    if (root && !root.contains(event.target)) {
      handler(event);
    }
  };

  render(): ReactNode {
    return this.props.children;
  }
}
Example #12
Source File: crewstat.tsx    From website with MIT License 6 votes vote down vote up
class CrewStat extends PureComponent<CrewStatProps> {
	render() {
		if (!this.props.data) {
			return <span />;
		}

		const stats = this.props.data;
		const scale = this.props.scale || 1;

		return (
			<div
				style={{
					display: 'inline-grid',
					width: 'max-content',
					gridTemplateColumns: `${2.5 * scale}em auto`,
					gridTemplateAreas: `'icon stats'`,
					gridGap: `${0.2 * scale}em`,
					paddingTop: `${0.2 * scale}em`,
					paddingRight: `${0.4 * scale}em`
				}}>
				<div style={{ gridArea: 'icon' }}>
					<img src={`${process.env.GATSBY_ASSETS_URL}atlas/icon_${this.props.skill_name}.png`} style={{ height: `${2 * scale}em` }} />
				</div>
				<div style={{ gridArea: 'stats' }}>
					<span style={{ fontWeight: 'bolder', fontSize: `${1.5 * scale}em` }}>{stats.core}</span>
					<span style={{ fontWeight: 'normal', fontSize: `${scale}em` }}>
						+({stats.range_min}-{stats.range_max})
					</span>
				</div>
			</div>
		);
	}
}
Example #13
Source File: BigValue.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
export class BigValue extends PureComponent<Props> {
  static defaultProps: Partial<Props> = {
    justifyMode: BigValueJustifyMode.Auto,
  };

  render() {
    const { value, onClick, className } = this.props;

    const layout = buildLayout(this.props);
    const panelStyles = layout.getPanelStyles();
    const valueAndTitleContainerStyles = layout.getValueAndTitleContainerStyles();
    const valueStyles = layout.getValueStyles();
    const titleStyles = layout.getTitleStyles();

    return (
      <div className={className} style={panelStyles} onClick={onClick}>
        <div style={valueAndTitleContainerStyles}>
          {value.title && <div style={titleStyles}>{value.title}</div>}
          <FormattedValueDisplay value={value} style={valueStyles} />
        </div>
        {layout.renderChart()}
      </div>
    );
  }
}
Example #14
Source File: SoundPlayer.tsx    From vscode-sound-player with MIT License 5 votes vote down vote up
export default class SoundPlayer extends PureComponent<Props, State>{

    private audioNode: AudioBufferSourceNode | null = null

    constructor(props: Readonly<Props>) {
        super(props)
        this.state = {
            isPlaying: false
        }
    }

    private onClickStop = () => {
        if (this.audioNode === null) return
        this.audioNode.stop()
        this.onPlayEnded()
    }

    private onClickStart = () => {
        const {
            audioData,
        } = this.props
        const audioContext = GetAudioContext()
        const audioBuffer = GetAudioBuffer(audioData)
        this.audioNode = audioContext.createBufferSource()
        this.audioNode.buffer = audioBuffer
        this.audioNode.addEventListener('ended', this.onPlayEnded)
        this.audioNode.connect(audioContext.destination)
        this.audioNode.start()
        this.setState({ isPlaying: true })
    }

    private onPlayEnded = () => {
        this.audioNode = null
        this.setState({ isPlaying: false })
    }

    render(): ReactElement {
        const {
            isPlaying
        } = this.state
        if (isPlaying) {
            return <button onClick={this.onClickStop}>停止</button>
        } else {
            return <button onClick={this.onClickStart}>播放</button>
        }
    }

}
Example #15
Source File: navigator-item-dnd-container.tsx    From utopia with MIT License 5 votes vote down vote up
export class NavigatorItemDndWrapper extends PureComponent<
  NavigatorItemDragAndDropWrapperProps & CollectResults
> {
  constructor(props: NavigatorItemDragAndDropWrapperProps & CollectResults) {
    super(props)
  }

  getMarginForHint = (): number => {
    if (
      this.props.isOver &&
      this.props.appropriateDropTargetHint?.target != null &&
      this.props.appropriateDropTargetHint?.type !== 'reparent'
    ) {
      return getHintPadding(this.props.appropriateDropTargetHint.target)
    } else {
      return 0
    }
  }

  render(): React.ReactElement {
    const props = this.props

    return (
      <div
        key='navigatorItem'
        id={`navigator-item-${EP.toVarSafeComponentId(this.props.elementPath)}`}
        style={{
          ...props.windowStyle,
        }}
      >
        <NavigatorItem
          elementPath={this.props.elementPath}
          index={this.props.index}
          getSelectedViewsInRange={this.props.getSelectedViewsInRange}
          noOfChildren={this.props.noOfChildren}
          staticElementName={this.props.staticElementName}
          label={this.props.label}
          dispatch={this.props.editorDispatch}
          isHighlighted={this.props.highlighted}
          isElementVisible={this.props.isElementVisible}
          renamingTarget={this.props.renamingTarget}
          collapsed={this.props.collapsed}
          selected={this.props.selected}
          elementOriginType={this.props.elementOriginType}
          elementWarnings={this.props.elementWarnings}
        />
        <NavigatorHintTop
          shouldBeShown={
            this.props.isOver && this.props.appropriateDropTargetHint?.type === 'before'
          }
          getMarginForHint={this.getMarginForHint}
        />
        <NavigatorHintBottom
          shouldBeShown={
            this.props.isOver && this.props.appropriateDropTargetHint?.type === 'after'
          }
          getMarginForHint={this.getMarginForHint}
        />
      </div>
    )
  }
}
Example #16
Source File: deployments-field.tsx    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
export default class extends PureComponent<IVariableInputGroupProps, any> {
  state = {
    value: defaultValue,
  };

  static getDerivedStateFromProps(nextProps: any, prevState: any) {
    if (!isEqual(nextProps.value, prevState.value)) {
      return {
        value: nextProps.value || defaultValue,
      };
    }
    return null;
  }

  triggerChange = (changedValue: any) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(changedValue);
    }
  };

  render() {
    const { disabled } = this.props;
    const { value } = this.state;
    const replicas = (
      <div>
        <span className="edit-service-label">{i18n.t('Number of instances')}: </span>
        <span>
          <InputNumber
            disabled={disabled}
            className="w-full"
            value={value.replicas || 1}
            onChange={(e: any) => this.changeValue(e, 'replicas')}
            placeholder={i18n.t('dop:please enter the number of instance')}
          />
        </span>
      </div>
    );
    return (
      <div>
        <div>
          <span className="edit-service-label">{i18n.t('dop:deployment mode')}: </span>
          <span>
            <Select
              disabled={disabled}
              defaultValue={'replicated'}
              onChange={(e: any) => this.changeValue(e, 'mode')}
              placeholder={i18n.t('dop:please enter the network configuration')}
            >
              <Option value="replicated">replicated</Option>
            </Select>
          </span>
        </div>
        {replicas}
      </div>
    );
  }

  private changeValue = (v: any, key: string) => {
    const { value } = this.state;
    // @ts-ignore
    value[key] = v;
    const state = {
      value: { ...value },
    };
    this.setState(state);
    this.triggerChange(state.value);
  };
}
Example #17
Source File: index.tsx    From portable with Apache License 2.0 5 votes vote down vote up
export class Events extends PureComponent {
    render() {
        return <div>Events</div>
    }
}
Example #18
Source File: Page.tsx    From wildduck-ui with MIT License 5 votes vote down vote up
/**
 * class component for Page
 * @class Page
 * @extends PureComponent
 * @exports
 */
export class Page extends PureComponent<IPageProps> {
	/**
	 *
	 * defaultProps
	 * @static
	 * @memberof Page
	 */
	static defaultProps = {
		title: '',
		subTitle: '',
		error: false,
		loading: false,
		extra: [] as React.ReactNode[],
	};

	/**
	 * render error page if error true
	 * @memberof Page
	 */
	// tslint:disable-next-line: variable-name
	static ErrorPage = ({ error }: IPageProps) =>
		error ? (
			<Result status={403} title='Oops...' subTitle='Sorry, we are having trouble showing the data!' />
		) : null;

	/**
	 * render children only if no loading or not having error
	 * @param {IPageProps} param0
	 * @memberof Page
	 */
	// tslint:disable-next-line: variable-name
	static Children = ({ error, loading, children }: IPageProps): JSX.Element | null => {
		if (error) {
			return null;
		}
		return <Spin spinning={loading}>{children}</Spin>;
	};

	/** Page Renderer */
	render(): JSX.Element {
		const { children, error, loading, title, subTitle, extra } = this.props;
		return (
			<PageHeader title={title} subTitle={subTitle} extra={extra} className={this.props.className}>
				{React.Children.map(children, (childElement) => {
					return React.cloneElement(childElement as React.ReactElement<any>, {
						error,
						loading,
					});
				})}
			</PageHeader>
		);
	}
}
Example #19
Source File: NewTodo.tsx    From casl-examples with MIT License 5 votes vote down vote up
export default class NewTodo extends PureComponent<Props, State> {
  state = {
    title: '',
    assignee: ''
  };

  private _updateTodoTitle = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ title: event.target.value });
  }

  private _updateTodoAssignee = (event: React.ChangeEvent<HTMLSelectElement>) => {
    this.setState({ assignee: event.target.value });
  }

  private _addTodo = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.keyCode !== 13) {
      return;
    }

    this.props.onNewTodo({ ...this.state });
    this.setState({ title: '', assignee: '' });
  }

  render() {
    return (
      <div className="new-todo">
        <input
          name="title"
          autoFocus
          autoComplete="off"
          placeholder="What needs to be done?"
          value={this.state.title}
          onChange={this._updateTodoTitle}
          onKeyUp={this._addTodo} />

        <select name="assignee" value={this.state.assignee} onChange={this._updateTodoAssignee}>
          <option value="" disabled>Choose Assignee</option>
          <option>me</option>
          <option>John Doe</option>
          <option>Alex Pupkin</option>
        </select>
      </div>
    );
  }
}
Example #20
Source File: crewfullequiptree.tsx    From website with MIT License 5 votes vote down vote up
class CrewFullEquipTree extends PureComponent<CrewFullEquipTreeProps> {
	render() {
		const { crew, items } = this.props;

		if (!crew || !this.props.visible) {
			return <span />;
		}

		let { craftCost, demands, factionOnlyTotal, totalChronCost } = calculateCrewDemands(crew, items);

		return (
			<Modal open={this.props.visible} onClose={() => this.props.onClosed()}>
				<Modal.Header>{crew.name}'s expanded equipment recipe trees</Modal.Header>
				<Modal.Content scrolling>
					<p>
						Faction-only items required <b>{factionOnlyTotal}</b>
					</p>
					<p>
						Estimated chroniton cost{' '}
						<span style={{ display: 'inline-block' }}>
							<img src={`${process.env.GATSBY_ASSETS_URL}atlas/energy_icon.png`} height={14} />
						</span>{' '}
						<b>{totalChronCost}</b>
						<Popup
							wide
							trigger={<Icon fitted name='help' />}
							header={'How is this calculated?'}
							content={
								<div>
									<p>This sums the estimated chroniton cost of each equipment and component in the tree.</p>
									<p>It estimates an item's cost by running the formula below for each mission and choosing the cheapest:</p>
									<p>
										<code>
											(6 - PIPS) * 1.8 * <i>mission cost</i>
										</code>
									</p>
									<p>See code for details. Feedback is welcome!</p>
								</div>
							}
						/>
					</p>
					<p>
						Build cost{' '}
						<span style={{ display: 'inline-block' }}>
							<img src={`${process.env.GATSBY_ASSETS_URL}currency_sc_currency_0.png`} height={16} />
						</span>{' '}
						<b>{craftCost}</b>
					</p>
					<Grid columns={3} centered padded>
						{demands.map((entry, idx) => (
							<Grid.Column key={idx}>
								<Popup
									trigger={
										<Header
											style={{ display: 'flex', cursor: 'zoom-in' }}
											icon={
												<ItemDisplay
													src={`${process.env.GATSBY_ASSETS_URL}${entry.equipment.imageUrl}`}
													size={48}
													maxRarity={entry.equipment.rarity}
													rarity={entry.equipment.rarity}
												/>
											}
											content={entry.equipment.name}
											subheader={`Need ${entry.count} ${entry.factionOnly ? ' (FACTION)' : ''}`}
										/>
									}
									header={CONFIG.RARITIES[entry.equipment.rarity].name + ' ' + entry.equipment.name}
									content={<ItemSources item_sources={entry.equipment.item_sources} />}
									on='click'
									wide
								/>
							</Grid.Column>
						))}
					</Grid>
				</Modal.Content>
			</Modal>
		);
	}
}
Example #21
Source File: ClipboardButton.tsx    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
export class ClipboardButton extends PureComponent<Props> {
  // @ts-ignore
  private clipboard: Clipboard;
  // @ts-ignore
  private elem: HTMLButtonElement;

  setRef = (elem: HTMLButtonElement) => {
    this.elem = elem;
  };

  componentDidMount() {
    const { getText, onClipboardCopy, onClipboardError } = this.props;

    this.clipboard = new Clipboard(this.elem, {
      text: () => getText(),
    });

    this.clipboard.on('success', (e: Clipboard.Event) => {
      onClipboardCopy && onClipboardCopy(e);
    });

    this.clipboard.on('error', (e: Clipboard.Event) => {
      onClipboardError && onClipboardError(e);
    });
  }

  componentWillUnmount() {
    this.clipboard.destroy();
  }

  render() {
    const { getText, onClipboardCopy, onClipboardError, children, ...buttonProps } = this.props;

    return (
      <Button {...buttonProps} ref={this.setRef}>
        {children}
      </Button>
    );
  }
}