path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ClassProperties.js
peopleticker/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; users = [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, ]; componentDidMount() { this.props.onReady(); } render() { return ( <div id="feature-class-properties"> {this.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
src/resources/assets/react-app/components/AuthHome.js
z5internet/ruf
import React, { Component } from 'react'; class AuthHome extends Component { render() { return ( <div> You are logged in! </div> ) } } export default AuthHome;
src/pages/dashboard/page.js
vgarcia692/wutmi_frontend
import React from 'react'; import styles from './style.css'; import CustomAxios from '../../common/components/CustomAxios'; export default class DashboardPage extends React.Component { constructor() { super() } render() { return ( <div className={styles.content}> <h1 className={styles.heading}>Dashboard</h1> </div> ); } }
app/containers/LanguageProvider/index.js
tomazy/react-boilerplate
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { selectLocale } from './selectors'; export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ); } } LanguageProvider.propTypes = { locale: React.PropTypes.string, messages: React.PropTypes.object, children: React.PropTypes.element.isRequired, }; const mapStateToProps = createSelector( selectLocale(), (locale) => ({ locale }) ); export default connect(mapStateToProps)(LanguageProvider);
demos/forms-demo/src/components/CurrentView/index.js
bdjnk/cerebral
import React from 'react' import {connect} from 'cerebral/react' import {state} from 'cerebral/tags' import Simple from '../Simple' const VIEWS = { Simple } export default connect({ currentView: state`app.currentView` }, function CurrentView ({currentView}) { const View = VIEWS[currentView] return ( <div style={{padding: 30, marginTop: 40}}> <View /> </div> ) })
src/datagrid-wrapper.js
JamesHageman/redux-datagrid
import React from 'react'; const { func, string, any, array, object } = React.PropTypes; export default class DatagridWrapper extends React.Component { static propTypes = { Component: func, initDatagrid: func, columns: array, name: string, searchText: string, sortBy: string, groupBy: string, sortDirection: string, handleSearchTextChange: func, handleGroupByChange: func, handleSortByChange: func, handleSortDirectionChange: func, filteredData: any, // should be array or array like (i.e. Immutable.List) fullData: any, // ditto groupedData: object, } componentDidMount() { if (!this.props.Component) { this.props.initDatagrid(); } } render() { const { Component, initDatagrid, // eslint-disable-line no-unused-vars columns, name, searchText, sortBy, groupBy, sortDirection, handleSearchTextChange, handleGroupByChange, handleSortByChange, handleSortDirectionChange, filteredData, fullData, groupedData, ...otherProps, } = this.props; if (!Component) { return null; } const datagridProps = { name: name, columns: columns, data: fullData, filtered: filteredData, grouped: groupedData, controls: { search: { value: searchText, onChange: handleSearchTextChange, }, sortBy: { value: sortBy, onChange: handleSortByChange, }, groupBy: { value: groupBy, onChange: handleGroupByChange, }, sortDirection: { value: sortDirection, onChange: handleSortDirectionChange, }, }, }; return <Component datagrid={datagridProps} {...otherProps}/>; } }
assets/js/components/ActivityPicker.js
ung-it/UngIT
import React from 'react'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; import {Glyphicon} from "react-bootstrap"; import '../../styles/activitypickerStyle.css'; let names = [ "Amerikansk idrett", "Bandy", "Basketball", "Biljard", "Boksing", "Bueskyting", "Cricket", "Curling", "Dans", "Fekting", "Festival", "Film/multimedia", "Fotball", "Friidrett", "Historielag", "Hopp", "Husflid", "Håndball", "Ishockey", "Kampsport", "Kor", "Kulturminnevern", "Kunst", "Kurs/opplæring", "Langrenn", "Litteratur", "Musikk/sang", "Orientering", "Scenekunst", "Skiskyting", "Skolekorps", "Skøytesport", "Svømming", "Sykling", "Tennis", "Turn", "Ungdoms/voksenkorps", "Volleyball", "Annet" ]; class ActivityPicker extends React.Component { constructor(props) { super(props); this.state = { activityButtonClicked: true, }; }; handleChange = (event, index, values) => { this.props.onFilterChange(values); }; menuItems(values) { return names.map((name) => ( <MenuItem key={name} insetChildren={true} checked={values && values.includes(name)} value={name} primaryText={name} /> )); }; handleEmptyFilter = () => { this.props.activityButton(this.state.activityButtonClicked) }; render() { return ( <div className="section row"> <div className="col-md-11"> <SelectField multiple={true} hintText="Velg type aktivitet..." value={this.props.activeFilters} onChange={this.handleChange} fullWidth={true} > {this.menuItems(this.props.activeFilters)} </SelectField> </div> <div className="col-md-1" id="activity-a-remove"> <div className="mdl-tooltip mdl-tooltip--large" data-mdl-for="remove-a-button"> Tøm aktivitetsfilter </div> <Glyphicon glyph="glyphicon glyphicon-remove" id="remove-a-button" onClick={this.handleEmptyFilter}/> </div> </div> ); }; } ActivityPicker.propTypes = { onFilterChange: React.PropTypes.func.isRequired, activeFilters: React.PropTypes.array.isRequired, activityButton: React.PropTypes.func.isRequired, }; export default ActivityPicker;
examples/nested-components/pages/index.js
dstreet/next.js
import React from 'react' import P from '../components/paragraph' import Post from '../components/post' import style from 'next/css' export default () => ( <div className={styles.main}> <Post title='My first blog post'> <P>Hello there</P> <P>This is an example of a componentized blog post</P> </Post> <Hr /> <Post title='My second blog post'> <P>Hello there</P> <P>This is another example.</P> <P>Wa-hoo!</P> </Post> <Hr /> <Post title='The final blog post'> <P>C'est fin</P> </Post> </div> ) const Hr = () => <hr className={styles.hr} /> const styles = { main: style({ margin: 'auto', maxWidth: '420px', padding: '10px' }), hr: style({ width: '100px', borderWidth: 0, margin: '20px auto', textAlign: 'center', '::before': { content: '"***"', color: '#ccc' } }) }
__tests__/InfoDisplay_test.js
SashaKoro/redux-tic-tac-toe
/* eslint-disable no-undef */ import React from 'react'; import { shallow, mount } from 'enzyme'; import InfoDisplay from '../src/components/InfoDisplay'; describe('InfoDisplay', () => { it('should be selectable by class name', () => { const wrapper = shallow(<InfoDisplay info="Your Turn!" />); expect(wrapper.is('.InfoDisplay')).toBe(true); }); it('should mount to the DOM', () => { const wrapper = mount(<InfoDisplay info="Your Turn!" />); expect(wrapper.find('.InfoDisplay').length).toBe(1); }); it('should display the info to the user', () => { const wrapper = mount(<InfoDisplay info="Your Turn!" />); expect(wrapper.find('.InfoDisplay').text()).toBe('Your Turn!'); }); });
Sources/ewsnodejs-server/node_modules/react-transition-group/esm/ReplaceTransition.js
nihospr01/OpenSpeechPlatform-UCSD
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose"; import PropTypes from 'prop-types'; import React from 'react'; import ReactDOM from 'react-dom'; import TransitionGroup from './TransitionGroup'; /** * The `<ReplaceTransition>` component is a specialized `Transition` component * that animates between two children. * * ```jsx * <ReplaceTransition in> * <Fade><div>I appear first</div></Fade> * <Fade><div>I replace the above</div></Fade> * </ReplaceTransition> * ``` */ var ReplaceTransition = /*#__PURE__*/function (_React$Component) { _inheritsLoose(ReplaceTransition, _React$Component); function ReplaceTransition() { var _this; for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) { _args[_key] = arguments[_key]; } _this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this; _this.handleEnter = function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return _this.handleLifecycle('onEnter', 0, args); }; _this.handleEntering = function () { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this.handleLifecycle('onEntering', 0, args); }; _this.handleEntered = function () { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return _this.handleLifecycle('onEntered', 0, args); }; _this.handleExit = function () { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } return _this.handleLifecycle('onExit', 1, args); }; _this.handleExiting = function () { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } return _this.handleLifecycle('onExiting', 1, args); }; _this.handleExited = function () { for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { args[_key7] = arguments[_key7]; } return _this.handleLifecycle('onExited', 1, args); }; return _this; } var _proto = ReplaceTransition.prototype; _proto.handleLifecycle = function handleLifecycle(handler, idx, originalArgs) { var _child$props; var children = this.props.children; var child = React.Children.toArray(children)[idx]; if (child.props[handler]) (_child$props = child.props)[handler].apply(_child$props, originalArgs); if (this.props[handler]) { var maybeNode = child.props.nodeRef ? undefined : ReactDOM.findDOMNode(this); this.props[handler](maybeNode); } }; _proto.render = function render() { var _this$props = this.props, children = _this$props.children, inProp = _this$props.in, props = _objectWithoutPropertiesLoose(_this$props, ["children", "in"]); var _React$Children$toArr = React.Children.toArray(children), first = _React$Children$toArr[0], second = _React$Children$toArr[1]; delete props.onEnter; delete props.onEntering; delete props.onEntered; delete props.onExit; delete props.onExiting; delete props.onExited; return /*#__PURE__*/React.createElement(TransitionGroup, props, inProp ? React.cloneElement(first, { key: 'first', onEnter: this.handleEnter, onEntering: this.handleEntering, onEntered: this.handleEntered }) : React.cloneElement(second, { key: 'second', onEnter: this.handleExit, onEntering: this.handleExiting, onEntered: this.handleExited })); }; return ReplaceTransition; }(React.Component); ReplaceTransition.propTypes = process.env.NODE_ENV !== "production" ? { in: PropTypes.bool.isRequired, children: function children(props, propName) { if (React.Children.count(props[propName]) !== 2) return new Error("\"" + propName + "\" must be exactly two transition components."); return null; } } : {}; export default ReplaceTransition;
src/SwipeableWithPagination.js
zeljkoX/swipable-views-with-pagination
import { StyleSheet, View, Image, Dimensions } from 'react-native'; import React, { Component } from 'react'; import SwipeableViews from 'react-swipeable-views/lib/index.native.animated'; import Pagination from './Pagination'; let paginationSize = 0; export default class SwipeableWithPagination extends Component { constructor(props) { super(props); this.state = { length: 0, index: 0 }; this.onChangeIndex = this.onChangeIndex.bind(this); } componentWillMount(){ this.setState({length: this.props.children.length}); } render() { return ( <View > <SwipeableViews onChangeIndex={this.onChangeIndex}> {this.props.children} </SwipeableViews> <Pagination length={this.props.children.length} index={this.state.index} paginationStyle={this.props.pagination || [styles.pagination]} dots={this.props.dots || styles.dots} getPaginationDimensions={this.props.getPaginationDimensions}/> </View> ); } onChangeIndex(index){ this.setState({index}); } } const styles = StyleSheet.create({ pagination: { flexDirection: 'row', bottom: 20, justifyContent: 'center', alignItems: 'center' }, dots: { width: 10, height: 10, borderRadius: 5, marginLeft: 5, marginRight: 5 } });
packages/days-off/src/components/App/index.js
simonrelet/days-off
import React, { Component } from 'react'; import injectSheet from 'react-jss'; import Icon from '@marv/components/Icon'; import fetch, { parseJSON, handleError } from '@marv/components/fetch'; import { isHalfDayBefore, isHalfDayAfter } from '../dateUtils'; import Calendars from '../Calendars'; import UserHeader from '../UserHeader'; import Menu from '../Menu'; import styles from './styles'; const app = { name: 'days-off', version: '0.1.0', }; class App extends Component { constructor() { super(); this.state = { user: null, selection: null, }; } componentDidMount() { fetch('/api/user') .then(parseJSON) .then(res => { this.setState({ user: res }); }) .catch(handleError); } handleSelect = (selection, selectionBlock) => { console.log('selection:', selection); this.setState(prevState => { if (!prevState.selection || !selectionBlock) { return { selection: { start: selection, end: selection, }, }; } if (isHalfDayBefore(selection, prevState.selection.start)) { return { selection: { start: selection, end: prevState.selection.end, }, }; } if (isHalfDayAfter(selection, prevState.selection.end)) { return { selection: { start: prevState.selection.start, end: selection, }, }; } }); }; handleCancelSelection = () => { this.setState({ selection: null }); }; handleKeyDown = e => { if (e.key === 'Escape') { this.handleCancelSelection(); } }; render() { const { user, selection } = this.state; const { classes } = this.props; return ( <div className={classes.app} onKeyDown={this.handleKeyDown} tabIndex={1}> <div className={classes.menu}> <div className={classes.menuHeader}> <Icon name="days-off" className={classes.icon} /> <span>Days Off</span> </div> <Menu className={classes.menuContent} selection={selection} onCancelSelection={this.handleCancelSelection} user={user} /> <div className={classes.menuFooter}> {app.version} </div> </div> <div className={classes.body}> <div className={classes.bodyHeader}> {user && <UserHeader {...user} />} </div> <div className={classes.bodyContent}> <Calendars onSelect={this.handleSelect} selection={selection} /> </div> </div> </div> ); } } export default injectSheet(styles)(App);
app/jsx/permissions/index.js
djbender/canvas-lms
/* * Copyright (C) 2018 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import ReactDOM from 'react-dom' import {Provider} from 'react-redux' // TODO: we probably want this one eventually // import { subscribeFlashNotifications } from '../shared/reduxNotifications' import {ConnectedPermissionsIndex} from './components/PermissionsIndex' import createStore from './store' export default function createPermissionsIndex(root, data = {}) { const store = createStore(data) function unmount() { ReactDOM.unmountComponentAtNode(root) } function render() { ReactDOM.render( <Provider store={store}> <ConnectedPermissionsIndex /> </Provider>, root ) } // For some reason this is not working TODO figure this out // subscribeFlashNotifications(store) return {unmount, render} }
client/src/javascript/components/general/filesystem/PriorityMeter.js
jfurrow/flood
import {injectIntl} from 'react-intl'; import React from 'react'; import PiorityLevels from '../../../constants/PriorityLevels'; const METHODS_TO_BIND = ['handleClick']; class PriorityMeter extends React.Component { constructor() { super(); this.state = { optimisticData: { level: null, }, }; METHODS_TO_BIND.forEach(method => { this[method] = this[method].bind(this); }); } componentDidMount() { if (this.props.bindExternalChangeHandler) { this.props.bindExternalChangeHandler(this.handleClick); } } componentWillUnmount() { if (this.props.bindExternalChangeHandler) { this.props.bindExternalChangeHandler(null); } } getPriorityLabel() { switch (PiorityLevels[this.props.priorityType][this.getPriorityLevel()]) { case 'DONT_DOWNLOAD': return this.props.intl.formatMessage({ id: 'priority.dont.download', defaultMessage: "Don't Download", }); case 'HIGH': return this.props.intl.formatMessage({ id: 'priority.high', defaultMessage: 'High', }); case 'LOW': return this.props.intl.formatMessage({ id: 'priority.low', defaultMessage: 'Low', }); case 'NORMAL': return this.props.intl.formatMessage({ id: 'priority.normal', defaultMessage: 'Normal', }); default: return ''; } } getPriorityLevel() { if (this.state.optimisticData.level != null) { return this.state.optimisticData.level; } return this.props.level; } handleClick() { let level = this.getPriorityLevel(); if (level++ >= this.props.maxLevel) { level = 0; } this.setState({optimisticData: {level}}); this.props.onChange(this.props.id, level); } render() { let label = null; if (this.props.showLabel) { label = <span className="priority-meter__label">{this.getPriorityLabel()}</span>; } return ( <div className="priority-meter__wrapper" onClick={this.handleClick}> <div className={ 'priority-meter ' + `priority-meter--max-${this.props.maxLevel} ` + `priority-meter--level-${this.getPriorityLevel()}` } /> {label} </div> ); } } export default injectIntl(PriorityMeter);
node_modules/react-bootstrap/es/Radio.js
NathanBWaters/jb_club
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import warning from 'warning'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { inline: React.PropTypes.bool, disabled: React.PropTypes.bool, /** * Only valid if `inline` is not set. */ validationState: React.PropTypes.oneOf(['success', 'warning', 'error']), /** * Attaches a ref to the `<input>` element. Only functions can be used here. * * ```js * <Radio inputRef={ref => { this.input = ref; }} /> * ``` */ inputRef: React.PropTypes.func }; var defaultProps = { inline: false, disabled: false }; var Radio = function (_React$Component) { _inherits(Radio, _React$Component); function Radio() { _classCallCheck(this, Radio); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Radio.prototype.render = function render() { var _props = this.props, inline = _props.inline, disabled = _props.disabled, validationState = _props.validationState, inputRef = _props.inputRef, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['inline', 'disabled', 'validationState', 'inputRef', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var input = React.createElement('input', _extends({}, elementProps, { ref: inputRef, type: 'radio', disabled: disabled })); if (inline) { var _classes2; var _classes = (_classes2 = {}, _classes2[prefix(bsProps, 'inline')] = true, _classes2.disabled = disabled, _classes2); // Use a warning here instead of in propTypes to get better-looking // generated documentation. process.env.NODE_ENV !== 'production' ? warning(!validationState, '`validationState` is ignored on `<Radio inline>`. To display ' + 'validation state on an inline radio, set `validationState` on a ' + 'parent `<FormGroup>` or other element instead.') : void 0; return React.createElement( 'label', { className: classNames(className, _classes), style: style }, input, children ); } var classes = _extends({}, getClassSet(bsProps), { disabled: disabled }); if (validationState) { classes['has-' + validationState] = true; } return React.createElement( 'div', { className: classNames(className, classes), style: style }, React.createElement( 'label', null, input, children ) ); }; return Radio; }(React.Component); Radio.propTypes = propTypes; Radio.defaultProps = defaultProps; export default bsClass('radio', Radio);
src/index.js
asithagihan03/alankara-hapi
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, hashHistory } from 'react-router'; import routes from './routes'; ReactDOM.render( <Router routes={routes} history={hashHistory} />, document.getElementById('root') );
node_modules/react-native/Libraries/Components/TextInput/TextInput.js
hpdmitriy/Bjj4All
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule TextInput * @flow */ 'use strict'; const ColorPropType = require('ColorPropType'); const DocumentSelectionState = require('DocumentSelectionState'); const EventEmitter = require('EventEmitter'); const NativeMethodsMixin = require('NativeMethodsMixin'); const Platform = require('Platform'); const React = require('React'); const ReactNative = require('ReactNative'); const StyleSheet = require('StyleSheet'); const Text = require('Text'); const TextInputState = require('TextInputState'); const TimerMixin = require('react-timer-mixin'); const TouchableWithoutFeedback = require('TouchableWithoutFeedback'); const UIManager = require('UIManager'); const View = require('View'); const warning = require('fbjs/lib/warning'); const emptyFunction = require('fbjs/lib/emptyFunction'); const invariant = require('fbjs/lib/invariant'); const requireNativeComponent = require('requireNativeComponent'); const PropTypes = React.PropTypes; const onlyMultiline = { onTextInput: true, children: true, }; if (Platform.OS === 'android') { var AndroidTextInput = requireNativeComponent('AndroidTextInput', null); } else if (Platform.OS === 'ios') { var RCTTextView = requireNativeComponent('RCTTextView', null); var RCTTextField = requireNativeComponent('RCTTextField', null); } type Event = Object; type Selection = { start: number, end?: number, }; const DataDetectorTypes = [ 'phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all', ]; /** * A foundational component for inputting text into the app via a * keyboard. Props provide configurability for several features, such as * auto-correction, auto-capitalization, placeholder text, and different keyboard * types, such as a numeric keypad. * * The simplest use case is to plop down a `TextInput` and subscribe to the * `onChangeText` events to read the user input. There are also other events, * such as `onSubmitEditing` and `onFocus` that can be subscribed to. A simple * example: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, TextInput } from 'react-native'; * * class UselessTextInput extends Component { * constructor(props) { * super(props); * this.state = { text: 'Useless Placeholder' }; * } * * render() { * return ( * <TextInput * style={{height: 40, borderColor: 'gray', borderWidth: 1}} * onChangeText={(text) => this.setState({text})} * value={this.state.text} * /> * ); * } * } * * // App registration and rendering * AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput); * ``` * * Note that some props are only available with `multiline={true/false}`. * Additionally, border styles that apply to only one side of the element * (e.g., `borderBottomColor`, `borderLeftWidth`, etc.) will not be applied if * `multiline=false`. To achieve the same effect, you can wrap your `TextInput` * in a `View`: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, TextInput } from 'react-native'; * * class UselessTextInput extends Component { * render() { * return ( * <TextInput * {...this.props} // Inherit any props passed to it; e.g., multiline, numberOfLines below * editable = {true} * maxLength = {40} * /> * ); * } * } * * class UselessTextInputMultiline extends Component { * constructor(props) { * super(props); * this.state = { * text: 'Useless Multiline Placeholder', * }; * } * * // If you type something in the text box that is a color, the background will change to that * // color. * render() { * return ( * <View style={{ * backgroundColor: this.state.text, * borderBottomColor: '#000000', * borderBottomWidth: 1 }} * > * <UselessTextInput * multiline = {true} * numberOfLines = {4} * onChangeText={(text) => this.setState({text})} * value={this.state.text} * /> * </View> * ); * } * } * * // App registration and rendering * AppRegistry.registerComponent( * 'AwesomeProject', * () => UselessTextInputMultiline * ); * ``` * * `TextInput` has by default a border at the bottom of its view. This border * has its padding set by the background image provided by the system, and it * cannot be changed. Solutions to avoid this is to either not set height * explicitly, case in which the system will take care of displaying the border * in the correct position, or to not display the border by setting * `underlineColorAndroid` to transparent. * * Note that on Android performing text selection in input can change * app's activity `windowSoftInputMode` param to `adjustResize`. * This may cause issues with components that have position: 'absolute' * while keyboard is active. To avoid this behavior either specify `windowSoftInputMode` * in AndroidManifest.xml ( https://developer.android.com/guide/topics/manifest/activity-element.html ) * or control this param programmatically with native code. * */ const TextInput = React.createClass({ statics: { /* TODO(brentvatne) docs are needed for this */ State: TextInputState, }, propTypes: { ...View.propTypes, /** * Can tell `TextInput` to automatically capitalize certain characters. * * - `characters`: all characters. * - `words`: first letter of each word. * - `sentences`: first letter of each sentence (*default*). * - `none`: don't auto capitalize anything. */ autoCapitalize: PropTypes.oneOf([ 'none', 'sentences', 'words', 'characters', ]), /** * If `false`, disables auto-correct. The default value is `true`. */ autoCorrect: PropTypes.bool, /** * If `false`, disables spell-check style (i.e. red underlines). * The default value is inherited from `autoCorrect`. * @platform ios */ spellCheck: PropTypes.bool, /** * If `true`, focuses the input on `componentDidMount`. * The default value is `false`. */ autoFocus: PropTypes.bool, /** * If `false`, text is not editable. The default value is `true`. */ editable: PropTypes.bool, /** * Determines which keyboard to open, e.g.`numeric`. * * The following values work across platforms: * * - `default` * - `numeric` * - `email-address` * - `phone-pad` */ keyboardType: PropTypes.oneOf([ // Cross-platform 'default', 'email-address', 'numeric', 'phone-pad', // iOS-only 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search', ]), /** * Determines the color of the keyboard. * @platform ios */ keyboardAppearance: PropTypes.oneOf([ 'default', 'light', 'dark', ]), /** * Determines how the return key should look. On Android you can also use * `returnKeyLabel`. * * *Cross platform* * * The following values work across platforms: * * - `done` * - `go` * - `next` * - `search` * - `send` * * *Android Only* * * The following values work on Android only: * * - `none` * - `previous` * * *iOS Only* * * The following values work on iOS only: * * - `default` * - `emergency-call` * - `google` * - `join` * - `route` * - `yahoo` */ returnKeyType: PropTypes.oneOf([ // Cross-platform 'done', 'go', 'next', 'search', 'send', // Android-only 'none', 'previous', // iOS-only 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo', ]), /** * Sets the return key to the label. Use it instead of `returnKeyType`. * @platform android */ returnKeyLabel: PropTypes.string, /** * Limits the maximum number of characters that can be entered. Use this * instead of implementing the logic in JS to avoid flicker. */ maxLength: PropTypes.number, /** * Sets the number of lines for a `TextInput`. Use it with multiline set to * `true` to be able to fill the lines. * @platform android */ numberOfLines: PropTypes.number, /** * When `false`, if there is a small amount of space available around a text input * (e.g. landscape orientation on a phone), the OS may choose to have the user edit * the text inside of a full screen text input mode. When `true`, this feature is * disabled and users will always edit the text directly inside of the text input. * Defaults to `false`. * @platform android */ disableFullscreenUI: PropTypes.bool, /** * If `true`, the keyboard disables the return key when there is no text and * automatically enables it when there is text. The default value is `false`. * @platform ios */ enablesReturnKeyAutomatically: PropTypes.bool, /** * If `true`, the text input can be multiple lines. * The default value is `false`. */ multiline: PropTypes.bool, /** * Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced` * The default value is `simple`. * @platform android */ textBreakStrategy: React.PropTypes.oneOf(['simple', 'highQuality', 'balanced']), /** * Callback that is called when the text input is blurred. */ onBlur: PropTypes.func, /** * Callback that is called when the text input is focused. */ onFocus: PropTypes.func, /** * Callback that is called when the text input's text changes. */ onChange: PropTypes.func, /** * Callback that is called when the text input's text changes. * Changed text is passed as an argument to the callback handler. */ onChangeText: PropTypes.func, /** * Callback that is called when the text input's content size changes. * This will be called with * `{ nativeEvent: { contentSize: { width, height } } }`. * * Only called for multiline text inputs. */ onContentSizeChange: PropTypes.func, /** * Callback that is called when text input ends. */ onEndEditing: PropTypes.func, /** * Callback that is called when the text input selection is changed. * This will be called with * `{ nativeEvent: { selection: { start, end } } }`. */ onSelectionChange: PropTypes.func, /** * Callback that is called when the text input's submit button is pressed. * Invalid if `multiline={true}` is specified. */ onSubmitEditing: PropTypes.func, /** * Callback that is called when a key is pressed. * This will be called with `{ nativeEvent: { key: keyValue } }` * where `keyValue` is `'Enter'` or `'Backspace'` for respective keys and * the typed-in character otherwise including `' '` for space. * Fires before `onChange` callbacks. * @platform ios */ onKeyPress: PropTypes.func, /** * Invoked on mount and layout changes with `{x, y, width, height}`. */ onLayout: PropTypes.func, /** * Invoked on content scroll with `{ nativeEvent: { contentOffset: { x, y } } }`. * May also contain other properties from ScrollEvent but on Android contentSize * is not provided for performance reasons. */ onScroll: PropTypes.func, /** * The string that will be rendered before text input has been entered. */ placeholder: PropTypes.node, /** * The text color of the placeholder string. */ placeholderTextColor: ColorPropType, /** * If `true`, the text input obscures the text entered so that sensitive text * like passwords stay secure. The default value is `false`. */ secureTextEntry: PropTypes.bool, /** * The highlight (and cursor on iOS) color of the text input. */ selectionColor: ColorPropType, /** * An instance of `DocumentSelectionState`, this is some state that is responsible for * maintaining selection information for a document. * * Some functionality that can be performed with this instance is: * * - `blur()` * - `focus()` * - `update()` * * > You can reference `DocumentSelectionState` in * > [`vendor/document/selection/DocumentSelectionState.js`](https://github.com/facebook/react-native/blob/master/Libraries/vendor/document/selection/DocumentSelectionState.js) * * @platform ios */ selectionState: PropTypes.instanceOf(DocumentSelectionState), /** * The start and end of the text input's selection. Set start and end to * the same value to position the cursor. */ selection: PropTypes.shape({ start: PropTypes.number.isRequired, end: PropTypes.number, }), /** * The value to show for the text input. `TextInput` is a controlled * component, which means the native value will be forced to match this * value prop if provided. For most uses, this works great, but in some * cases this may cause flickering - one common cause is preventing edits * by keeping value the same. In addition to simply setting the same value, * either set `editable={false}`, or set/update `maxLength` to prevent * unwanted edits without flicker. */ value: PropTypes.string, /** * Provides an initial value that will change when the user starts typing. * Useful for simple use-cases where you do not want to deal with listening * to events and updating the value prop to keep the controlled state in sync. */ defaultValue: PropTypes.node, /** * When the clear button should appear on the right side of the text view. * @platform ios */ clearButtonMode: PropTypes.oneOf([ 'never', 'while-editing', 'unless-editing', 'always', ]), /** * If `true`, clears the text field automatically when editing begins. * @platform ios */ clearTextOnFocus: PropTypes.bool, /** * If `true`, all text will automatically be selected on focus. */ selectTextOnFocus: PropTypes.bool, /** * If `true`, the text field will blur when submitted. * The default value is true for single-line fields and false for * multiline fields. Note that for multiline fields, setting `blurOnSubmit` * to `true` means that pressing return will blur the field and trigger the * `onSubmitEditing` event instead of inserting a newline into the field. */ blurOnSubmit: PropTypes.bool, /** * Note that not all Text styles are supported, * see [Issue#7070](https://github.com/facebook/react-native/issues/7070) * for more detail. * * [Styles](docs/style.html) */ style: Text.propTypes.style, /** * The color of the `TextInput` underline. * @platform android */ underlineColorAndroid: ColorPropType, /** * If defined, the provided image resource will be rendered on the left. * @platform android */ inlineImageLeft: PropTypes.string, /** * Padding between the inline image, if any, and the text input itself. * @platform android */ inlineImagePadding: PropTypes.number, /** * Determines the types of data converted to clickable URLs in the text input. * Only valid if `multiline={true}` and `editable={false}`. * By default no data types are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes: PropTypes.oneOfType([ PropTypes.oneOf(DataDetectorTypes), PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), ]), }, /** * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We * make `this` look like an actual native component class. */ mixins: [NativeMethodsMixin, TimerMixin], viewConfig: ((Platform.OS === 'ios' && RCTTextField ? RCTTextField.viewConfig : (Platform.OS === 'android' && AndroidTextInput ? AndroidTextInput.viewConfig : {})) : Object), /** * Returns `true` if the input is currently focused; `false` otherwise. */ isFocused: function(): boolean { return TextInputState.currentlyFocusedField() === ReactNative.findNodeHandle(this._inputRef); }, contextTypes: { onFocusRequested: React.PropTypes.func, focusEmitter: React.PropTypes.instanceOf(EventEmitter), }, _inputRef: (undefined: any), _focusSubscription: (undefined: ?Function), _lastNativeText: (undefined: ?string), _lastNativeSelection: (undefined: ?Selection), componentDidMount: function() { this._lastNativeText = this.props.value; if (!this.context.focusEmitter) { if (this.props.autoFocus) { this.requestAnimationFrame(this.focus); } return; } this._focusSubscription = this.context.focusEmitter.addListener( 'focus', (el) => { if (this === el) { this.requestAnimationFrame(this.focus); } else if (this.isFocused()) { this.blur(); } } ); if (this.props.autoFocus) { this.context.onFocusRequested(this); } }, componentWillUnmount: function() { this._focusSubscription && this._focusSubscription.remove(); if (this.isFocused()) { this.blur(); } }, getChildContext: function(): Object { return {isInAParentText: true}; }, childContextTypes: { isInAParentText: React.PropTypes.bool }, /** * Removes all text from the `TextInput`. */ clear: function() { this.setNativeProps({text: ''}); }, render: function() { if (Platform.OS === 'ios') { return this._renderIOS(); } else if (Platform.OS === 'android') { return this._renderAndroid(); } }, _getText: function(): ?string { return typeof this.props.value === 'string' ? this.props.value : ( typeof this.props.defaultValue === 'string' ? this.props.defaultValue : '' ); }, _setNativeRef: function(ref: any) { this._inputRef = ref; }, _renderIOS: function() { var textContainer; var props = Object.assign({}, this.props); props.style = [styles.input, this.props.style]; if (props.selection && props.selection.end == null) { props.selection = {start: props.selection.start, end: props.selection.start}; } if (!props.multiline) { if (__DEV__) { for (var propKey in onlyMultiline) { if (props[propKey]) { const error = new Error( 'TextInput prop `' + propKey + '` is only supported with multiline.' ); warning(false, '%s', error.stack); } } } textContainer = <RCTTextField ref={this._setNativeRef} {...props} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onSelectionChange={this._onSelectionChange} onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue} text={this._getText()} />; } else { var children = props.children; var childCount = 0; React.Children.forEach(children, () => ++childCount); invariant( !(props.value && childCount), 'Cannot specify both value and children.' ); if (childCount >= 1) { children = <Text style={props.style}>{children}</Text>; } if (props.inputView) { children = [children, props.inputView]; } textContainer = <RCTTextView ref={this._setNativeRef} {...props} children={children} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onContentSizeChange={this.props.onContentSizeChange} onSelectionChange={this._onSelectionChange} onTextInput={this._onTextInput} onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue} text={this._getText()} dataDetectorTypes={this.props.dataDetectorTypes} onScroll={this._onScroll} />; } return ( <TouchableWithoutFeedback onLayout={props.onLayout} onPress={this._onPress} rejectResponderTermination={true} accessible={props.accessible} accessibilityLabel={props.accessibilityLabel} accessibilityTraits={props.accessibilityTraits} testID={props.testID}> {textContainer} </TouchableWithoutFeedback> ); }, _renderAndroid: function() { const props = Object.assign({}, this.props); props.style = [this.props.style]; props.autoCapitalize = UIManager.AndroidTextInput.Constants.AutoCapitalizationType[this.props.autoCapitalize]; var children = this.props.children; var childCount = 0; React.Children.forEach(children, () => ++childCount); invariant( !(this.props.value && childCount), 'Cannot specify both value and children.' ); if (childCount > 1) { children = <Text>{children}</Text>; } if (props.selection && props.selection.end == null) { props.selection = {start: props.selection.start, end: props.selection.start}; } const textContainer = <AndroidTextInput ref={this._setNativeRef} {...props} mostRecentEventCount={0} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onSelectionChange={this._onSelectionChange} onTextInput={this._onTextInput} text={this._getText()} children={children} disableFullscreenUI={this.props.disableFullscreenUI} textBreakStrategy={this.props.textBreakStrategy} />; return ( <TouchableWithoutFeedback onLayout={this.props.onLayout} onPress={this._onPress} accessible={this.props.accessible} accessibilityLabel={this.props.accessibilityLabel} accessibilityComponentType={this.props.accessibilityComponentType} testID={this.props.testID}> {textContainer} </TouchableWithoutFeedback> ); }, _onFocus: function(event: Event) { if (this.props.onFocus) { this.props.onFocus(event); } if (this.props.selectionState) { this.props.selectionState.focus(); } }, _onPress: function(event: Event) { if (this.props.editable || this.props.editable === undefined) { this.focus(); } }, _onChange: function(event: Event) { // Make sure to fire the mostRecentEventCount first so it is already set on // native when the text value is set. if (this._inputRef) { this._inputRef.setNativeProps({ mostRecentEventCount: event.nativeEvent.eventCount, }); } var text = event.nativeEvent.text; this.props.onChange && this.props.onChange(event); this.props.onChangeText && this.props.onChangeText(text); if (!this._inputRef) { // calling `this.props.onChange` or `this.props.onChangeText` // may clean up the input itself. Exits here. return; } this._lastNativeText = text; this.forceUpdate(); }, _onSelectionChange: function(event: Event) { this.props.onSelectionChange && this.props.onSelectionChange(event); if (!this._inputRef) { // calling `this.props.onSelectionChange` // may clean up the input itself. Exits here. return; } this._lastNativeSelection = event.nativeEvent.selection; if (this.props.selection || this.props.selectionState) { this.forceUpdate(); } }, componentDidUpdate: function () { // This is necessary in case native updates the text and JS decides // that the update should be ignored and we should stick with the value // that we have in JS. const nativeProps = {}; if (this._lastNativeText !== this.props.value && typeof this.props.value === 'string') { nativeProps.text = this.props.value; } // Selection is also a controlled prop, if the native value doesn't match // JS, update to the JS value. const {selection} = this.props; if (this._lastNativeSelection && selection && (this._lastNativeSelection.start !== selection.start || this._lastNativeSelection.end !== selection.end)) { nativeProps.selection = this.props.selection; } if (Object.keys(nativeProps).length > 0 && this._inputRef) { this._inputRef.setNativeProps(nativeProps); } if (this.props.selectionState && selection) { this.props.selectionState.update(selection.start, selection.end); } }, _onBlur: function(event: Event) { this.blur(); if (this.props.onBlur) { this.props.onBlur(event); } if (this.props.selectionState) { this.props.selectionState.blur(); } }, _onTextInput: function(event: Event) { this.props.onTextInput && this.props.onTextInput(event); }, _onScroll: function(event: Event) { this.props.onScroll && this.props.onScroll(event); }, }); var styles = StyleSheet.create({ input: { alignSelf: 'stretch', }, }); module.exports = TextInput;
still/src/components/Layout/Footer.js
marktheshark13/Stillwaters-farm
import React, { Component } from 'react'; class Footer extends Component { render() { return ( <div> <h1>Footer test</h1> </div> ); } } export default Footer;
src/content/index.js
squarewave/bhr.html
import React from 'react'; import Perf from 'react-addons-perf'; import { render } from 'react-dom'; import Root from './containers/Root'; import createStore from './create-store'; import 'photon-colors/colors.css'; import '../../res/style.css'; if (process.env.NODE_ENV === 'production') { const runtime = require('offline-plugin/runtime'); runtime.install({ onUpdateReady: () => { runtime.applyUpdate(); }, }); } window.geckoProfilerPromise = new Promise(function (resolve) { window.connectToGeckoProfiler = resolve; }); const store = createStore(); render( <Root store={store} />, document.getElementById('root') ); window.Perf = Perf;
docs/src/app/components/pages/components/GridList/Page.js
pancho111203/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import gridListReadmeText from './README'; import gridListExampleSimpleCode from '!raw!./ExampleSimple'; import GridListExampleSimple from './ExampleSimple'; import gridListExampleComplexCode from '!raw!./ExampleComplex'; import GridListExampleComplex from './ExampleComplex'; import gridListExampleSingleLineCode from '!raw!./ExampleSingleLine'; import GridListExampleSingleLine from './ExampleSingleLine'; import gridListCode from '!raw!material-ui/GridList/GridList'; import gridTileCode from '!raw!material-ui/GridList/GridTile'; const GridListPage = () => ( <div> <Title render={(previousTitle) => `Grid List - ${previousTitle}`} /> <MarkdownElement text={gridListReadmeText} /> <CodeExample title="Simple example" code={gridListExampleSimpleCode} > <GridListExampleSimple /> </CodeExample> <CodeExample title="Complex example" code={gridListExampleComplexCode} > <GridListExampleComplex /> </CodeExample> <CodeExample title="One line example" code={gridListExampleSingleLineCode} > <GridListExampleSingleLine /> </CodeExample> <PropTypeDescription header="### GridList Properties" code={gridListCode} /> <PropTypeDescription header="### GridTile Properties" code={gridTileCode} /> </div> ); export default GridListPage;
client/modules/App/components/Menu/Menu.js
lordknight1904/bigvnadmin
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { getUserName, getId } from '../../../Login/LoginReducer'; import { logout } from '../../../Login/LoginActions'; import { Tab, Row, Col, Nav, NavItem, NavDropdown, MenuItem } from'react-bootstrap'; import styles from '../../App.css'; class Menu extends Component{ constructor(props){ super(props); this.state = { selected: 'news', approvedNews: false, }; } handleSelect = (eventKey) => { if (eventKey === 'approvedNews') { this.setState({ approvedNews: true, places: false, menu: false }); return; } if (eventKey === 'places') { this.setState({ approvedNews: false, places: true, menu: false }); return; } if (eventKey === 'menu') { this.setState({ approvedNews: false, places: false, menu: true }); return; } if (eventKey !== 'logOut') { this.setState({ selected: eventKey }); this.context.router.push(`/${eventKey}`); } else { this.setState({ approvedNews: false, places: false, menu: false }); this.props.dispatch(logout()); } }; render(){ return ( <Nav bsStyle="pills" stacked activeKey={1} onSelect={this.handleSelect} bsClass={`nav ${styles.sideMenu}`} style={{ backgroundColor: '#2E363F', color: 'white' }}> <NavItem eventKey="approvedNews"> Duyệt tin </NavItem> { this.state.approvedNews ? ( <MenuItem className={styles.subMenu} eventKey="news">Rao vặt</MenuItem> ) : '' } { this.state.approvedNews ? ( <MenuItem className={styles.subMenu} eventKey="blog">Blog</MenuItem> ) : '' } <NavItem eventKey="admin"> Quản trị viên </NavItem> <NavItem eventKey="user"> Người dùng </NavItem> <NavItem eventKey="places"> Địa điểm </NavItem> { this.state.places ? ( <MenuItem className={styles.subMenu} eventKey="city">City</MenuItem> ) : '' } { this.state.places ? ( <MenuItem className={styles.subMenu} eventKey="district">District</MenuItem> ) : '' } { this.state.places ? ( <MenuItem className={styles.subMenu} eventKey="ward">Ward</MenuItem> ) : '' } <NavItem eventKey="menu"> Menu </NavItem> { this.state.menu ? ( <MenuItem className={styles.subMenu} eventKey="menunews">Rao vặt</MenuItem> ) : '' } { this.state.menu ? ( <MenuItem className={styles.subMenu} eventKey="menublog">Blog</MenuItem> ) : '' } <NavItem eventKey="keyword"> Từ khóa </NavItem> <NavItem eventKey="banner"> Quảng cáo </NavItem> <NavItem eventKey="setting"> Cấu hình </NavItem> <NavItem eventKey="logOut"> Đăng xuất </NavItem> </Nav> ); } } function mapStateToProps(state) { return { // userName: getUserName(state), // id: getId(state), }; } Menu.propTypes = { dispatch: PropTypes.func, // userName: PropTypes.string.isRequired, // id: PropTypes.string.isRequired, }; Menu.contextTypes = { router: PropTypes.object, }; export default connect(mapStateToProps)(Menu);
packages/react-router-website/modules/components/App.js
react-translate-team/react-router-CN
import React from 'react' // don't want the shimmed one // eslint-disable-next-line import BrowserRouter from '../../../react-router-dom/BrowserRouter' // this stuff is shimmed, see ReactRouterDOMShim.js for more details import { Switch, Route } from 'react-router-dom' import DelegateMarkdownLinks from './DelegateMarkdownLinks' import Home from './Home' import Environment from './Environment' const base = document.querySelector('base') const baseHref = base ? base.getAttribute('href') : '/' const App = () => ( <BrowserRouter basename={baseHref.replace(/\/$/, '')}> <DelegateMarkdownLinks> <Switch> <Route path="/" exact={true} component={Home}/> <Route path="/:environment" component={Environment}/> </Switch> </DelegateMarkdownLinks> </BrowserRouter> ) export default App
web/src/templates/blog-list.js
ajmalafif/ajmalafif.com
import React from 'react' import { graphql } from 'gatsby' import { mapEdgesToNodes, filterOutDocsWithoutSlugs, filterOutDocsPublishedInTheFuture, } from '../lib/helpers' import BlogPostPreviewGrid from '../components/blog-post-preview-grid' import GraphQLErrorList from '../components/graphql-error-list' import tw, { theme, css } from 'twin.macro' import Layout from '../containers/layout' import { Helmet } from 'react-helmet' export const query = graphql` query BlogListTemplateQuery($skip: Int!, $limit: Int!) { site { siteMetadata { siteUrl title } } file(relativePath: { eq: "og-image.jpg" }) { childImageSharp { fluid(maxWidth: 1024, quality: 100) { ...GatsbyImageSharpFluid } } } posts: allSanityPost( sort: { fields: [publishedAt], order: DESC } filter: { slug: { current: { ne: null } }, publishedAt: { ne: null } } limit: $limit skip: $skip ) { edges { node { id publishedAt mainImage { ...ImageWithPreview caption alt } title _rawExcerpt slug { current } } } } } ` const BlogListTemplate = (props) => { const { data, errors, pageContext } = props if (errors) { return ( <Layout> <GraphQLErrorList errors={errors} /> </Layout> ) } const postNodes = data && data.posts && mapEdgesToNodes(data.posts) .filter(filterOutDocsWithoutSlugs) .filter(filterOutDocsPublishedInTheFuture) const site = data.site const siteTitle = site.siteMetadata.title const domain = site.siteMetadata.siteUrl const desc = 'Open notes from my learnings and personal reflections I feel worth sharing. I write them for future references and as a way to process my thoughts. These notes are intended to be revisited and read as work-in-progress.' return ( <Layout> <Helmet htmlAttributes={{ lang: 'en', }} title={`Notes · ${siteTitle}`} > <meta name="description" content={desc} /> <meta name="image" content={`${domain}${data.file.childImageSharp.fluid.src}`} /> <meta name="twitter:title" content={`Notes · ${siteTitle}`} /> <meta name="twitter:description" content={desc} /> <meta property="twitter:image" content={`${domain}${data.file.childImageSharp.fluid.src}`} /> <meta property="twitter:card" content="summary" /> <meta name="og:title" content={`Notes · ${siteTitle}`} /> <meta name="og:description" content={desc} /> <meta property="og:image" content={`${domain}${data.file.childImageSharp.fluid.src}`} /> <meta name="og:type" content="website" /> </Helmet> <section tw="w-full"> <div tw="mt-5 pt-5 md:mt-16 md:pt-20 mx-6 md:mx-auto grid grid-cols-1 md:grid-cols-2 font-serif pb-10 md:pb-16 border-b " css={{ width: 'min(1024px, calc(100% - 48px))', gridRowGap: 8, borderColor: `${theme`borderColor.accent`}`, }} > <h1 tw="text-3xl lg:text-4xl col-span-1 font-semibold ">Personal Notes</h1> <p tw="col-span-1 text-softer prose lg:prose-lg xl:prose-xl"> {desc} </p> </div> </section> {postNodes && postNodes.length > 0 && ( <BlogPostPreviewGrid pageContext={pageContext} nodes={postNodes} /> )} </Layout> ) } export default BlogListTemplate
public/app/components/online-tab/details-component-binding.js
vincent-tr/mylife-home-studio
'use strict'; import React from 'react'; import * as mui from 'material-ui'; import icons from '../icons'; const DetailsComponentBinding = ({ binding }) => ( <div> <icons.Binding style={{verticalAlign: 'middle'}}/> &nbsp; Binding: &nbsp; {`${binding.remote_id}.${binding.remote_attribute}`} &nbsp; -> &nbsp; {binding.local_action} <mui.Divider /> </div> ); DetailsComponentBinding.propTypes = { binding: React.PropTypes.object.isRequired }; export default DetailsComponentBinding;
UI/app/components/Dashboard.js
Acheron-VAF/Acheron
// @flow import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import styles from './Home.css'; type Props = { increment: () => void, incrementIfOdd: () => void, incrementAsync: () => void, decrement: () => void, counter: number }; export default class PageTemplate extends Component<Props> { props: Props; render() { const { increment, incrementIfOdd, incrementAsync, decrement, counter } = this.props; return ( <div className={styles.menucontainer}> settings </div> ); } }
src/components/Paralax/Paralax/Paralax.js
easingthemes/notamagic
import React from 'react'; import { Parallax as ParallaxComponent } from 'react-parallax'; import { Link } from 'react-router'; import bgImage from '../images/parallax.jpg'; const Parallax = (props) => ( <ParallaxComponent id="info-1" className={'pt50 pb50 parallax-window mt' + props.mt} bgImage={bgImage} strength={400} > <div className="container"> <div className="row pt75"> <div className="col-md-12 text-center"> <h1 className="color-light"> <small className="color-light"> Do you need more information about my skills and experience? </small> Communication is key to Success </h1> <Link to="/contact" className="button button-md button-blue hover-ripple-out mt25 mr25"> Contact me </Link> <a href="/portfolio.pdf" download="Dragan-Filipovic_FrontendDeveloper.pdf" className="button-o button-md button-green hover-fade mt25" > <span className="color-light">Download PDF CV</span> </a> </div> </div> </div> </ParallaxComponent> ); Parallax.propTypes = { mt: React.PropTypes.number }; Parallax.defaultProps = { mt: 0 }; export default Parallax;
node_modules/eslint-config-airbnb/test/test-react-order.js
ichbinder/homeapp
import test from 'tape'; import { CLIEngine } from 'eslint'; import eslintrc from '../'; import reactRules from '../rules/react'; import reactA11yRules from '../rules/react-a11y'; const cli = new CLIEngine({ useEslintrc: false, baseConfig: eslintrc, // This rule fails when executing on text. rules: { indent: 0 }, }); function lint(text) { // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeontext const linter = cli.executeOnText(text); return linter.results[0]; } function wrapComponent(body) { return ` import React from 'react'; export default class MyComponent extends React.Component { /* eslint no-empty-function: 0 */ ${body} } `; } test('validate react prop order', (t) => { t.test('make sure our eslintrc has React and JSX linting dependencies', (t) => { t.plan(2); t.deepEqual(reactRules.plugins, ['react']); t.deepEqual(reactA11yRules.plugins, ['jsx-a11y', 'react']); }); t.test('passes a good component', (t) => { t.plan(3); const result = lint(wrapComponent(` componentWillMount() {} componentDidMount() {} setFoo() {} getFoo() {} setBar() {} someMethod() {} renderDogs() {} render() { return <div />; } `)); t.notOk(result.warningCount, 'no warnings'); t.notOk(result.errorCount, 'no errors'); t.deepEquals(result.messages, [], 'no messages in results'); }); t.test('order: when random method is first', t => { t.plan(2); const result = lint(wrapComponent(` someMethod() {} componentWillMount() {} componentDidMount() {} setFoo() {} getFoo() {} setBar() {} renderDogs() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort'); }); t.test('order: when random method after lifecycle methods', t => { t.plan(2); const result = lint(wrapComponent(` componentWillMount() {} componentDidMount() {} someMethod() {} setFoo() {} getFoo() {} setBar() {} renderDogs() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort'); }); });
app/javascript/mastodon/features/lists/index.js
Craftodon/Craftodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import { fetchLists } from '../../actions/lists'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ColumnLink from '../ui/components/column_link'; import ColumnSubheading from '../ui/components/column_subheading'; import NewListForm from './components/new_list_form'; import { createSelector } from 'reselect'; const messages = defineMessages({ heading: { id: 'column.lists', defaultMessage: 'Lists' }, subheading: { id: 'lists.subheading', defaultMessage: 'Your lists' }, }); const getOrderedLists = createSelector([state => state.get('lists')], lists => { if (!lists) { return lists; } return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title'))); }); const mapStateToProps = state => ({ lists: getOrderedLists(state), }); @connect(mapStateToProps) @injectIntl export default class Lists extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, lists: ImmutablePropTypes.list, intl: PropTypes.object.isRequired, }; componentWillMount () { this.props.dispatch(fetchLists()); } render () { const { intl, lists } = this.props; if (!lists) { return ( <Column> <LoadingIndicator /> </Column> ); } return ( <Column icon='bars' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <NewListForm /> <div className='scrollable'> <ColumnSubheading text={intl.formatMessage(messages.subheading)} /> {lists.map(list => <ColumnLink key={list.get('id')} to={`/timelines/list/${list.get('id')}`} icon='bars' text={list.get('title')} /> )} </div> </Column> ); } }
src/components/video_detail.js
kahlilashanti/react_youtube_project
import React from 'react'; const VideoDetail = ({video}) => { if(!video){ return <div>Hold yer horses...</div>; } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9" > <iframe className="embed-responsive-item" src={url}></iframe> </div> <div className="details"> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ) }; export default VideoDetail;
docs/src/app/components/pages/components/DatePicker/ExampleInternational.js
rscnt/material-ui
import React from 'react'; import DatePicker from 'material-ui/DatePicker'; import areIntlLocalesSupported from 'intl-locales-supported'; let DateTimeFormat; /** * Use the native Intl.DateTimeFormat if available, or a polyfill if not. */ if (areIntlLocalesSupported(['fr', 'en-US'])) { DateTimeFormat = global.Intl.DateTimeFormat; } else { const IntlPolyfill = require('intl'); DateTimeFormat = IntlPolyfill.DateTimeFormat; require('intl/locale-data/jsonp/fr'); require('intl/locale-data/jsonp/en-US'); } const DatePickerExampleInternational = () => ( <div> <DatePicker hintText="fr locale" DateTimeFormat={DateTimeFormat} okLabel="OK" cancelLabel="Annuler" locale="fr" /> <DatePicker hintText="en-US locale" DateTimeFormat={DateTimeFormat} locale="en-US" firstDayOfWeek={0} /> <DatePicker hintText="Custom date format" firstDayOfWeek={0} formatDate={new DateTimeFormat('en-US', { day: 'numeric', month: 'long', year: 'numeric', }).format} /> </div> ); export default DatePickerExampleInternational;
frontend/src/Components/Form/CaptchaInputConnector.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { getCaptchaCookie, refreshCaptcha, resetCaptcha } from 'Store/Actions/captchaActions'; import CaptchaInput from './CaptchaInput'; function createMapStateToProps() { return createSelector( (state) => state.captcha, (captcha) => { return captcha; } ); } const mapDispatchToProps = { refreshCaptcha, getCaptchaCookie, resetCaptcha }; class CaptchaInputConnector extends Component { // // Lifecycle componentDidUpdate(prevProps) { const { name, token, onChange } = this.props; if (token && token !== prevProps.token) { onChange({ name, value: token }); } } componentWillUnmount = () => { this.props.resetCaptcha(); } // // Listeners onRefreshPress = () => { const { provider, providerData } = this.props; this.props.refreshCaptcha({ provider, providerData }); } onCaptchaChange = (captchaResponse) => { // If the captcha has expired `captchaResponse` will be null. // In the event it's null don't try to get the captchaCookie. // TODO: Should we clear the cookie? or reset the captcha? if (!captchaResponse) { return; } const { provider, providerData } = this.props; this.props.getCaptchaCookie({ provider, providerData, captchaResponse }); } // // Render render() { return ( <CaptchaInput {...this.props} onRefreshPress={this.onRefreshPress} onCaptchaChange={this.onCaptchaChange} /> ); } } CaptchaInputConnector.propTypes = { provider: PropTypes.string.isRequired, providerData: PropTypes.object.isRequired, name: PropTypes.string.isRequired, token: PropTypes.string, onChange: PropTypes.func.isRequired, refreshCaptcha: PropTypes.func.isRequired, getCaptchaCookie: PropTypes.func.isRequired, resetCaptcha: PropTypes.func.isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(CaptchaInputConnector);
src/CameraView.js
AppADay/AppADayApp
import React, { Component } from 'react'; import { StyleSheet, Text, View, Platform, TouchableOpacity, Image, Animated, Easing, InteractionManager, } from 'react-native'; import Emoji from 'react-native-emoji'; import Camera from 'react-native-camera'; import fs from 'react-native-fs'; import idx from 'idx'; import { VISION_API_KEY as API_KEY } from './constants'; const fruits = { pineapple: require('./../assets/pineapple.png'), apple: require('./../assets/apple.png'), banana: require('./../assets/banana.png'), ['banana family']: require('./../assets/banana.png'), pear: require('./../assets/pear.png'), orange: require('./../assets/orange.png'), citrus: require('./../assets/orange.png'), lemon: require('./../assets/orange.png'), poo: require('./../assets/poo.png'), }; const fruitMatch = { pineapple: 'pineapple', apple: 'apple', banana: 'banana', ['banana family']: 'banana', pear: 'pear', orange: 'orange', citrus: 'orange', lemon: 'orange', }; const getRealImagePath = path => { if (Platform.OS === 'ios') return path; const matches = path.match(/^file:\/{2}(.+\.jpg)$/); return matches[1] || path; }; const retrieveBase64ImageFromStorage = imagePath => { const path = getRealImagePath(imagePath); if (path && fs.exists(path)) { return Promise.resolve().then(() => fs.readFile(path, 'base64')); } return null; }; const analyzeImage = base64Image => { if (!base64Image) return null; return Promise.resolve() .then(() => fetch(`https://vision.googleapis.com/v1/images:annotate?key=${API_KEY}`, { method: 'POST', body: JSON.stringify({ requests: [ { image: { content: base64Image, }, features: [ { type: 'LABEL_DETECTION', maxResults: 5, }, ], }, ], }), }), ) .then(response => response.json()); }; const blackList = [ 'produce', 'fruit', 'food', 'local food', 'still life', 'cooking plantain', 'yuzu', ]; const filterResults = response => { const results = idx(response, _ => _.responses[0].labelAnnotations); const filtered = results.filter( result => !blackList.includes(result.description.toLowerCase()), ); return filtered.map(item => item.description); }; export default class CameraView extends Component { state = { bounceValue: new Animated.Value(0), rotateValue: new Animated.Value(0), translateValue: new Animated.ValueXY({ x: 0, y: 0 }), // 二维坐标 fadeOutOpacity: new Animated.Value(0), startFadeOut: new Animated.Value(0), startMoveIn: new Animated.Value(0), resultImage: 'poo', isShowingResultImage: false, score: { pineapple: false, apple: false, banana: false, pear: false, orange: false, }, }; takePicture = () => { const options = {}; //options.location = ... this.camera .capture({ metadata: options, jpegQuality: 95 }) .then(data => retrieveBase64ImageFromStorage(data.path)) .then(image => analyzeImage(image)) .then(response => filterResults(response)) .then(filteredResults => this.showAnimation(filteredResults)) .catch(err => console.error(err)); }; sendLoserPost = () => { return Promise.resolve() .then(() => fetch(`http://be332e2a.ngrok.io/loser`, { method: 'POST', headers: { 'Content-Type': 'application/json', // 'Accept': 'application/json', // 'Access-Key': 'myAccessKey', // use in future for safer requests }, body: JSON.stringify({ email1: 'bla', }), }), ) .then(response => response.json()); }; sendLoser = () => { return Promise.resolve() .then(() => fetch(`http://be332e2a.ngrok.io/loser`, { method: 'GET', }), ) .then(response => response.json()); }; showAnimation = resultArray => { const result = resultArray.length ? resultArray[0] : 'poo'; const possibleFruits = Object.keys(fruits); console.log({ resultArray, result, possibleFruits }); if (possibleFruits.includes(result)) { // Fruit animation this.setState( { resultImage: result, score: { ...this.state.score, [fruitMatch[result]]: true, }, }, this.startAnimation, ); } else { // Shit animation this.setState({ resultImage: 'poo' }, this.startAnimation); // send request out! this.sendLoser(); } return null; }; startAnimation = () => { this.setState({ isShowingResultImage: true }); console.log({ state: this.state }); this.state.bounceValue.setValue(1.5); // 设置一个较大的初始值 this.state.rotateValue.setValue(0); this.state.translateValue.setValue({ x: 10, y: 10 }); this.state.fadeOutOpacity.setValue(1); Animated.sequence([ Animated.sequence([ Animated.spring( // the this.state.bounceValue, { toValue: 0.8, friction: 3, // defaut:7. tension: 40, //maximal }, ), Animated.delay(1000), Animated.timing(this.state.rotateValue, { toValue: 1, duration: 600, // defaut 500ms easing: Easing.out(Easing.quad), // 一个用于定义曲线的渐变函数 }), Animated.decay( // S=vt-(at^2)/2 v=v - at this.state.translateValue, { velocity: 100, // 起始速度,必填参数。 deceleration: 0.8, // 速度衰减比例,默认为0.997。 }, ), ]), Animated.timing(this.state.fadeOutOpacity, { toValue: 0, duration: 1000, easing: Easing.linear, // 线性的渐变函数 }), ]).start(() => this.setState({ isShowingResultImage: false })); // no cricle }; bannerAnimation = () => { Animated.sequence([ Animated.timing(this.state.startMoveIn, { toValue: 1, duration: 2500, easing: Easing.out(Easing.quad), delay: 6000, }), Animated.timing(this.state.startFadeOut, { toValue: 1, duration: 3000, easing: Easing.linear, }), ]).start(); }; renderCheckMark = name => this.state.score[name] ? ( <Image style={styles.checkMark} source={require('./../assets/checkmark.png')} /> ) : null; componentDidMount() { // animation InteractionManager.runAfterInteractions(() => setTimeout(() => {}, 2000)); this.bannerAnimation(); } render() { const { score } = this.state; return ( <View style={styles.container}> <Camera ref={cam => { this.camera = cam; }} style={styles.preview} aspect={Camera.constants.Aspect.fill} captureQuality={Camera.constants.CaptureQuality.low} > <View style={styles.buttonWrapper}> <TouchableOpacity style={styles.button} onPress={this.takePicture}> <View style={styles.buttonOuter}> <View style={styles.buttonInner} /> </View> </TouchableOpacity> </View> </Camera> <View style={styles.emojiBar}> <View> <Image style={{ opacity: score.pineapple ? 1 : 0.6, width: 80, height: 80, marginRight: 5, }} source={fruits.pineapple} /> {this.renderCheckMark('pineapple')} </View> <View> <Image style={{ opacity: score.apple ? 1 : 0.6, width: 75, height: 75, marginRight: 5, }} source={fruits.apple} /> {this.renderCheckMark('apple')} </View> <View> <Image style={{ opacity: score.banana ? 1 : 0.6, width: 70, height: 70, marginLeft: 15, }} source={fruits.banana} /> {this.renderCheckMark('banana')} </View> <View> <Image style={{ opacity: score.pear ? 1 : 0.6, width: 70, height: 70, }} source={fruits.pear} /> {this.renderCheckMark('pear')} </View> <View> <Image style={{ opacity: score.orange ? 1 : 0.6, width: 70, height: 70, marginLeft: 5, }} source={fruits.orange} /> {this.renderCheckMark('orange')} </View> </View> <Animated.View style={{ position: 'absolute', top: this.state.startMoveIn.interpolate({ inputRange: [0, 1], outputRange: [-70, 140], }), left: 0, right: 0, justifyContent: 'center', alignItems: 'center', opacity: this.state.startFadeOut.interpolate({ inputRange: [0, 1], outputRange: [1, 0], }), }} > <View style={styles.challengeTitle}> <Image source={require('./../assets/camera_TropicalChallenge.png')} /> </View> </Animated.View> {this.state.isShowingResultImage ? ( <View style={{ ...StyleSheet.absoluteFillObject, justifyContent: 'center', alignItems: 'center', }} > <Animated.View style={{ transform: [ { scale: this.state.bounceValue }, // 缩放 { rotate: this.state.rotateValue.interpolate({ // 旋转, inputRange: [0, 1], outputRange: ['0deg', '180deg'], }), }, { translateX: this.state.translateValue.x }, // x轴移动 { translateY: this.state.translateValue.y }, // y轴移动 ], opacity: this.state.fadeOutOpacity, // 透明度 }} > <Image source={fruits[this.state.resultImage]} style={{ width: 200, height: 200 }} /> </Animated.View> </View> ) : null} </View> ); } } const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, flex: 1, // alignItems: 'center', // justifyContent: 'center', }, emojiBar: { position: 'absolute', top: 30, left: 0, right: 0, flexDirection: 'row', justifyContent: 'center', }, fruit: { width: 70, height: 70, opacity: 0.6, }, preview: { flex: 1, justifyContent: 'flex-end', alignItems: 'center', }, capture: { flex: 0, padding: 10, margin: 40, fontSize: 160, }, buttonWrapper: { alignItems: 'center', }, button: { position: 'absolute', bottom: 70, }, buttonOuter: { flex: 1, padding: 10, backgroundColor: '#ED7D7D', borderRadius: 50, width: 80, height: 80, justifyContent: 'center', alignItems: 'center', }, buttonInner: { width: 66, height: 66, borderRadius: 50, borderWidth: 3, borderColor: 'white', }, challengeWrapper: { position: 'absolute', top: 130, left: 0, right: 0, justifyContent: 'center', alignItems: 'center', }, challengeTitle: {}, checkMark: { position: 'absolute', right: 20, top: 10, width: 55, height: 55, }, });
client/src/components/city/city-view.js
BrunoSalerno/citylines
import React from 'react'; import Translate from 'react-translate-component'; import CityBase from '../city-base'; import PropTypes from 'prop-types'; import CityViewStore from '../../stores/city-view-store'; import MainStore from '../../stores/main-store'; import {PanelHeader, PanelBody} from '../panel'; import LinesTree from './lines-tree'; import Year from './year'; import KmIndicator from './km-indicator'; import Tags from '../tags'; import CitySettings from './settings'; import CityToggleableContainer from './toggleable-container'; import Share from '../share'; class CityView extends CityBase { constructor(props, context) { super(props, context); this.urlName = this.props.match.params.city_url_name; this.bindedOnChange = this.onChange.bind(this); this.bindedOnYearChange = this.onYearChange.bind(this); this.bindedOnLineToggle = this.onLineToggle.bind(this); this.bindedOnAllLinesToggle = this.onAllLinesToggle.bind(this); this.bindedHandleSpeedChange = this.handleSpeedChange.bind(this) } onChange() { this.setState(CityViewStore.getState(this.urlName)); } componentDidMount() { CityViewStore.addChangeListener(this.bindedOnChange); MainStore.setLoading(); CityViewStore.load(this.urlName, this.params()).then(() => { MainStore.unsetLoading(); }); } componentWillUnmount() { CityViewStore.unload(this.urlName); CityViewStore.removeChangeListener(this.bindedOnChange); } componentDidUpdate(prevProps, prevState) { if (!prevState) return; if (prevState.linesShown.length != this.state.linesShown.length) { this.onLinesShownChange(); } } onYearChange() { if (this.state.playing) return; const newYear = this.state.currentYear; this.updateParams({year: newYear}); CityViewStore.setKmYear(this.urlName, newYear, null); } onLineToggle(lineUrlName) { CityViewStore.toggleLine(this.urlName, lineUrlName); } onAllLinesToggle(system_id, checked) { CityViewStore.toggleAllLines(this.urlName, system_id, checked); } onLinesShownChange() { let linesShown; if (this.state.linesShown.length == this.state.lines.length) { linesShown = null; } else { linesShown = this.state.linesShown.join(','); } // An update in the lines parameter should remove the system_id param this.updateParams({lines: linesShown, system_id: null}); } handleSpeedChange(speed) { this.updateParams({speed: speed}); CityViewStore.setSpeed(this.urlName, speed); } handleTransportModesChange(e) { CityViewStore.setShowTransportModes(this.urlName, e.target.checked); } selectedSystem() { // TODO: shall this be deprecated in favour of the systems param? // (which allow multiple system?) const systemId = parseInt(this.params().system_id); return this.state.systems.find(s => s.id == systemId); } cityTitle() { return <Tags title="city.title" description="city.description" interpolations={{city: this.context.cityName}} /> } systemTitle() { const system = this.selectedSystem(); if (!system) return; const interpolations = { city: this.context.cityName, system: system.name } return <Tags title="city.system_title" description="city.description" interpolations={interpolations} /> } systemIndicator() { const system = this.selectedSystem(); if (!system) return; return <div className="system-indicator"> <div className="system-indicator-name">{system.name}</div> <div className="system-indicator-link"> <a className="c-link" onClick={(e) => {e.preventDefault(); CityViewStore.showAllSystems(this.urlName);}} > <Translate content="city.show_all_systems" /> </a> </div> </div> } render() { if (!this.state) return null; return ( <PanelBody> { this.params().system_id ? this.systemTitle() : this.cityTitle()} { this.params().system_id && this.systemIndicator() } { this.props.displaySettings && <CitySettings speed={this.state.speed} onSpeedChange={this.bindedHandleSpeedChange} showTransportModes={this.state.showTransportModes} i onShowTransportModesChange={this.handleTransportModesChange.bind(this)} /> } { this.props.displayShare && <CityToggleableContainer><Share /></CityToggleableContainer>} <div className="year-and-km-container"> <Year urlName={this.urlName} min={(this.state.years || {}).start} max={(this.state.years || {}).end} year={this.state.currentYear} playing={this.state.playing} onYearChange={this.bindedOnYearChange} /> <KmIndicator kmOperative={this.state.kmOperative} kmUnderConstruction={this.state.kmUnderConstruction} /> </div> { this.state.systems.map((system) => { const systemLines = this.state.lines.filter(line => line.system_id == system.id); return systemLines.length ? <LinesTree key={system.id} system={system} defaultExpanded={true} lines={systemLines} linesShown={this.state.linesShown} transportModes={this.state.transportModes} showTransportModes={this.state.showTransportModes} onLineToggle={this.bindedOnLineToggle} onAllLinesToggle={this.bindedOnAllLinesToggle} /> : null }) } </PanelBody> ) } } CityView.contextTypes = { cityName: PropTypes.string } export default CityView
src/containers/OverBar.js
zachlevy/react-playground
import React from 'react' import { connect } from 'react-redux' import { setTheme } from '../actions' const mapStateToProps = (state, ownProps) => ({ theme: state.theme }) let OverBar = ({ theme, dispatch }) => { let input const handleOnSubmit = (e) => { e.preventDefault() if (!input.value.trim()) { return } dispatch(setTheme(input.value)) console.log("switch theme with query") document.querySelector('body').className = `theme-${input.value}` document.querySelector('html').className = `theme-${input.value}` input.value = '' } return ( <nav className="navbar navbar-inverse navbar-fixed-top"> <div className="container"> <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <a className="navbar-brand" href="#">Dice</a> </div> <div id="navbar" className="collapse navbar-collapse"> <div className="form-group"> <form className="navbar-form" onSubmit={handleOnSubmit}> <ul className="nav navbar-nav"> <li> <input className="form-control" ref={node => { input = node }} /> </li> <li> <button className="btn btn-primary" type="submit"> Set Theme </button> </li> </ul> </form> </div> </div> </div> </nav> ) } OverBar = connect( mapStateToProps )(OverBar) export default OverBar
src/DatePicker/DateDisplay.spec.js
lawrence-yu/material-ui
/* eslint-env mocha */ import React from 'react'; import {shallow} from 'enzyme'; import {assert} from 'chai'; import getMuiTheme from '../styles/getMuiTheme'; import {dateTimeFormat} from './dateUtils'; import DateDisplay from './DateDisplay'; describe('<DateDisplay />', () => { const muiTheme = getMuiTheme(); const shallowWithContext = (node) => shallow(node, {context: {muiTheme}}); describe('i18n', () => { it('should format the date correctly', () => { const date = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT const wrapper = shallowWithContext( <DateDisplay selectedDate={date} DateTimeFormat={dateTimeFormat} locale="en-US" /> ); assert.strictEqual(wrapper.find('div').at(1).text(), '2015'); assert.strictEqual(wrapper.find('div').at(2).text(), 'Tue, Dec 1'); }); }); });
app/javascript/mastodon/features/notifications/components/column_settings.js
dunn/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { FormattedMessage } from 'react-intl'; import ClearColumnButton from './clear_column_button'; import SettingToggle from './setting_toggle'; export default class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, pushSettings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, onClear: PropTypes.func.isRequired, }; onPushChange = (path, checked) => { this.props.onChange(['push', ...path], checked); } render () { const { settings, pushSettings, onChange, onClear } = this.props; const filterShowStr = <FormattedMessage id='notifications.column_settings.filter_bar.show' defaultMessage='Show' />; const filterAdvancedStr = <FormattedMessage id='notifications.column_settings.filter_bar.advanced' defaultMessage='Display all categories' />; const alertStr = <FormattedMessage id='notifications.column_settings.alert' defaultMessage='Desktop notifications' />; const showStr = <FormattedMessage id='notifications.column_settings.show' defaultMessage='Show in column' />; const soundStr = <FormattedMessage id='notifications.column_settings.sound' defaultMessage='Play sound' />; const showPushSettings = pushSettings.get('browserSupport') && pushSettings.get('isSubscribed'); const pushStr = showPushSettings && <FormattedMessage id='notifications.column_settings.push' defaultMessage='Push notifications' />; return ( <div> <div className='column-settings__row'> <ClearColumnButton onClick={onClear} /> </div> <div role='group' aria-labelledby='notifications-filter-bar'> <span id='notifications-filter-bar' className='column-settings__section'> <FormattedMessage id='notifications.column_settings.filter_bar.category' defaultMessage='Quick filter bar' /> </span> <div className='column-settings__row'> <SettingToggle id='show-filter-bar' prefix='notifications' settings={settings} settingPath={['quickFilter', 'show']} onChange={onChange} label={filterShowStr} /> <SettingToggle id='show-filter-bar' prefix='notifications' settings={settings} settingPath={['quickFilter', 'advanced']} onChange={onChange} label={filterAdvancedStr} /> </div> </div> <div role='group' aria-labelledby='notifications-follow'> <span id='notifications-follow' className='column-settings__section'><FormattedMessage id='notifications.column_settings.follow' defaultMessage='New followers:' /></span> <div className='column-settings__row'> <SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'follow']} onChange={onChange} label={alertStr} /> {showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'follow']} onChange={this.onPushChange} label={pushStr} />} <SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'follow']} onChange={onChange} label={showStr} /> <SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'follow']} onChange={onChange} label={soundStr} /> </div> </div> <div role='group' aria-labelledby='notifications-follow-request'> <span id='notifications-follow-request' className='column-settings__section'><FormattedMessage id='notifications.column_settings.follow_request' defaultMessage='New follow requests:' /></span> <div className='column-settings__row'> <SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'follow_request']} onChange={onChange} label={alertStr} /> {showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'follow_request']} onChange={this.onPushChange} label={pushStr} />} <SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'follow_request']} onChange={onChange} label={showStr} /> <SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'follow_request']} onChange={onChange} label={soundStr} /> </div> </div> <div role='group' aria-labelledby='notifications-favourite'> <span id='notifications-favourite' className='column-settings__section'><FormattedMessage id='notifications.column_settings.favourite' defaultMessage='Favourites:' /></span> <div className='column-settings__row'> <SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'favourite']} onChange={onChange} label={alertStr} /> {showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'favourite']} onChange={this.onPushChange} label={pushStr} />} <SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'favourite']} onChange={onChange} label={showStr} /> <SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'favourite']} onChange={onChange} label={soundStr} /> </div> </div> <div role='group' aria-labelledby='notifications-mention'> <span id='notifications-mention' className='column-settings__section'><FormattedMessage id='notifications.column_settings.mention' defaultMessage='Mentions:' /></span> <div className='column-settings__row'> <SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'mention']} onChange={onChange} label={alertStr} /> {showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'mention']} onChange={this.onPushChange} label={pushStr} />} <SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'mention']} onChange={onChange} label={showStr} /> <SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'mention']} onChange={onChange} label={soundStr} /> </div> </div> <div role='group' aria-labelledby='notifications-reblog'> <span id='notifications-reblog' className='column-settings__section'><FormattedMessage id='notifications.column_settings.reblog' defaultMessage='Boosts:' /></span> <div className='column-settings__row'> <SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'reblog']} onChange={onChange} label={alertStr} /> {showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'reblog']} onChange={this.onPushChange} label={pushStr} />} <SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'reblog']} onChange={onChange} label={showStr} /> <SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'reblog']} onChange={onChange} label={soundStr} /> </div> </div> <div role='group' aria-labelledby='notifications-poll'> <span id='notifications-poll' className='column-settings__section'><FormattedMessage id='notifications.column_settings.poll' defaultMessage='Poll results:' /></span> <div className='column-settings__row'> <SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'poll']} onChange={onChange} label={alertStr} /> {showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'poll']} onChange={this.onPushChange} label={pushStr} />} <SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'poll']} onChange={onChange} label={showStr} /> <SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'poll']} onChange={onChange} label={soundStr} /> </div> </div> </div> ); } }
src/components/register/v1/form-field.js
Lokiedu/libertysoil-site
/* This file is a part of libertysoil.org website Copyright (C) 2017 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import PropTypes from 'prop-types'; import React from 'react'; import omit from 'lodash/omit'; import MESSAGE_TYPES from '../../../consts/messageTypeConstants'; import Message from '../../message'; export default class RegisterFormV1Field extends React.PureComponent { static propTypes = { error: PropTypes.string, name: PropTypes.string, refFn: PropTypes.func, title: PropTypes.string, type: PropTypes.string, warn: PropTypes.string }; static defaultProps = { type: 'text' }; render() { const { error, name, warn } = this.props; return ( <div className="layout__row layout__row-double"> <label className="label label-before_input label-space" htmlFor={name}> {this.props.title} </label> <input className="input input-gray input-big input-block" id={name} name={name} ref={this.props.refFn} type={this.props.type} {...omit(this.props, KNOWN_PROPS)} /> {error && <Message message={error} type={MESSAGE_TYPES.ERROR} /> } {warn && <Message message={warn} type={MESSAGE_TYPES.INFO} /> } </div> ); } } const KNOWN_PROPS = Object.keys(RegisterFormV1Field.propTypes);
client/src/components/profile_page/ProfilePage.js
thewizardplusplus/vk-group-stats
import React from 'react' import {DrivedProfile} from '../../containers/drived_profile/DrivedProfile' export default class ProfilePage extends React.Component { render() { return <DrivedProfile /> } }
src/svg-icons/editor/format-paint.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatPaint = (props) => ( <SvgIcon {...props}> <path d="M18 4V3c0-.55-.45-1-1-1H5c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V6h1v4H9v11c0 .55.45 1 1 1h2c.55 0 1-.45 1-1v-9h8V4h-3z"/> </SvgIcon> ); EditorFormatPaint = pure(EditorFormatPaint); EditorFormatPaint.displayName = 'EditorFormatPaint'; EditorFormatPaint.muiName = 'SvgIcon'; export default EditorFormatPaint;
src/js/screens/Anchor.js
grommet/next-sample
import React from 'react'; import { Anchor, Box } from 'grommet'; import doc from 'grommet/components/Anchor/doc'; import { Edit } from 'grommet-icons'; import Doc from '../components/Doc'; const desc = doc(Anchor).toJSON(); function onClick(event) { event.preventDefault(); alert('hi'); } export default () => ( <Doc name='Anchor' desc={desc}> <Box pad='large' align='start'> <Box margin='small'> <Anchor href='#' onClick={onClick}> Child text </Anchor> </Box> <Box margin='small'> <Anchor href='#' label='Label' primary={true} onClick={onClick} /> </Box> <Box margin='small'> <Anchor href='#' icon={<Edit />} label='Label' onClick={onClick} /> </Box> <Box margin='small'> <Anchor href='#' icon={<Edit />} label='Reverse' reverse={true} onClick={onClick} /> </Box> <Box margin='small'> <Anchor href='#' icon={<Edit />} label='Disabled' disabled={true} onClick={onClick} /> </Box> <Box margin='small'> <Anchor href='#' icon={<Edit />} onClick={onClick} /> </Box> </Box> </Doc> );
rojak-ui-web/src/App.js
bobbypriambodo/rojak
import React from 'react'; import { Provider } from 'react-redux'; import { ReduxRouter } from 'redux-router'; import routes from './routes'; import store from './store'; import createRojakClient from './app/utils/createRojakClient'; class App extends React.Component { static childContextTypes = { rojakClient: React.PropTypes.object, } getChildContext() { return { rojakClient: createRojakClient(process.env.ROJAK_API_ENDPOINT), } } render() { return ( <Provider store={store}> <ReduxRouter routes={routes} /> </Provider> ); } } export default App;
packages/cockpit/ui/src/components/Pagination.js
iurimatias/embark-framework
import React from 'react'; import {Pagination as RPagination, PaginationItem, PaginationLink} from 'reactstrap'; import PropTypes from 'prop-types'; const NB_PAGES_MAX = 8; const Pagination = ({currentPage, numberOfPages, changePage}) => { let max = currentPage + NB_PAGES_MAX / 2; if (max > numberOfPages) { max = numberOfPages; } let i = max - NB_PAGES_MAX; if (i < 1) { i = 1; } const pageNumbers = []; for (i; i <= max; i++) { pageNumbers.push(i); } return ( <RPagination aria-label="Explorer navigation" className="mt-4 mb-0 float-right"> <PaginationItem disabled={currentPage <= 1}> <PaginationLink previous href="#" onClick={(e) => { e.preventDefault(); changePage(currentPage - 1); }}/> </PaginationItem> {pageNumbers.map(number => (<PaginationItem active={currentPage === number} key={'page-' + number}> <PaginationLink href="#" onClick={(e) => { e.preventDefault(); changePage(number); }}> {number} </PaginationLink> </PaginationItem>))} <PaginationItem disabled={currentPage >= numberOfPages}> <PaginationLink next href="#" onClick={(e) => { e.preventDefault(); changePage(currentPage + 1); }}/> </PaginationItem> </RPagination> ); }; Pagination.propTypes = { numberOfPages: PropTypes.number, currentPage: PropTypes.number, changePage: PropTypes.func }; export default Pagination;
src/components/general/WebView.js
eventures-io/ldn-retail-demo
/** * Web View * * <WebView url={"http://google.com"} /> * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { WebView, StyleSheet, InteractionManager, } from 'react-native'; // Consts and Libs import { AppColors, AppStyles } from '@theme/'; // Components import Loading from '@components/general/Loading'; import Error from '@components/general/Error'; /* Styles ==================================================================== */ const styles = StyleSheet.create({ container: { backgroundColor: AppColors.background, }, }); /* Component ==================================================================== */ class AppWebView extends Component { static componentName = 'AppWebView'; static propTypes = { url: PropTypes.string.isRequired, onNavigationStateChange: PropTypes.func, } static defaultProps = { onNavigationStateChange: null, } constructor(props) { super(props); this.state = { loading: true, webViewURL: props.url || null, }; } componentDidMount = () => { // Wait until interaction has finished before loading the webview in InteractionManager.runAfterInteractions(() => { this.setState({ loading: false }); }); } /** * Each time page loads, update the URL */ onNavigationStateChange = (navState) => { this.state.webViewURL = navState.url; if (this.props.onNavigationStateChange) this.props.onNavigationStateChange(navState.url); } render = () => { const { webViewURL, loading } = this.state; if (loading) return <Loading />; if (!webViewURL) return <Error type={'URL not defined.'} />; return ( <WebView scalesPageToFit startInLoadingState source={{ uri: webViewURL }} automaticallyAdjustContentInsets={false} style={[AppStyles.container, styles.container]} onNavigationStateChange={this.onNavigationStateChange} /> ); } } /* Export Component ==================================================================== */ export default AppWebView;
app/javascript/mastodon/features/compose/components/poll_button.js
lindwurm/mastodon
import React from 'react'; import IconButton from '../../../components/icon_button'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ add_poll: { id: 'poll_button.add_poll', defaultMessage: 'Add a poll' }, remove_poll: { id: 'poll_button.remove_poll', defaultMessage: 'Remove poll' }, }); const iconStyle = { height: null, lineHeight: '27px', }; export default @injectIntl class PollButton extends React.PureComponent { static propTypes = { disabled: PropTypes.bool, unavailable: PropTypes.bool, active: PropTypes.bool, onClick: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleClick = () => { this.props.onClick(); } render () { const { intl, active, unavailable, disabled } = this.props; if (unavailable) { return null; } return ( <div className='compose-form__poll-button'> <IconButton icon='tasks' title={intl.formatMessage(active ? messages.remove_poll : messages.add_poll)} disabled={disabled} onClick={this.handleClick} className={`compose-form__poll-button-icon ${active ? 'active' : ''}`} size={18} inverted style={iconStyle} /> </div> ); } }
webpack/scenes/AnsibleCollections/Details/AnsibleCollectionDetails.js
snagoor/katello
import React, { Component } from 'react'; import BreadcrumbsBar from 'foremanReact/components/BreadcrumbBar'; import { PropTypes } from 'prop-types'; import { translate as __ } from 'foremanReact/common/I18n'; import api from '../../../services/api'; import ContentDetails from '../../../components/Content/Details/ContentDetails'; import ansibleCollectionsSchema from './AnsibleCollectionsSchema'; class AnsibleCollectionDetails extends Component { componentDidMount() { this.updateAnsibleCollection(); } componentDidUpdate(prevProps) { const { match: { params: prevRouterParams } } = this.props; const { match: { params: currentRouterParams } } = prevProps; if (prevRouterParams.id && (prevRouterParams.id !== currentRouterParams.id)) { this.updateAnsibleCollection(); } } updateAnsibleCollection = () => { const ansibleCollectionId = parseInt(this.props.match.params.id, 10); this.props.getAnsibleCollectionDetails(ansibleCollectionId); }; handleBreadcrumbSwitcherItem = (e, url) => { this.props.history.push(url); e.preventDefault(); }; render() { const { ansibleCollectionDetails } = this.props; const { loading, name, namespace, version, } = ansibleCollectionDetails; const resource = { nameField: 'name', resourceUrl: api.getApiUrl('/ansible_collections'), switcherItemUrl: '/ansible_collections/:id', }; return ( <div> {!loading && <BreadcrumbsBar onSwitcherItemClick={(e, url) => this.handleBreadcrumbSwitcherItem(e, url)} data={{ isSwitchable: true, breadcrumbItems: [ { caption: __('Ansible Collection Details'), onClick: () => this.props.history.push('/ansible_collections'), }, { caption: `${name}-${namespace}-${version}`, }, ], resource, }} />} <ContentDetails contentDetails={ansibleCollectionDetails} schema={ansibleCollectionsSchema(ansibleCollectionDetails)} /> </div> ); } } AnsibleCollectionDetails.propTypes = { getAnsibleCollectionDetails: PropTypes.func.isRequired, history: PropTypes.shape({ push: PropTypes.func.isRequired }).isRequired, location: PropTypes.shape({}).isRequired, match: PropTypes.shape({ params: PropTypes.shape({ id: PropTypes.string.isRequired, }).isRequired, }).isRequired, ansibleCollectionDetails: PropTypes.shape({ loading: PropTypes.bool, name: PropTypes.string, namespace: PropTypes.string, version: PropTypes.string, // Disabling rule as existing code failed due to an eslint-plugin-react update /* eslint-disable react/forbid-prop-types */ repositories: PropTypes.array, tags: PropTypes.array, /* eslint-enable react/forbid-prop-types */ }).isRequired, }; export default AnsibleCollectionDetails;
docs/src/app/components/pages/components/Paper/ExampleSimple.js
nathanmarks/material-ui
import React from 'react'; import Paper from 'material-ui/Paper'; const style = { height: 100, width: 100, margin: 20, textAlign: 'center', display: 'inline-block', }; const PaperExampleSimple = () => ( <div> <Paper style={style} zDepth={1} /> <Paper style={style} zDepth={2} /> <Paper style={style} zDepth={3} /> <Paper style={style} zDepth={4} /> <Paper style={style} zDepth={5} /> </div> ); export default PaperExampleSimple;
test/specs/collections/Form/Form-test.js
Semantic-Org/Semantic-UI-React
import faker from 'faker' import _ from 'lodash' import React from 'react' import Form from 'src/collections/Form/Form' import FormButton from 'src/collections/Form/FormButton' import FormCheckbox from 'src/collections/Form/FormCheckbox' import FormDropdown from 'src/collections/Form/FormDropdown' import FormField from 'src/collections/Form/FormField' import FormGroup from 'src/collections/Form/FormGroup' import FormInput from 'src/collections/Form/FormInput' import FormRadio from 'src/collections/Form/FormRadio' import FormSelect from 'src/collections/Form/FormSelect' import FormTextArea from 'src/collections/Form/FormTextArea' import { SUI } from 'src/lib' import * as common from 'test/specs/commonTests' import { consoleUtil, sandbox } from 'test/utils' describe('Form', () => { common.isConformant(Form) common.hasSubcomponents(Form, [ FormButton, FormCheckbox, FormDropdown, FormField, FormTextArea, FormGroup, FormInput, FormRadio, FormSelect, ]) common.hasUIClassName(Form) common.rendersChildren(Form, { rendersContent: false, }) common.implementsWidthProp(Form, [], { propKey: 'widths', }) common.propKeyOnlyToClassName(Form, 'error') common.propKeyOnlyToClassName(Form, 'inverted') common.propKeyOnlyToClassName(Form, 'loading') common.propKeyOnlyToClassName(Form, 'reply') common.propKeyOnlyToClassName(Form, 'success') common.propKeyOnlyToClassName(Form, 'unstackable') common.propKeyOnlyToClassName(Form, 'warning') common.propValueOnlyToClassName(Form, 'size', _.without(SUI.SIZES, 'medium')) describe('action', () => { it('is not set by default', () => { shallow(<Form />).should.not.have.prop('action') }) it('applied when defined', () => { const action = faker.internet.url() shallow(<Form action={action} />).should.have.prop('action', action) }) }) describe('onSubmit', () => { it('prevents default on the event when there is no action', () => { // Heads up! // In this test we pass some invalid values to verify correct work. consoleUtil.disableOnce() const event = { preventDefault: sandbox.spy() } shallow(<Form />).simulate('submit', event) shallow(<Form action={false} />).simulate('submit', event) shallow(<Form action={null} />).simulate('submit', event) event.preventDefault.should.have.been.calledThrice() }) it('does not prevent default on the event when there is an action', () => { const event = { preventDefault: sandbox.spy() } shallow(<Form action='do not prevent default!' />).simulate('submit', event) shallow(<Form action='' />).simulate('submit', event) event.preventDefault.should.not.have.been.called() }) it('is called with (e, props) on submit', () => { const onSubmit = sandbox.spy() const event = { name: 'foo' } const props = { 'data-bar': 'baz' } shallow(<Form {...props} onSubmit={onSubmit} />).simulate('submit', event) onSubmit.should.have.been.calledOnce() onSubmit.should.have.been.calledWithMatch(event, props) }) it('passes all args to onSubmit', () => { const onSubmit = sandbox.spy() const props = { 'data-baz': 'baz' } const event = { fake: 'event' } const args = ['some', 'extra', 'args'] shallow(<Form {...props} onSubmit={onSubmit} />).simulate('submit', event, ...args) onSubmit.should.have.been.calledOnce() onSubmit.should.have.been.calledWithMatch(event, props, ...args) }) }) })
docs/client.js
sheep902/react-bootstrap
import 'bootstrap/less/bootstrap.less'; import './assets/docs.css'; import './assets/style.css'; import './assets/carousel.png'; import './assets/logo.png'; import './assets/favicon.ico'; import './assets/thumbnail.png'; import './assets/thumbnaildiv.png'; import 'codemirror/mode/htmlmixed/htmlmixed'; import 'codemirror/mode/javascript/javascript'; import 'codemirror/theme/solarized.css'; import 'codemirror/lib/codemirror.css'; import './assets/CodeMirror.css'; import React from 'react'; import CodeMirror from 'codemirror'; import 'codemirror/addon/runmode/runmode'; import Router from 'react-router'; import routes from './src/Routes'; global.CodeMirror = CodeMirror; Router.run(routes, Router.RefreshLocation, Handler => { React.render( React.createElement(Handler, window.INITIAL_PROPS), document); });
app/containers/LocaleToggle/index.js
zuban/zuban-boilerplate
/* * * LanguageToggle * */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import Toggle from 'components/Toggle'; import Wrapper from './Wrapper'; import messages from './messages'; import { appLocales } from '../../i18n'; import { changeLocale } from '../LanguageProvider/actions'; import { makeSelectLocale } from '../LanguageProvider/selectors'; export class LocaleToggle extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <Wrapper> <Toggle value={this.props.locale} values={appLocales} messages={messages} onToggle={this.props.onLocaleToggle} /> </Wrapper> ); } } LocaleToggle.propTypes = { onLocaleToggle: React.PropTypes.func, locale: React.PropTypes.string, }; const mapStateToProps = createSelector( makeSelectLocale(), (locale) => ({ locale }) ); export function mapDispatchToProps(dispatch) { return { onLocaleToggle: (evt) => dispatch(changeLocale(evt.target.value)), dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LocaleToggle);
src/svg-icons/av/skip-previous.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSkipPrevious = (props) => ( <SvgIcon {...props}> <path d="M6 6h2v12H6zm3.5 6l8.5 6V6z"/> </SvgIcon> ); AvSkipPrevious = pure(AvSkipPrevious); AvSkipPrevious.displayName = 'AvSkipPrevious'; AvSkipPrevious.muiName = 'SvgIcon'; export default AvSkipPrevious;
test/OverlayTriggerSpec.js
glenjamin/react-bootstrap
import PropTypes from 'prop-types'; import React from 'react'; import ReactDOM from 'react-dom'; import { mount } from 'enzyme'; import OverlayTrigger from '../src/OverlayTrigger'; import Popover from '../src/Popover'; import Tooltip from '../src/Tooltip'; describe('<OverlayTrigger>', () => { // Swallow extra props. const Div = React.forwardRef(({ className, children }, ref) => ( <div ref={ref} className={className} role="tooltip" id="test-tooltip"> {children} </div> )); it('Should render OverlayTrigger element', () => { mount( <OverlayTrigger overlay={<Div>test</Div>}> <button type="button">button</button> </OverlayTrigger>, ).assertSingle('button'); }); it('Should call OverlayTrigger onClick prop to child', () => { const callback = sinon.spy(); mount( <OverlayTrigger overlay={<Div>test</Div>} trigger="click"> <button type="button" onClick={callback}> button </button> </OverlayTrigger>, ) .find('button') .simulate('click'); callback.should.have.been.called; }); it('Should show after click trigger', () => { const wrapper = mount( <OverlayTrigger trigger="click" overlay={<Div className="test" />}> <button type="button">button</button> </OverlayTrigger>, ); wrapper.assertNone('.test'); wrapper.find('button').simulate('click'); wrapper.assertSingle('div.test'); }); it('Should not set aria-describedby if the state is not show', () => { const wrapper = mount( <OverlayTrigger trigger="click" overlay={<Div />}> <button type="button">button</button> </OverlayTrigger>, ).getDOMNode(); assert.equal(wrapper.getAttribute('aria-describedby'), null); }); it('Should set aria-describedby for tooltips if the state is show', done => { const wrapper = mount( <OverlayTrigger trigger="click" overlay={<Div />}> <button type="button">button</button> </OverlayTrigger>, ); wrapper.find('button').simulate('click'); setTimeout(() => { wrapper .find('button') .getDOMNode() .matches('[aria-describedby="test-tooltip"]') .should.equal(true); done(); }); }); describe('trigger handlers', () => { let mountPoint; beforeEach(() => { mountPoint = document.createElement('div'); document.body.appendChild(mountPoint); }); afterEach(() => { ReactDOM.unmountComponentAtNode(mountPoint); document.body.removeChild(mountPoint); }); it('Should keep trigger handlers', done => { mount( <div> <OverlayTrigger trigger="click" overlay={<Div>test</Div>}> <button type="button" onClick={() => done()}> button </button> </OverlayTrigger> <input id="target" /> </div>, ) .find('button') .simulate('click'); }); }); it('Should maintain overlay classname', () => { const wrapper = mount( <OverlayTrigger trigger="click" overlay={<Div className="test-overlay">test</Div>} > <button type="button">button</button> </OverlayTrigger>, ); wrapper.find('button').simulate('click'); wrapper.assertSingle('div.test-overlay'); }); it('Should pass transition callbacks to Transition', done => { let count = 0; const increment = () => count++; const wrapper = mount( <OverlayTrigger trigger="click" overlay={<Div>test</Div>} onExit={increment} onExiting={increment} onExited={() => { increment(); expect(count).to.equal(6); done(); }} onEnter={increment} onEntering={increment} onEntered={() => { increment(); wrapper.find('button').simulate('click'); }} > <button type="button">button</button> </OverlayTrigger>, ); wrapper.find('button').simulate('click'); }); it('Should forward requested context', () => { const contextTypes = { key: PropTypes.string, }; const contextSpy = sinon.spy(); class ContextReader extends React.Component { static contextTypes = contextTypes; render() { contextSpy(this.context.key); return <div />; } } class ContextHolder extends React.Component { static childContextTypes = contextTypes; getChildContext() { return { key: 'value' }; } render() { return ( <OverlayTrigger trigger="click" overlay={<ContextReader />}> <button type="button">button</button> </OverlayTrigger> ); } } mount(<ContextHolder />) .find('button') .simulate('click'); contextSpy.calledWith('value').should.be.true; }); describe('overlay types', () => { [ { name: 'Popover', overlay: <Popover id="test-popover">test</Popover>, }, { name: 'Tooltip', overlay: <Tooltip id="test-tooltip">test</Tooltip>, }, ].forEach(testCase => { describe(testCase.name, () => { it('Should handle trigger without warnings', () => { mount( <OverlayTrigger trigger="click" overlay={testCase.overlay}> <button type="button">button</button> </OverlayTrigger>, ) .find('button') .simulate('click'); }); }); }); }); describe('rootClose', () => { [ { label: 'true', rootClose: true, shownAfterClick: false, }, { label: 'default (false)', rootClose: null, shownAfterClick: true, }, ].forEach(testCase => { describe(testCase.label, () => { it('Should have correct show state', () => { const wrapper = mount( <OverlayTrigger overlay={<Div>test</Div>} trigger="click" rootClose={testCase.rootClose} > <button type="button">button</button> </OverlayTrigger>, ); wrapper.find('button').simulate('click'); expect(wrapper.state('show')).to.equal(true); // Need to click this way for it to propagate to document element. document.documentElement.click(); expect(wrapper.state('show')).to.equal(testCase.shownAfterClick); }); }); }); describe('clicking on trigger to hide', () => { it('should hide after clicking on trigger', () => { const attachTo = document.createElement('div'); document.body.appendChild(attachTo); const wrapper = mount( <OverlayTrigger overlay={<Div>test</Div>} trigger="click" rootClose> <button type="button">button</button> </OverlayTrigger>, { attachTo }, ); const node = wrapper.getDOMNode(); expect(wrapper.state('show')).to.be.false; node.click(); expect(wrapper.state('show')).to.be.true; // Need to click this way for it to propagate to document element. node.click(); expect(wrapper.state('show')).to.be.false; wrapper.unmount(); }); }); describe('replaced overlay', () => { it('Should still be shown', () => { class ReplacedOverlay extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.state = { replaced: false }; } handleClick() { this.setState({ replaced: true }); } render() { if (this.state.replaced) { return <div>replaced</div>; } return ( <div> <a id="replace-overlay" onClick={this.handleClick}> original </a> </div> ); } } const wrapper = mount( <OverlayTrigger overlay={<ReplacedOverlay />} trigger="click" rootClose > <button type="button">button</button> </OverlayTrigger>, ); wrapper.find('button').simulate('click'); // Need to click this way for it to propagate to document element. document.getElementById('replace-overlay').click(); wrapper.state('show').should.be.true; }); }); }); });
app/components/EyesProtect/EyesNotify.js
SuperDOgePx/chrome-extension-react
import React, { Component } from 'react'; import { unmountComponentAtNode } from 'react-dom'; import { setChromeLocalStore, getChromeLocalStore } from '../../utils/settings'; export default class EyesNotify extends Component { constructor(props) { super(props); this.state = { timer: 30 }; this.notiInterval = setInterval(() => { if (this.state.timer > 0) { this.setState({ timer: this.state.timer - 1 }); } else { unmountComponentAtNode(document.getElementById('voz-eyes-notify')); } }, 1000); } componentWillUnmount() { clearInterval(this.notiInterval); } openSettings(e) { e.preventDefault(); chrome.runtime.sendMessage({ service: 'open-options' }); return false; } render() { return ( <div className="voz-bao-ve-mat"> <div style={{ position: 'fixed', height: '100%', width: '100%', top: 0, zIndex: 9999, background: 'rgba(0, 0, 0, 0.8)', fontSize: '15px', }} /> <div style={{ textAlign: 'center', padding: '50px', backgroundColor: '#4286f4', color: 'white', position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', zIndex: 10000, fontSize: '15px', }} > <strong> Vì một đôi mắt khoẻ mạnh, các thím hãy cùng nhau không nhìn vào máy tính trong lúc này nào! </strong> <img style={{ verticalAlign: 'middle' }} src="/images/smilies/Off/byebye.gif" /> <img style={{ verticalAlign: 'middle' }} src="/images/smilies/Off/matrix.gif" /> <img style={{ verticalAlign: 'middle' }} src="/images/smilies/Off/matrix.gif" /> <br /> <strong> Thông báo này sẽ tự tắt sau </strong> <strong className="dem-nguoc">{this.state.timer} giây</strong> <div style={{ fontSize: '9px' }}>Bạn có thể tắt thông báo tại <a href="#" onClick={this.openSettings}>menu cài đặt voz living</a></div> <div className="eyes-close" onClick={() => unmountComponentAtNode(document.getElementById('voz-eyes-notify'))} style={{ position: 'absolute', width: '150px', height: '50px', backgroundColor: 'green', right: 0, bottom: 0, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', }} >Tắt thông báo </div> </div> </div> ); } }
docs/app/Examples/addons/Radio/Types/RadioExampleRadio.js
vageeshb/Semantic-UI-React
import React from 'react' import { Radio } from 'semantic-ui-react' const RadioExampleRadio = () => ( <Radio label='Make my profile visible' /> ) export default RadioExampleRadio
src/layouts/index.js
getinsomnia/insomnia.rest
import React from 'react'; import Helmet from 'react-helmet'; import './styles/index.less'; import Navbar from '../partials/navbar'; import Footer from '../partials/footer'; import Title from '../partials/title'; import { isLoggedIn } from '../lib/session'; import { site } from '../config'; import { parse as urlParse } from 'url'; export default class extends React.Component { state = { isLoggedIn: false }; componentDidMount() { this.setState({ isLoggedIn: isLoggedIn() }); this.trackSignupSource(); } trackSignupSource() { const url = urlParse(document.location.href, true); // Override signup source with ref non matter what if (url.query.ref) { localStorage.signupSource = url.query.ref; return; } // Fallback to referrer but don't track self-referrals. Also don't set referrer // if signupSource already exists. We don't want to accidentally overwrite the ref if ( !localStorage.signupSource && document.referrer && document.referrer.indexOf('https://insomnia.rest') !== 0 ) { localStorage.signupSource = document.referrer; } } render() { const { children, location } = this.props; const { isLoggedIn } = this.state; return ( <React.Fragment> <Title /> <Helmet> <meta name="description" content={site && site.description} /> <body data-pathname={location.pathname} /> </Helmet> <Navbar loggedIn={isLoggedIn} /> <main role="main">{children}</main> <Footer /> </React.Fragment> ); } }
src/public/js/main.js
datalocale/dataviz-finances-gironde
import { createStore } from 'redux'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { Record, Map as ImmutableMap, List, Set as ImmutableSet } from 'immutable'; import { csv, xml, json } from 'd3-fetch'; import page from 'page'; import {urls, FINANCE_DATA, AGGREGATED_ATEMPORAL, AGGREGATED_TEMPORAL} from './constants/resources'; import reducer from './reducer'; import {LigneBudgetRecord, DocumentBudgetaire} from '../../shared/js/finance/DocBudgDataStructures.js'; import { fromXMLDocument } from '../../shared/js/finance/planDeCompte'; import {makeChildToParent, flattenTree} from '../../shared/js/finance/visitHierarchical.js'; import hierarchicalM52 from '../../shared/js/finance/hierarchicalM52.js'; import Breadcrumb from '../../shared/js/components/gironde.fr/Breadcrumb'; import Home from './components/screens/Home'; import FinanceElement from './components/screens/FinanceElement'; import FocusSolidarity from './components/screens/FocusSolidarity'; import FocusInvestments from './components/screens/FocusInvestments'; import FocusPresence from './components/screens/FocusPresence'; import ExploreBudget from './components/screens/ExploreBudget'; import { HOME, SOLIDARITES, INVEST, PRESENCE } from './constants/pages'; import { FINANCE_DATA_RECEIVED, ATEMPORAL_TEXTS_RECEIVED, TEMPORAL_TEXTS_RECEIVED, PLAN_DE_COMPTE_RECEIVED, FINANCE_DETAIL_ID_CHANGE, } from './constants/actions'; import {fonctionLabels} from '../../../build/finances/m52-strings.json'; /** * * Initialize Redux store + React binding * */ const REACT_CONTAINER_SELECTOR = '.cd33-finance-dataviz'; const CONTAINER_ELEMENT = document.querySelector(REACT_CONTAINER_SELECTOR); /* Dirty (temporary) hacks to fix the gironde.fr pages so the content displays properly */ if(process.env.NODE_ENV === 'production'){ const main = document.body.querySelector('main'); const columnsEl = main.querySelector('.columns'); const rowEl = main.querySelector('.row'); const elementsToMove = main.querySelectorAll('.columns > :nth-child(-n+3)'); Array.from(elementsToMove).forEach(e => { if(e.querySelector('h1')){ // remove server-generated h1 e.remove(); } else{ main.insertBefore(e, rowEl); } }); main.insertBefore(CONTAINER_ELEMENT, rowEl); } // Breadcrumb const BREADCRUMB_CONTAINER = process.env.NODE_ENV === "production" ? document.body.querySelector('.breadcrumb').parentNode : document.body.querySelector('nav'); const DEFAULT_BREADCRUMB = List([ { text: 'Accueil', url: '/' }, { text: 'Le Département', url: '/le-departement' }, { text: `Un budget au service des solidarités humaine et territoriale`, url: '#' } ]); const StoreRecord = Record({ docBudgByYear: undefined, aggregationByYear: undefined, planDeCompteByYear: undefined, currentYear: undefined, explorationYear: undefined, // ImmutableMap<id, FinanceElementTextsRecord> textsById: undefined, financeDetailId: undefined, screenWidth: undefined }); const store = createStore( reducer, new StoreRecord({ docBudgByYear: new ImmutableMap(), aggregationByYear: new ImmutableMap(), planDeCompteByYear: new ImmutableMap(), currentYear: (new Date()).getFullYear() - 1, explorationYear: (new Date()).getFullYear() - 1, financeDetailId: undefined, textsById: ImmutableMap([[HOME, {label: 'Acceuil'}]]), screenWidth: window.innerWidth }) ); store.dispatch({ type: ATEMPORAL_TEXTS_RECEIVED, textList: Object.keys(fonctionLabels) .map(fonction => ({ id: `M52-DF-${fonction}`, label: fonctionLabels[fonction] })) }); store.dispatch({ type: ATEMPORAL_TEXTS_RECEIVED, textList: Object.keys(fonctionLabels) .map(fonction => ({ id: `M52-DI-${fonction}`, label: fonctionLabels[fonction] })) }); /** * * Fetching initial data * */ json(urls[FINANCE_DATA]) .then(({documentBudgetaires, aggregations}) => { store.dispatch({ type: FINANCE_DATA_RECEIVED, documentBudgetaires: documentBudgetaires.map(db => { db.rows = new ImmutableSet(db.rows.map(LigneBudgetRecord)) return DocumentBudgetaire(db) }), aggregations }); for(const {Exer} of documentBudgetaires){ xml(`https://datalocale.github.io/dataviz-finances-gironde/data/finances/plansDeCompte/plan-de-compte-M52-M52-${Exer}.xml`) .then(fromXMLDocument) .then(planDeCompte => { store.dispatch({ type: PLAN_DE_COMPTE_RECEIVED, planDeCompte }); }) } }); csv(urls[AGGREGATED_ATEMPORAL]) .then(textList => { store.dispatch({ type: ATEMPORAL_TEXTS_RECEIVED, textList }); }); csv(urls[AGGREGATED_TEMPORAL]) .then(textList => { store.dispatch({ type: TEMPORAL_TEXTS_RECEIVED, textList }); }); /** * * Routing * */ page('/', () => { console.log('in route', '/') ReactDOM.render( React.createElement( Provider, { store }, React.createElement(Home) ), CONTAINER_ELEMENT ); const breadcrumb = DEFAULT_BREADCRUMB; ReactDOM.render( React.createElement(Breadcrumb, { items: breadcrumb }), BREADCRUMB_CONTAINER ); }); page('/explorer', () => { console.log('in route', '/explorer'); ReactDOM.render( React.createElement( Provider, { store }, React.createElement(ExploreBudget) ), CONTAINER_ELEMENT ); const breadcrumb = DEFAULT_BREADCRUMB.push({text: 'Explorer'}); ReactDOM.render( React.createElement(Breadcrumb, { items: breadcrumb }), BREADCRUMB_CONTAINER ); }); page('/finance-details/:contentId', ({params: {contentId}}) => { console.log('in route', '/finance-details', contentId) scrollTo(0, 0); store.dispatch({ type: FINANCE_DETAIL_ID_CHANGE, financeDetailId: contentId }) ReactDOM.render( React.createElement( Provider, { store }, React.createElement(FinanceElement) ), CONTAINER_ELEMENT ); const {docBudgByYear, aggregationByYear, planDeCompteByYear, currentYear, textsById} = store.getState() const isM52Element = contentId.startsWith('M52-'); let RDFI; if(isM52Element){ RDFI = contentId.slice('M52-'.length, 'M52-XX'.length); } const documentBudgetaire = docBudgByYear.get(currentYear); const aggregatedDocumentBudgetaire = aggregationByYear.get(currentYear); const planDeCompte = planDeCompteByYear.get(currentYear) const hierM52 = documentBudgetaire && RDFI && planDeCompte && hierarchicalM52(documentBudgetaire, planDeCompte, RDFI); const childToParent = makeChildToParent(...[aggregatedDocumentBudgetaire, hierM52].filter(x => x !== undefined)) const breadcrumbData = []; let currentElement = (aggregatedDocumentBudgetaire && flattenTree(aggregatedDocumentBudgetaire).find(el => el.id === contentId)) || (hierM52 && flattenTree(hierM52).find(el => el.id === contentId)) while(currentElement){ if(currentElement.id !== 'racine'){ breadcrumbData.push({ text: textsById.get(currentElement.id).label, url: `#!/finance-details/${currentElement.id}` }) } currentElement = childToParent.get(currentElement); } breadcrumbData.push({ text: 'Explorer', url: `#!/explorer` }) const breadcrumb = DEFAULT_BREADCRUMB.concat(breadcrumbData.reverse()); ReactDOM.render( React.createElement(Breadcrumb, { items: breadcrumb }), BREADCRUMB_CONTAINER ); }); page(`/focus/${SOLIDARITES}`, () => { console.log('in route', `/focus/${SOLIDARITES}`); scrollTo(0, 0); ReactDOM.render( React.createElement( Provider, { store }, React.createElement(FocusSolidarity) ), CONTAINER_ELEMENT ); }); page(`/focus/${INVEST}`, () => { console.log('in route', `/focus/${INVEST}`); scrollTo(0, 0); ReactDOM.render( React.createElement( Provider, { store }, React.createElement(FocusInvestments) ), CONTAINER_ELEMENT ); }); page(`/focus/${PRESENCE}`, () => { console.log('in route', `/focus/${PRESENCE}`); scrollTo(0, 0); ReactDOM.render( React.createElement( Provider, { store }, React.createElement(FocusPresence) ), CONTAINER_ELEMENT ); }); page.redirect(location.pathname, '#!/') page.redirect(location.pathname+'/', '#!/') page.base(location.pathname); page({ hashbang: true }); window.addEventListener('hashchange', () => { scrollTo(0, 0); page.redirect(location.hash); }); window.addEventListener('popstate', () => { scrollTo(0, 0); page.redirect(location.hash); });
src/components/thumbnail.js
menthena/project-a
import React from 'react'; import { Link } from 'react-router'; const Thumbnail = ({ thumbnailURL }) => ( <div className="thumbnail"> <img src={thumbnailURL} /> </div> ); Thumbnail.propTypes = { thumbnailURL: React.PropTypes.string.isRequired }; export default Thumbnail;
tests/client/admin/components/TestNavBar.js
mstriemer/addons-frontend
import React from 'react'; import { NavBar, NavBarLink } from 'core/components/NavBar'; import AdminNavBar from 'admin/components/NavBar'; import { shallowRender } from 'tests/client/helpers'; describe('<AdminNavBar />', () => { it('renders a link to Search but not log out unauthenticated', () => { const root = shallowRender(<AdminNavBar isAuthenticated={false} />); assert.equal(root.type, NavBar); const link = root.props.children[0]; assert.equal(link.type, NavBarLink); assert.equal(link.props.to, '/search'); assert.equal(link.props.children, 'Search'); }); it('renders a link to Search and log out authenticated', () => { const handleLogOut = sinon.spy(); const root = shallowRender(<AdminNavBar isAuthenticated handleLogOut={handleLogOut} />); assert.equal(root.type, NavBar); const link = root.props.children[0]; assert.equal(link.type, NavBarLink); assert.equal(link.props.to, '/search'); assert.equal(link.props.children, 'Search'); const logOutButton = root.props.children[1]; assert.strictEqual(logOutButton.props.onClick, handleLogOut); }); });
src/scripts/Playlist.js
Ribeiro/yoda
'use strict'; import React from 'react'; import PlaylistHeader from './PlaylistHeader'; import PlaylistVideos from './PlaylistVideos'; const PureRenderMixin = React.addons.PureRenderMixin; export default React.createClass({ propTypes: { playlist: React.PropTypes.array.isRequired, }, mixins: [PureRenderMixin], renderPlaylists(playlist){ return ( <div key={playlist.get('id')} className="playlist-items"> <PlaylistHeader title={playlist.get('title')} playlist={playlist.get('id')} /> <PlaylistVideos videos={playlist.get('videos')} /> </div> ); }, render() { let nodes = this.props.playlist.map(this.renderPlaylists); return ( <div className="playlist-items-container"> {nodes} </div> ); } });
example/example/index.android.js
JimmyDaddy/doctorstrange-updater
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Alert } from 'react-native'; import DoctorstrangeUpdater from 'doctorstrange-updater'; console.log(DoctorstrangeUpdater); export default class example extends Component { constructor(props){ super(props); this.state = { showDownLoad: false, downloadProgress: 0, } } componentDidMount() { let updater = DoctorstrangeUpdater.getDoctorStrangeUpdater({ DEBUG: __DEV__, debugVersionHost: 'http://192.168.0.146:3002/update/version/selectlatest', debugDownloadHost: 'http://192.168.0.146:3002/update/download', debugErrorReportHost: 'http://192.168.0.146:3002/update/errorreport', versionHost: `http://doctorstrange.songxiaocai.org/update/version/selectlatest`, downloadHost: `http://doctorstrange.songxiaocai.org/update/download`, errorReportHost: `http://doctorstrange.songxiaocai.org/update/errorreport`, allowCellularDataUse: true, showInfo: true, downloadStart: () => { this.changeState({ showDownLoad: false }) }, downloadProgress: (progress) => { this.changeState({ downloadProgress: progress, }) }, downloadEnd: () => { this.changeState({ showDownLoad: false }) }, checkError: () => { updater.showMessageOnStatusBar('检查更新出错,请检查您的网络设置'); // Alert.alert( // '检查更新出错', // '请检查您的网络设置', // ); }, onError: () => { Alert.alert( '更新出错', '请检查您的网络设置,并重启app', ); }, askReload: (reload) => { Alert.alert( '新功能准备就绪,是否立即应用?', null, [ {text: '取消', onPress: () => {}}, {text: '应用', onPress: () => reload(true)} ] ); }, alreadyUpdated: () => { updater.showMessageOnStatusBar('已全部更新'); }, needUpdateApp: () => { Alert.alert('当前应用版本过低', '请更新', [ {text: '取消', onPress: ()=>{}}, {text: '确定', onPress: ()=>{ Linking.openURL('http://www.songxiaocai.com/captain/download-ios.html'); }}, ]); } }); updater.checkUpdate(); } render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> <Text style={styles.instructions, {color: 'red'}}> Code Version {DoctorstrangeUpdater.getDoctorStrangeUpdater().JSCODE_VERSION} </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('example', () => example);
src/components/type-link.js
tylerchilds/pokedex
import React from 'react'; import { Link } from 'react-router'; export default class TypeLink extends React.Component { render() { const type = this.props.type.name || this.props.type; return ( <Link to={`/type/${type}`} className={`type ${type.toLowerCase()}`}>{type}</Link> ); } }
src/js/containers/NotFound/index.js
ClubExpressions/poc-expression.club
import React, { Component } from 'react'; import { Link } from 'react-router'; export default class NotFound extends Component { render () { return ( <div className='container text-center'> <h1>This is a demo 404 page!</h1> <hr /> <Link to='/'>Back To Home View</Link> </div> ); } }
src/components/app.js
jameswatkins77/React-Blogger-App
import React, { Component } from 'react'; export default class App extends Component { render() { return ( <div> {this.props.children} </div> ); } }
src/main.js
vesparny/react-kickstart
import 'sanitize.css/sanitize.css' import React from 'react' import ReactDOM from 'react-dom' const rootEl = document.getElementById('root') let render = () => { const Root = require('./components/Root').default ReactDOM.render(<Root />, rootEl) } if (module.hot) { const renderApp = render const renderError = err => { const RedBox = require('redbox-react') ReactDOM.render(<RedBox error={err} />, rootEl) } render = () => { try { renderApp() } catch (err) { renderError(err) } } module.hot.accept('./components/Root', render) } render()
blueprints/smart/files/__root__/containers/__name__.js
donnycrash/react-redux-electron-starter-kit
import React from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' type Props = { } export class <%= pascalEntityName %> extends React.Component { props: Props; render() { return ( <div></div> ) } } const mapStateToProps = (state) => { return {} } const mapDispatchToProps = (dispatch) => { return {} } export default connect( mapStateToProps, mapDispatchToProps )(<%= pascalEntityName %>)
src/js/test/components/pages/items/Item.spec.js
athill/wimf
import React from 'react'; import { shallow } from 'enzyme'; import faker from 'faker'; import sinon from 'sinon'; import Item, { ItemHeader } from '../../../../components/pages/items/Item'; describe('Item', () => { const name = faker.lorem.words(); const quantity = faker.random.number(); const date = '2016-01-02'; const displayDate = '01/02/2016'; it('works', () => { const output = shallow(<Item name={name} quantity={quantity} date={date} />); expect(output.is('Panel')).toBe(true); const cols = output.find('Col'); expect(cols.get(0).props.children).toBe(quantity); expect(cols.get(1).props.children).toBe(displayDate); }); describe('ItemHeader', () => { it('works', () => { const output = shallow(<ItemHeader name={name} />); const h4 = output.find('h4'); expect(h4.length).toBe(1); expect(h4.props().children).toBe(name); expect(output.find('Icon').length).toBe(2); }); it('handles edit click', () => { const editClickHandler = sinon.spy(); const output = shallow(<ItemHeader name={name} editClickHandler={editClickHandler} />); const editIcon = output.find('.edit-button'); editIcon.simulate('click'); expect(editClickHandler.calledOnce).toBe(true); }); it('handles delete click', () => { const deleteClickHandler = sinon.spy(); const output = shallow(<ItemHeader name={name} deleteClickHandler={deleteClickHandler} />); const deleteIcon = output.find('.delete-button'); deleteIcon.simulate('click'); expect(deleteClickHandler.calledOnce).toBe(true); }); }); });
material-ui/src/cookbook/2-appbar/AppbarWithComplexMenu.js
Muzietto/react-playground
import React from 'react'; import { fade, makeStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import IconButton from '@material-ui/core/IconButton'; import Typography from '@material-ui/core/Typography'; import InputBase from '@material-ui/core/InputBase'; import Badge from '@material-ui/core/Badge'; import MenuItem from '@material-ui/core/MenuItem'; import Menu from '@material-ui/core/Menu'; import MenuIcon from '@material-ui/icons/Menu'; import SearchIcon from '@material-ui/icons/Search'; import AccountCircle from '@material-ui/icons/AccountCircle'; import MailIcon from '@material-ui/icons/Mail'; import NotificationsIcon from '@material-ui/icons/Notifications'; import MoreIcon from '@material-ui/icons/MoreVert'; const useStyles = makeStyles(theme => ({ grow: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), }, title: { display: 'none', [theme.breakpoints.up('sm')]: { display: 'block', }, }, search: { position: 'relative', borderRadius: theme.shape.borderRadius, backgroundColor: fade(theme.palette.common.white, 0.15), '&:hover': { backgroundColor: fade(theme.palette.common.white, 0.25), }, marginRight: theme.spacing(2), marginLeft: 0, width: '100%', [theme.breakpoints.up('sm')]: { marginLeft: theme.spacing(3), width: 'auto', }, }, searchIcon: { width: theme.spacing(7), height: '100%', position: 'absolute', pointerEvents: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', }, inputRoot: { color: 'inherit', }, inputInput: { padding: theme.spacing(1, 1, 1, 7), transition: theme.transitions.create('width'), width: '100%', [theme.breakpoints.up('md')]: { width: 200, }, }, sectionDesktop: { display: 'none', [theme.breakpoints.up('md')]: { display: 'flex', }, }, sectionMobile: { display: 'flex', [theme.breakpoints.up('md')]: { display: 'none', }, }, })); export default function AppbarWithComplexMenu() { const classes = useStyles(); const [anchorEl, setAnchorEl] = React.useState(null); const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = React.useState(null); const isMenuOpen = Boolean(anchorEl); const isMobileMenuOpen = Boolean(mobileMoreAnchorEl); const handleProfileMenuOpen = event => { setAnchorEl(event.currentTarget); }; const handleMobileMenuClose = () => { setMobileMoreAnchorEl(null); }; const handleMenuClose = () => { setAnchorEl(null); handleMobileMenuClose(); }; const handleMobileMenuOpen = event => { setMobileMoreAnchorEl(event.currentTarget); }; const menuId = 'primary-search-account-menu'; const renderMenu = ( <Menu anchorEl={anchorEl} anchorOrigin={{ vertical: 'top', horizontal: 'right' }} id={menuId} keepMounted transformOrigin={{ vertical: 'top', horizontal: 'right' }} open={isMenuOpen} onClose={handleMenuClose} > <MenuItem onClick={handleMenuClose}>Profile</MenuItem> <MenuItem onClick={handleMenuClose}>My account</MenuItem> </Menu> ); const mobileMenuId = 'primary-search-account-menu-mobile'; const renderMobileMenu = ( <Menu anchorEl={mobileMoreAnchorEl} anchorOrigin={{ vertical: 'top', horizontal: 'right' }} id={mobileMenuId} keepMounted transformOrigin={{ vertical: 'top', horizontal: 'right' }} open={isMobileMenuOpen} onClose={handleMobileMenuClose} > <MenuItem> <IconButton aria-label="show 4 new mails" color="inherit"> <Badge badgeContent={4} color="secondary"> <MailIcon /> </Badge> </IconButton> <p>Messages</p> </MenuItem> <MenuItem> <IconButton aria-label="show 11 new notifications" color="inherit"> <Badge badgeContent={11} color="secondary"> <NotificationsIcon /> </Badge> </IconButton> <p>Notifications</p> </MenuItem> <MenuItem onClick={handleProfileMenuOpen}> <IconButton aria-label="account of current user" aria-controls="primary-search-account-menu" aria-haspopup="true" color="inherit" > <AccountCircle /> </IconButton> <p>Profile</p> </MenuItem> </Menu> ); return ( <div className={classes.grow}> <AppBar position="static"> <Toolbar> <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="open drawer" > <MenuIcon /> </IconButton> <Typography className={classes.title} variant="h6" noWrap> Material-UI </Typography> <div className={classes.search}> <div className={classes.searchIcon}> <SearchIcon /> </div> <InputBase placeholder="Search…" classes={{ root: classes.inputRoot, input: classes.inputInput, }} inputProps={{ 'aria-label': 'search' }} /> </div> <div className={classes.grow} /> <div className={classes.sectionDesktop}> <IconButton aria-label="show 4 new mails" color="inherit"> <Badge badgeContent={4} color="secondary"> <MailIcon /> </Badge> </IconButton> <IconButton aria-label="show 17 new notifications" color="inherit"> <Badge badgeContent={17} color="secondary"> <NotificationsIcon /> </Badge> </IconButton> <IconButton edge="end" aria-label="account of current user" aria-controls={menuId} aria-haspopup="true" onClick={handleProfileMenuOpen} color="inherit" > <AccountCircle /> </IconButton> </div> <div className={classes.sectionMobile}> <IconButton aria-label="show more" aria-controls={mobileMenuId} aria-haspopup="true" onClick={handleMobileMenuOpen} color="inherit" > <MoreIcon /> </IconButton> </div> </Toolbar> </AppBar> {renderMobileMenu} {renderMenu} </div> ); }
src/svg-icons/editor/format-color-text.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatColorText = (props) => ( <SvgIcon {...props}> <path fillOpacity=".36" d="M0 20h24v4H0z"/><path d="M11 3L5.5 17h2.25l1.12-3h6.25l1.12 3h2.25L13 3h-2zm-1.38 9L12 5.67 14.38 12H9.62z"/> </SvgIcon> ); EditorFormatColorText = pure(EditorFormatColorText); EditorFormatColorText.displayName = 'EditorFormatColorText'; EditorFormatColorText.muiName = 'SvgIcon'; export default EditorFormatColorText;
src/containers/Address/index.js
wvfan/HSBC
import * as F from 'firebase'; import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { withRouter } from 'react-router'; import Page from 'components/Page'; import Header from 'components/Page/Header'; import Body from 'components/Page/Body'; import * as systemActions from 'actions/system'; import { styles } from './styles.scss'; import img from './images/address.jpg'; @connect( state => ({ user: state.system.user, }), bindActionCreators({ ...systemActions, }), ) export default class Address extends React.Component { static propTypes = { history: PropTypes.object, user: PropTypes.object, update: PropTypes.func, }; render() { const { user, } = this.props; return ( <Page className={styles}> <Header backTo="" /> <Body style={{ backgroundImage: `url(${img})`, }} > {!user.addressVerified ? <div className="absolute-parent container not-verified"> <div className="absolute-parent bgColor" /> <div className="absolute-parent content"> <div className="type"> <div className="fill-space" /> <div className="icon">&#xe61b;</div> <div className="word">Address</div> <div className="fill-space" /> </div> <div className="main">You are not verified!</div> <div className="button" onClick={() => { this.props.history.push('/scanner'); }} > VERIFY </div> <div className="notif">To verify your address, please ensure you have an active mobile network connection.</div> </div> </div> : <div className="absolute-parent container verified"> <div className="absolute-parent bgColor" /> </div> } </Body> </Page> ); } }
src/widgets/JSONForm/widgets/TimePicker.js
sussol/mobile
/* eslint-disable no-console */ import React from 'react'; import { TextInput } from 'react-native'; import moment from 'moment'; import PropTypes from 'prop-types'; import { DatePickerButton } from '../../DatePickerButton'; import { FlexRow } from '../../FlexRow'; import { useJSONFormOptions } from '../JSONFormContext'; import { DARKER_GREY, LIGHT_GREY } from '../../../globalStyles/colors'; const regex = new RegExp('^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$'); export const TimePicker = ({ disabled, value, onChange, placeholder, readonly, onBlur, id }) => { const { focusController } = useJSONFormOptions(); const ref = focusController.useRegisteredRef(); const initialValue = regex.test(value) ? moment(value, 'hh:mm').toDate() : new Date(); const handleChange = dateString => { onChange(dateString); onBlur(id, dateString); }; return ( <FlexRow> <TextInput style={{ flex: 1 }} placeholderTextColor={LIGHT_GREY} underlineColorAndroid={DARKER_GREY} placeholder={placeholder} editable={!(readonly || disabled)} value={value} ref={ref} onSubmitEditing={() => focusController.next(ref)} onChangeText={handleChange} returnKeyType="next" autoCapitalize="none" keyboardType="numeric" autoCorrect={false} /> <DatePickerButton mode="time" isDisabled={readonly || disabled} initialValue={initialValue} onDateChanged={date => { handleChange(moment(date).format('HH:mm')); }} /> </FlexRow> ); }; TimePicker.defaultProps = { value: '', }; TimePicker.propTypes = { disabled: PropTypes.bool.isRequired, value: PropTypes.string, onChange: PropTypes.func.isRequired, placeholder: PropTypes.string.isRequired, readonly: PropTypes.bool.isRequired, onBlur: PropTypes.func.isRequired, id: PropTypes.string.isRequired, };
app/src/display/DisplaySearch.js
sfelderman/inverted-index
import React from 'react'; import {connect} from 'react-redux'; import {clean} from '../util/createDict'; import FileBlock from './FileBlock'; let DisplaySearch = ({dict, files, query}) => { let result = dict[query.toLowerCase()]; if (!result) { result = dict[clean(query)]; } if (!result) { result = ''; } else { result = Object.keys(result).map((name, index) => { return <FileBlock key={index} name={name} data={files[name]} query={query} locations={result} /> }) } return ( <div> <div> Query: {query} </div> <div> {result} </div> </div> ) }; const mapStateToProps = (state) => { return { dict: state.dict, files: state.uploadedFiles, query: state.query } }; DisplaySearch = connect( mapStateToProps, null )(DisplaySearch); export default DisplaySearch;
fluxible-router/app.js
eriknyk/flux-examples
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ import React from 'react'; import Fluxible from 'fluxible'; import Application from './components/Application'; import RouteStore from './stores/RouteStore'; import ApplicationStore from './stores/ApplicationStore'; import TimeStore from './stores/TimeStore'; import PageStore from './stores/PageStore'; let app = new Fluxible({ component: Application, stores: [ RouteStore, ApplicationStore, TimeStore, PageStore ] }); export default app;
src/components/TextInput/ControlledPasswordInput-test.js
joshblack/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import TextInput from '../TextInput'; import { mount, shallow } from 'enzyme'; describe('TextInput', () => { describe('renders as expected', () => { const wrapper = mount( <TextInput.ControlledPasswordInput id="test" className="extra-class" labelText="testlabel" helperText="testHelper" light /> ); const textInput = () => wrapper.find('input'); describe('input', () => { it('renders as expected', () => { expect(textInput().length).toBe(1); }); it('should accept refs', () => { class MyComponent extends React.Component { constructor(props) { super(props); this.textInput = React.createRef(); this.focus = this.focus.bind(this); } focus() { this.textInput.current.focus(); } render() { return ( <TextInput id="test" labelText="testlabel" ref={this.textInput} /> ); } } const wrapper = mount(<MyComponent />); expect(document.activeElement.type).toBeUndefined(); wrapper.instance().focus(); expect(document.activeElement.type).toEqual('text'); }); it('has the expected classes', () => { expect(textInput().hasClass('bx--text-input')).toEqual(true); }); it('should add extra classes that are passed via className', () => { expect(textInput().hasClass('extra-class')).toEqual(true); }); it('has the expected classes for light', () => { wrapper.setProps({ light: true }); expect(textInput().hasClass('bx--text-input--light')).toEqual(true); }); it('should set type as expected', () => { expect(textInput().props().type).toEqual('password'); wrapper.setProps({ type: 'text' }); expect(textInput().props().type).toEqual('text'); }); it('should set value as expected', () => { expect(textInput().props().defaultValue).toEqual(undefined); wrapper.setProps({ defaultValue: 'test' }); expect(textInput().props().defaultValue).toEqual('test'); }); it('should set disabled as expected', () => { expect(textInput().props().disabled).toEqual(false); wrapper.setProps({ disabled: true }); expect(textInput().props().disabled).toEqual(true); }); it('should set placeholder as expected', () => { expect(textInput().props().placeholder).not.toBeDefined(); wrapper.setProps({ placeholder: 'Enter text' }); expect(textInput().props().placeholder).toEqual('Enter text'); }); }); describe('label', () => { wrapper.setProps({ labelText: 'Email Input' }); const renderedLabel = wrapper.find('label'); it('renders a label', () => { expect(renderedLabel.length).toBe(1); }); it('has the expected classes', () => { expect(renderedLabel.hasClass('bx--label')).toEqual(true); }); it('should set label as expected', () => { expect(renderedLabel.text()).toEqual('Email Input'); }); }); describe('helper', () => { it('renders a helper', () => { const renderedHelper = wrapper.find('.bx--form__helper-text'); expect(renderedHelper.length).toEqual(1); }); it('renders children as expected', () => { wrapper.setProps({ helperText: ( <span> This helper text has <a href="/">a link</a>. </span> ), }); const renderedHelper = wrapper.find('.bx--form__helper-text'); expect(renderedHelper.props().children).toEqual( <span> This helper text has <a href="/">a link</a>. </span> ); }); it('should set helper text as expected', () => { wrapper.setProps({ helperText: 'Helper text' }); const renderedHelper = wrapper.find('.bx--form__helper-text'); expect(renderedHelper.text()).toEqual('Helper text'); }); }); }); describe('events', () => { describe('disabled textinput', () => { const onClick = jest.fn(); const onChange = jest.fn(); const wrapper = shallow( <TextInput id="test" labelText="testlabel" onClick={onClick} onChange={onChange} disabled /> ); const input = wrapper.find('input'); it('should not invoke onClick', () => { input.simulate('click'); expect(onClick).not.toBeCalled(); }); it('should not invoke onChange', () => { input.simulate('change'); expect(onChange).not.toBeCalled(); }); }); describe('enabled textinput', () => { const onClick = jest.fn(); const onChange = jest.fn(); const wrapper = shallow( <TextInput labelText="testlabel" id="test" onClick={onClick} onChange={onChange} /> ); const input = wrapper.find('input'); const eventObject = { target: { defaultValue: 'test', }, }; it('should invoke onClick when input is clicked', () => { input.simulate('click'); expect(onClick).toBeCalled(); }); it('should invoke onChange when input value is changed', () => { input.simulate('change', eventObject); expect(onChange).toBeCalledWith(eventObject); }); }); }); });
ui/src/main/js/pages/Home.js
apache/aurora
import React from 'react'; import Breadcrumb from 'components/Breadcrumb'; import Loading from 'components/Loading'; import RoleList from 'components/RoleList'; export default class HomePage extends React.Component { constructor(props) { super(props); this.state = {cluster: '', roles: [], loading: true}; } componentWillMount(props) { const that = this; this.props.api.getRoleSummary((response) => { that.setState({ cluster: response.serverInfo.clusterName, loading: false, roles: response.result.roleSummaryResult.summaries }); }); } render() { return this.state.loading ? <Loading /> : (<div> <Breadcrumb cluster={this.state.cluster} /> <div className='container'> <div className='row'> <div className='col-md-12'> <div className='panel'> <RoleList roles={this.state.roles} /> </div> </div> </div> </div> </div>); } }
app/src/App.js
kawallis/omni_mock
import React, { Component } from 'react'; import './App.css'; import NavBar from './components/navbar'; import DateTimeContainer from './DateSelector/DateTimeContainer'; class App extends Component { render() { return ( <div className="App"> <NavBar /> <div className="DateContainer"> <DateTimeContainer /> </div> </div> ); } } export default App;
MobileApp/App/components/closetradenext.js
VowelWeb/CoinTradePros.com
/** * CoinTradePros.com React Native App * http://www.cointradepros.com/ * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, View, Image, TouchableOpacity, PixelRatio, Text, TouchableHighlight, ScrollView, TextInput, Picker, } from 'react-native'; import ImagePicker from 'react-native-image-picker'; import Icon from 'react-native-vector-icons/FontAwesome'; import ModalDropdown from 'react-native-modal-dropdown'; export default class CloseTradeNext extends Component { state = { avatarSource: null, } SelectPhotoTapped() { const options = { quality: 1.0, maxWidth: 500, maxHeight: 500, storageOptions: { skipBackup: true } }; ImagePicker.showImagePicker(options, (response) => { console.log('Response = ', response); if (response.didCancel) { console.log('User cancelled image picker'); } else if (response.error) { console.log('Image Picker Error: ', response.error); } else if (response.customButton) { console.log('User Tapped Cutom Button: ', response.customButton); } else { let source = { uri: respinse.uri }; this.setState({ avatarSource: source }); } }); } render() { return( <View style={styles.container}> <View style={styles.header_main} > <TouchableHighlight onPress={() => this.props.navigator.push({id: 'closetrade', userData: {userId: this.props.userData.userId, userName: this.props.userData.userName, userAvatar: this.props.userData.userAvatar}})}><Icon name="arrow-left" size={20} color="black" /></TouchableHighlight> <Image source={{uri: 'http://res.cloudinary.com/vowelweb/image/upload/v1498114115/Logo_mqzlgt.png'}} style={styles.header_logo}/> <Icon name="list-ul" size={20} color="black" /> </View> <ScrollView> <View style={styles.body_main}> <Text style={styles.body_main_heading} >Post a Closed Trade</Text> <Text style={{fontFamily: 'Montserrat-Medium', color: 'black', fontSize: 12, paddingLeft: 20, paddingTop: 5,}}>$ Profit/Loss</Text> <TextInput underlineColorAndroid='transparent' returnKeyLabel = {"next"} onChangeText={(text) => this.setState({username:text})} placeholderTextColor = "black" autoCorrect={false} style={{height: 40, backgroundColor: 'white', marginLeft: 20, marginRight: 20, marginTop: 0, borderWidth: 1, fontFamily: 'Montserrat-Medium', color: 'black', fontSize: 12, paddingLeft: 10, marginTop: 5,}} /> <Text style={{fontFamily: 'Montserrat-Medium', color: 'black', fontSize: 12, paddingLeft: 20, paddingTop: 10,}}>% Profit/Loss</Text> <TextInput underlineColorAndroid='transparent' returnKeyLabel = {"next"} onChangeText={(text) => this.setState({username:text})} placeholderTextColor = "black" autoCorrect={false} style={{height: 40, backgroundColor: 'white', marginLeft: 20, marginRight: 20, marginTop: 0, borderWidth: 1, fontFamily: 'Montserrat-Medium', color: 'black', fontSize: 12, paddingLeft: 10, marginTop: 5,}} /> <Text style={{fontFamily: 'Montserrat-Medium', color: 'black', fontSize: 12, paddingLeft: 20, paddingTop: 10,}}>Comments</Text> <TextInput underlineColorAndroid='transparent' returnKeyLabel = {"next"} onChangeText={(text) => this.setState({username:text})} placeholderTextColor = "black" autoCorrect={false} multiline={true} numberOfLines={6} style={{ backgroundColor: 'white', marginLeft: 20, marginRight: 20, marginTop: 0, borderWidth: 1, fontFamily: 'Montserrat-Medium', color: 'black', fontSize: 12, paddingLeft: 10, marginTop: 5,}} /> <Text style={{fontFamily: 'Montserrat-Medium', color: 'black', fontSize: 12, paddingLeft: 20, paddingTop: 10,}}>Pro Tip From</Text> <ModalDropdown style={{marginLeft:20, marginRight:20, width:370, borderWidth:1, backgroundColor: 'white', height:35, marginTop: 5,}} textStyle={{fontFamily: 'Montserrat-Medium', fontSize: 10, color:'black', paddingTop: 8, paddingLeft: 8,}} defaultValue={'Select Pro Trader'} dropdownStyle={{width:370, height:250, borderWidth:1,}} dropdownTextStyle={{color:'black', fontSize: 14, fontFamily:'Montserrat-Medium', paddingLeft:10,}} options={['test', 'test1', 'test2']} /> <Text style={{fontFamily: 'Montserrat-Medium', color: 'black', fontSize: 12, paddingLeft: 20, paddingTop: 10,}}>Exchange</Text> <ModalDropdown style={{marginLeft:20, marginRight:20, width:370, borderWidth:1, backgroundColor: 'white', height:35, marginTop: 5,}} textStyle={{fontFamily: 'Montserrat-Medium', fontSize: 10, color:'black', paddingTop: 8, paddingLeft: 8,}} defaultValue={'Select Pro Trader'} dropdownStyle={{width:370, height:250, borderWidth:1,}} dropdownTextStyle={{color:'black', fontSize: 14, fontFamily:'Montserrat-Medium', paddingLeft:10,}} options={['test', 'test1', 'test2']} /> <Text style={{fontFamily: 'Montserrat-Medium', color: 'black', fontSize: 12, paddingLeft: 20, paddingTop: 10,}}>Prove It</Text> <TouchableOpacity onPress={this.SelectPhotoTapped.bind(this)}> <View style={[styles.avatar, styles.avatarContainer, {marginBottom: 20}]}> <Text style={{color: 'black', fontFamily: 'Montserrat-Medium',}}>Browse...</Text> </View> </TouchableOpacity> <TouchableHighlight style={styles.button} onPress={() => this._userLogin()} underlayColor='#99d9f4'> <Text style={styles.buttonText}>Post Trade</Text> </TouchableHighlight> </View> </ScrollView> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'flex-start', backgroundColor: '#efeff2' }, avatarContainer: { borderColor: '#9B9B9B', justifyContent: 'center', alignItems: 'center', backgroundColor: 'white', marginTop: 5, marginLeft: 20, }, avatar: { width: 371, height: 40, borderWidth: 1, borderColor: 'black' }, header_main: { flex: 0.15, paddingLeft: 30, paddingRight:30, backgroundColor: 'white', justifyContent: 'center', flexDirection: 'row', borderBottomWidth:1, alignItems: 'center', }, header_logo: { width:300, height:100, resizeMode:'contain', marginRight: 12, marginLeft: 12, }, body_main: { flex: 5, backgroundColor: '#efeff2', justifyContent: 'flex-start', }, body_main_heading: { fontSize:24, fontFamily: 'Montserrat-Bold', color: '#217821', paddingLeft: 20, paddingTop: 8, }, cover: { flex: 1, alignItems: 'center' }, button: { height: 35, backgroundColor: '#006837', borderColor: '#006837', borderWidth: 1, borderRadius: 10, alignSelf: 'stretch', justifyContent: 'center', marginLeft: 80, marginRight: 80, marginTop: 10, marginBottom: 10, }, buttonText: { justifyContent: 'center', textAlign: 'center', fontFamily: 'Montserrat-Bold', color: 'white' }, });
src/components/block-types/block-types.js
xutou12/draft-richer
import React from 'react'; import Icon from '../icons'; import Header from './header'; import Button from '../button'; import ButtonPopover from '../button-popover'; /** * Draft.DefaultDraftBlockRenderMap * <h1/> header-one * <h2/> header-two * <h3/> header-three * <h4/> header-four * <h5/> header-five * <h6/> header-six * <h6/> header-six * <blockquote/> blockquote * <pre/> code-block * <figure/> atomic * <li/> unordered-list-item,ordered-list-item** * <div/> unstyled* * 是默认的 blocktype 列表 * 自定义的 blocktype 必须在此列表中定义 * */ // 按钮配置 export const blockTypes = { // 自定义 header: { type: [ 'header-one', 'header-two', 'header-three', 'header-four', 'header-five', 'header-six' ], label: <Icon type="header" />, title: '标题', Element( props ) { return ( <ButtonPopover {...props}> <Header select={props.id} onChange={props.onToggle} /> </ButtonPopover> ); } }, blockquote: { type: 'blockquote', label: <Icon type="blockquote" />, title: '引用', Element: Button }, 'unordered-list-item': { type: 'unordered-list-item', label: <Icon type="listalt" />, title: '无序列表', Element: Button }, 'ordered-list-item': { type: 'ordered-list-item', label: <Icon type="listol" />, title: '有序列表', Element: Button }, 'code-block': { type: 'code-block', label: <Icon type="script" />, title: '代码块', Element: Button } };
packages/mineral-ui-icons/src/IconEnhancedEncryption.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconEnhancedEncryption(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zM8.9 6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1v2H8.9V6zM16 16h-3v3h-2v-3H8v-2h3v-3h2v3h3v2z"/> </g> </Icon> ); } IconEnhancedEncryption.displayName = 'IconEnhancedEncryption'; IconEnhancedEncryption.category = 'notification';
docs/app/Examples/collections/Menu/Types/index.js
clemensw/stardust
import React from 'react' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' // TODO: Add example with <Popup> after it will be added const Types = () => { return ( <ExampleSection title='Types'> <ComponentExample title='Menu' description='A menu.' examplePath='collections/Menu/Types/MenuExampleBasic' /> <ComponentExample description='Menu can be rendered via shorthand prop.' examplePath='collections/Menu/Types/MenuExampleProps' /> <ComponentExample description='Menu item text can be defined with the content prop.' examplePath='collections/Menu/Types/MenuExampleContentProp' /> <ComponentExample description='The name prop will be used for content if neither children nor content props are defined.' examplePath='collections/Menu/Types/MenuExampleNameProp' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleAttached' /> <ComponentExample title='Secondary Menu' description='A menu can adjust its appearance to de-emphasize its contents.' examplePath='collections/Menu/Types/MenuExampleSecondary' /> <ComponentExample title='Pointing' description='A menu can point to show its relationship to nearby content.' examplePath='collections/Menu/Types/MenuExamplePointing' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleSecondaryPointing' /> <ComponentExample title='Tabular' description='A menu can be formatted to show tabs of information.' examplePath='collections/Menu/Types/MenuExampleTabular' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleTabularOnTop' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleTabularOnBottom' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleTabularOnLeft' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleTabularOnRight' /> <ComponentExample title='Text' description='A menu can be formatted for text content.' examplePath='collections/Menu/Types/MenuExampleText' /> <ComponentExample title='Vertical Menu' description='A vertical menu displays elements vertically.' examplePath='collections/Menu/Types/MenuExampleVertical' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleVerticalText' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleVerticalDropdown' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleVerticalPointing' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleVerticalSecondary' /> <ComponentExample title='Pagination' description='A pagination menu is specially formatted to present links to pages of content.' examplePath='collections/Menu/Types/MenuExamplePagination' /> </ExampleSection> ) } export default Types
components/stories/header.js
kadira-samples/react-storybook-demo
import React from 'react'; import Header from '../Header'; import { storiesOf, action } from '@kadira/storybook'; storiesOf('Header', module) .add('default view', () => { return ( <div className="todoapp"> <Header addTodo={action('Add Todo')}/> </div> ); });
packages/reactor-kitchensink/src/examples/Charts/Area/FullStackedArea/FullStackedArea.js
dbuhrman/extjs-reactor
import React, { Component } from 'react'; import { Container } from '@extjs/ext-react'; import { Cartesian } from '@extjs/ext-react-charts'; import ChartToolbar from '../../ChartToolbar'; export default class FullStackedAreaChartExample extends Component { constructor(){ super(); } store = Ext.create('Ext.data.Store', { fields: ['month', 'data1', 'data2', 'data3', 'data4', 'other'], data:[ { month: 'Jan', data1: 20, data2: 37, data3: 35, data4: 4, other: 4 }, { month: 'Feb', data1: 20, data2: 37, data3: 36, data4: 5, other: 2 }, { month: 'Mar', data1: 19, data2: 36, data3: 37, data4: 4, other: 4 }, { month: 'Apr', data1: 18, data2: 36, data3: 38, data4: 5, other: 3 }, { month: 'May', data1: 18, data2: 35, data3: 39, data4: 4, other: 4 }, { month: 'Jun', data1: 17, data2: 34, data3: 42, data4: 4, other: 3 }, { month: 'Jul', data1: 16, data2: 34, data3: 43, data4: 4, other: 3 }, { month: 'Aug', data1: 16, data2: 33, data3: 44, data4: 4, other: 3 }, { month: 'Sep', data1: 16, data2: 32, data3: 44, data4: 4, other: 4 }, { month: 'Oct', data1: 16, data2: 32, data3: 45, data4: 4, other: 3 }, { month: 'Nov', data1: 15, data2: 31, data3: 46, data4: 4, other: 4 }, { month: 'Dec', data1: 15, data2: 31, data3: 47, data4: 4, other: 3 } ] }) state = { theme: 'default' }; onAxisLabelRender = (axis, label, layoutContext) => { // Custom renderer overrides the native axis label renderer. // Since we don't want to do anything fancy with the value // ourselves except appending a '%' sign, but at the same time // don't want to loose the formatting done by the native renderer, // we let the native renderer process the value first. return layoutContext.renderer(label) + '%'; }; changeTheme = theme => this.setState({ theme }) onSeriesTooltipRender = (tooltip, record, item) => { var fieldIndex = Ext.Array.indexOf(item.series.getYField(), item.field), browser = item.series.getTitle()[fieldIndex]; tooltip.setHtml(`${browser} on ${record.get('month')}: ${record.get(item.field)}%`) } render(){ const {theme}=this.state; return ( <Container padding={!Ext.os.is.Phone && 10} layout="fit"> <ChartToolbar onThemeChange={this.changeTheme} theme={theme} /> <Cartesian shadow store={this.store} theme={theme} insetPadding={'20 20 0 0'} legend={{type:'sprite'}} axes={[{ type: 'numeric', position: 'left', fields: ['data1', 'data2', 'data3', 'data4', 'other' ], grid: true, minimum: 0, maximum: 100, renderer: this.onAxisLabelRender }, { type: 'category', position: 'bottom', fields: 'month', grid: true, label: { rotate: { degrees: -90 } } }]} series={[{ type: 'area', fullStack: true, title: [ 'IE', 'Firefox', 'Chrome', 'Safari', 'Others' ], xField: 'month', yField: [ 'data1', 'data2', 'data3', 'data4', 'other' ], style: { opacity: 0.80 }, marker: { opacity: 0, scaling: 0.01, animation: { duration: 200, easing: 'easeOut' } }, highlightCfg: { opacity: 1, scaling: 1.5 }, tooltip: { trackMouse: true, renderer: this.onSeriesTooltipRender } }]} /> </Container> ) } }
actor-apps/app-web/src/app/components/ToolbarSection.react.js
webwlsong/actor-platform
import React from 'react'; import ReactMixin from 'react-mixin'; import { IntlMixin } from 'react-intl'; import classnames from 'classnames'; import ActivityActionCreators from 'actions/ActivityActionCreators'; import DialogStore from 'stores/DialogStore'; import ActivityStore from 'stores/ActivityStore'; //import AvatarItem from 'components/common/AvatarItem.react'; const getStateFromStores = () => { return { dialogInfo: DialogStore.getSelectedDialogInfo(), isActivityOpen: ActivityStore.isOpen() }; }; @ReactMixin.decorate(IntlMixin) class ToolbarSection extends React.Component { state = { dialogInfo: null, isActivityOpen: false }; constructor(props) { super(props); DialogStore.addSelectedChangeListener(this.onChange); ActivityStore.addChangeListener(this.onChange); } componentWillUnmount() { DialogStore.removeSelectedChangeListener(this.onChange); ActivityStore.removeChangeListener(this.onChange); } onClick = () => { if (!this.state.isActivityOpen) { ActivityActionCreators.show(); } else { ActivityActionCreators.hide(); } }; onChange = () => { this.setState(getStateFromStores()); }; render() { const info = this.state.dialogInfo; const isActivityOpen = this.state.isActivityOpen; let infoButtonClassName = classnames('button button--icon', { 'button--active': isActivityOpen }); if (info != null) { return ( <header className="toolbar"> <div className="pull-left"> <div className="toolbar__peer row"> <div className="toolbar__peer__body col-xs"> <span className="toolbar__peer__title">{info.name}</span> <span className="toolbar__peer__presence">{info.presence}</span> </div> </div> </div> <div className="toolbar__controls pull-right"> <div className="toolbar__controls__search pull-left hide"> <i className="material-icons">search</i> <input className="input input--search" placeholder={this.getIntlMessage('search')} type="search"/> </div> <div className="toolbar__controls__buttons pull-right"> <button className={infoButtonClassName} onClick={this.onClick}> <i className="material-icons">info</i> </button> <button className="button button--icon hide"> <i className="material-icons">more_vert</i> </button> </div> </div> </header> ); } else { return ( <header className="toolbar"> </header> ); } } } export default ToolbarSection;
app/javascript/mastodon/components/__tests__/display_name-test.js
foozmeat/mastodon
import React from 'react'; import renderer from 'react-test-renderer'; import { fromJS } from 'immutable'; import DisplayName from '../display_name'; describe('<DisplayName />', () => { it('renders display name + account name', () => { const account = fromJS({ username: 'bar', acct: 'bar@baz', display_name_html: '<p>Foo</p>', }); const component = renderer.create(<DisplayName account={account} />); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); });
packages/material-ui-icons/src/AirlineSeatLegroomExtra.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let AirlineSeatLegroomExtra = props => <SvgIcon {...props}> <path d="M4 12V3H2v9c0 2.76 2.24 5 5 5h6v-2H7c-1.66 0-3-1.34-3-3zm18.83 5.24c-.38-.72-1.29-.97-2.03-.63l-1.09.5-3.41-6.98c-.34-.68-1.03-1.12-1.79-1.12L11 9V3H5v8c0 1.66 1.34 3 3 3h7l3.41 7 3.72-1.7c.77-.36 1.1-1.3.7-2.06z" /> </SvgIcon>; AirlineSeatLegroomExtra = pure(AirlineSeatLegroomExtra); AirlineSeatLegroomExtra.muiName = 'SvgIcon'; export default AirlineSeatLegroomExtra;
src/scotch-night/App.js
SeattleScotchSociety/ScotchNight
// @flow import React, { Component } from 'react'; import Expo from 'expo'; import { Provider } from 'react-redux'; import Store from './app/Store'; import ScotchNight from './app/ScotchNight'; export default class App extends Component { constructor() { super(); this.state = { isLoading: false, isReady: false }; } async componentWillMount() { await Expo.Font.loadAsync({ Roboto: require('native-base/Fonts/Roboto.ttf'), Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'), Ionicons: require('native-base/Fonts/Ionicons.ttf') }); this.setState({ isReady: true }); } render() { return <Provider store={Store}><ScotchNight /></Provider>; } }
app/components/Home.js
yaolei/Node-Clound
import React from 'react'; import {bindActionCreators, createStore} from 'redux'; import 'babel-polyfill'; // 为generator 使用 import {connect, Provider} from 'react-redux'; import fetch from 'isomorphic-fetch'; export default class Home extends React.Component { constructor(props){ super(props); this.state = { scJsonData: [] } } render() { return( <div /> ); } }
test/date_input_test.js
flexport/react-datepicker
import React from 'react' import moment from 'moment' import ReactDOM from 'react-dom' import TestUtils from 'react-addons-test-utils' import DateInput from '../src/date_input.jsx' describe('DateInput', function () { it('adds disabled attribute to input field when disabled is passed as prop', function () { var dateInput = TestUtils.renderIntoDocument( <DateInput disabled /> ) expect(dateInput.disabled).to.not.equal(null) }) it('adds autocomplete attribute to input field when autoComplete is passed as prop', function () { var dateInput = TestUtils.renderIntoDocument( <DateInput autoComplete='off' /> ) expect(ReactDOM.findDOMNode(dateInput).autocomplete).to.equal('off') }) it('uses a custom className if provided', function () { const className = 'custom-class-name' var dateInput = TestUtils.renderIntoDocument( <DateInput className={className} /> ) expect(ReactDOM.findDOMNode(dateInput).className).to.contain(className) }) it('has a tabIndex if provided', function () { var dateInput = TestUtils.renderIntoDocument( <DateInput tabIndex={1} /> ) expect(ReactDOM.findDOMNode(dateInput).tabIndex).to.equal(1) }) it('should call onChangeDate when changing from null to valid date', function () { var date = moment() var dateFormat = 'YYYY-MM-DD' var callback = sinon.spy() var dateInput = TestUtils.renderIntoDocument( <DateInput date={null} dateFormat={dateFormat} onChangeDate={callback} /> ) var inputNode = dateInput.refs.input inputNode.value = date.format(dateFormat) TestUtils.Simulate.change(inputNode) assert(callback.calledOnce, 'must be called once') assert(date.isSame(callback.getCall(0).args[0], 'day'), 'must be called with correct date') }) it('should call onChangeDate when changing from valid date to another', function () { var dateFrom = moment() var dateTo = dateFrom.clone().add(1, 'day') var dateFormat = 'YYYY-MM-DD' var callback = sinon.spy() var dateInput = TestUtils.renderIntoDocument( <DateInput date={dateFrom} dateFormat={dateFormat} onChangeDate={callback} /> ) var inputNode = dateInput.refs.input inputNode.value = dateTo.format(dateFormat) TestUtils.Simulate.change(inputNode) assert(callback.calledOnce, 'must be called once') assert(dateTo.isSame(callback.getCall(0).args[0], 'day'), 'must be called with correct date') }) it('should call onChangeDate when changing from valid date to empty', function () { var callback = sinon.spy() var dateInput = TestUtils.renderIntoDocument( <DateInput date={moment()} onChangeDate={callback} /> ) var inputNode = dateInput.refs.input inputNode.value = '' TestUtils.Simulate.change(inputNode) assert(callback.withArgs(null).calledOnce, 'must be called once with null') }) it('should not call onChangeDate when changing from valid date to invalid', function () { var callback = sinon.spy() var dateInput = TestUtils.renderIntoDocument( <DateInput date={moment()} onChangeDate={callback} /> ) var inputNode = dateInput.refs.input inputNode.value = 'invalid' TestUtils.Simulate.change(inputNode) assert(!callback.called, 'must not be called') }) it('should call onChangeDate when changing from invalid date to valid', function () { var dateFrom = moment() var dateTo = dateFrom.clone().add(1, 'day') var dateFormat = 'YYYY-MM-DD' var callback = sinon.spy() var dateInput = TestUtils.renderIntoDocument( <DateInput date={dateFrom} dateFormat={dateFormat} onChangeDate={callback} /> ) var inputNode = dateInput.refs.input inputNode.value = 'invalid' TestUtils.Simulate.change(inputNode) inputNode.value = dateTo.format(dateFormat) TestUtils.Simulate.change(inputNode) assert(callback.calledOnce, 'must be called once') assert(dateTo.isSame(callback.getCall(0).args[0], 'day'), 'must be called with correct date') }) it('should not call onChangeDate when changing to a disabled date', function () { var date = moment() var dateFormat = 'YYYY-MM-DD' var callback = sinon.spy() var dateInput = TestUtils.renderIntoDocument( <DateInput date={null} excludeDates={[date]} dateFormat={dateFormat} onChangeDate={callback} /> ) var inputNode = dateInput.refs.input inputNode.value = date.format(dateFormat) TestUtils.Simulate.change(inputNode) assert(!callback.called, 'must not be called') }) it('should call onChangeDate with a date matching the format of the locale', function () { var locale = 'fr' var dateFormat = 'll' var callback = sinon.spy() var dateInput = TestUtils.renderIntoDocument( <DateInput date={null} locale={locale} dateFormat={dateFormat} onChangeDate={callback} /> ) var date = moment().locale(locale) var inputNode = dateInput.refs.input inputNode.value = date.format(dateFormat) TestUtils.Simulate.change(inputNode) assert(callback.called, 'must be called once') assert(date.isSame(callback.getCall(0).args[0], 'day'), 'must be called with correct date') }) it('should call onChange when changing the input text to an invalid date', function () { var onChange = sinon.spy() var dateInput = TestUtils.renderIntoDocument( <DateInput date={null} onChange={onChange} /> ) var inputNode = dateInput.refs.input inputNode.value = 'invalid' TestUtils.Simulate.change(inputNode) assert(onChange.calledOnce, 'must be called once') }) it('should call onChange when changing the input text to a valid date', function () { var date = moment() var dateFormat = 'll' var onChange = sinon.spy() var dateInput = TestUtils.renderIntoDocument( <DateInput date={null} dateFormat={dateFormat} onChange={onChange} /> ) var inputNode = dateInput.refs.input inputNode.value = date.format(dateFormat) TestUtils.Simulate.change(inputNode) assert(onChange.calledOnce, 'must be called once') }) it('should not call onChangeDate when onChange default prevented', function () { var date = moment() var dateFormat = 'll' var onChange = function (event) { event.preventDefault() } var onChangeDate = sinon.spy() var dateInput = TestUtils.renderIntoDocument( <DateInput date={null} dateFormat={dateFormat} onChange={onChange} onChangeDate={onChangeDate} /> ) var inputNode = dateInput.refs.input inputNode.value = date.format(dateFormat) TestUtils.Simulate.change(inputNode) assert(!onChangeDate.called, 'must not be called') }) describe('blurring', function () { it('should call onBlur when blurring the input', function () { var spy = sinon.spy() var dateInput = TestUtils.renderIntoDocument( <DateInput onBlur={spy} /> ) TestUtils.Simulate.blur(ReactDOM.findDOMNode(dateInput)) assert(spy.calledOnce, 'must be called once') }) it('should keep showing the selected date if input is same date', function () { var date = moment() var dateFormat = 'YYYY-MM-DD' var formattedDate = date.format(dateFormat) var dateInput = TestUtils.renderIntoDocument( <DateInput date={date} dateFormat={dateFormat} /> ) var inputNode = dateInput.refs.input inputNode.value = formattedDate TestUtils.Simulate.change(inputNode) TestUtils.Simulate.blur(inputNode) expect(inputNode.value).to.equal(formattedDate) }) it('should show the selected date if input is invalid', function () { var date = moment() var dateFormat = 'YYYY-MM-DD' var dateInput = TestUtils.renderIntoDocument( <DateInput date={date} dateFormat={dateFormat} /> ) var inputNode = dateInput.refs.input inputNode.value = 'invalid' TestUtils.Simulate.change(inputNode) TestUtils.Simulate.blur(inputNode) expect(inputNode.value).to.equal(date.format(dateFormat)) }) it('should empty the input if no date selected and input is invalid', function () { var dateInput = TestUtils.renderIntoDocument( <DateInput /> ) var inputNode = dateInput.refs.input inputNode.value = 'invalid' TestUtils.Simulate.change(inputNode) TestUtils.Simulate.blur(inputNode) expect(inputNode.value).to.equal('') }) }) describe('localization', function () { var dateFormat = 'LL' function testLocale (dateInput, date, locale) { var localized = date.clone().locale(locale) var inputNode = dateInput.refs.input expect(inputNode.value).to.equal(localized.format(dateFormat)) } it('should use the globally-defined locale by default', function () { var date = moment() var dateInput = TestUtils.renderIntoDocument( <DateInput date={date} dateFormat={dateFormat} /> ) testLocale(dateInput, date, moment.locale()) }) it('should use the locale specified as a prop', function () { var locale = 'fr' var date = moment().locale(locale) var dateInput = TestUtils.renderIntoDocument( <DateInput date={date} dateFormat={dateFormat} locale={locale} /> ) testLocale(dateInput, date, locale) }) it('should override the locale of the date with the globally-defined locale', function () { var date = moment().locale('fr') var dateInput = TestUtils.renderIntoDocument( <DateInput date={date} dateFormat={dateFormat} /> ) testLocale(dateInput, date, moment.locale()) }) it('should override the locale of the date with the locale prop', function () { var locale = 'fr' var date = moment() var dateInput = TestUtils.renderIntoDocument( <DateInput date={date} dateFormat={dateFormat} locale={locale} /> ) testLocale(dateInput, date, locale) }) }) describe('dateFormat', function () { it('should use the date format of the global locale by default', function () { var date = moment() var dateInput = TestUtils.renderIntoDocument( <DateInput date={date} /> ) expect(dateInput.refs.input.value).to.equal(date.format('L')) }) it('should use the date format of the locale prop', function () { var locale = 'fr' var date = moment().locale(locale) var dateInput = TestUtils.renderIntoDocument( <DateInput date={date} locale={locale} /> ) expect(dateInput.refs.input.value).to.equal(date.format('L')) }) it('should use the date format of the dateFormat prop', function () { var locale = 'fr' var dateFormat = 'LL' var date = moment().locale(locale) var dateInput = TestUtils.renderIntoDocument( <DateInput date={date} dateFormat={dateFormat} locale={locale} /> ) expect(dateInput.refs.input.value).to.equal(date.format(dateFormat)) }) }) describe('localeChange', function () { it('should rerender with correct format on locale props change', function () { // Need to use ReactDom Render var node = document.createElement('div') var date = moment() date.locale('fr') var dateInput = ReactDOM.render( <DateInput date={date} locale='fr'/> , node) expect(dateInput.refs.input.value).to.equal(date.format('L')) date.locale('en') dateInput = ReactDOM.render( <DateInput date={date} locale='en'/> , node) expect(dateInput.refs.input.value).to.equal(date.format('L')) }) it('should rerender with correct format on format props change', function () { // Need to use ReactDom Render var node = document.createElement('div') var date = moment() var dateFormat = 'YYYY-MM-DD' var dateInput = ReactDOM.render( <DateInput date={date} dateFormat={dateFormat}/> , node) expect(dateInput.refs.input.value).to.equal(date.format(dateFormat)) dateFormat = 'DD-MM-YYYY' dateInput = ReactDOM.render( <DateInput date={date} dateFormat={dateFormat}/> , node) expect(dateInput.refs.input.value).to.equal(date.format(dateFormat)) }) }) })
src/components/Header/Header.js
golotiuk/Good_luck
import React, { Component } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Header.scss'; import Link from '../Link'; import Navigation from '../Navigation'; class Header extends Component { render() { return ( <div className={s.root}> <div className={s.container}> <Navigation className={s.nav} /> <Link className={s.brand} to="/"> <img src={require('./Logo.jpg')} width="38" height="38" alt="React" /> <span className={s.brandTxt}>Good luck!!!</span> </Link> <div className={s.banner}> <h1 className={s.bannerTitle}><a href="/admin">Строим новый ЖК</a></h1> <p className={s.bannerDesc}>Надеемся что найдете тут свое счастье =)</p> </div> </div> </div> ); } } export default withStyles(Header, s);
src/adjudicator/adjudicationTable.js
dgretho/adjudication
import React from 'react'; import { render } from 'react-dom'; import { Table } from 'react-bootstrap'; function AdjudicationTableRow(props) { return ( // TODO: Set style using a class <tr onClick={props.onClick} style={{cursor: 'pointer'}}> <td>{props.case.address}</td> <td>{props.case.depositAmount}</td> </tr> ); } function AdjudicationTable(props) { var rows = props.cases.map(function(step) { return (<AdjudicationTableRow case={step} key={step.caseReference} onClick={() => props.onRowClick(step.caseReference)}/>); }); return ( <Table striped bordered condensed hover> <thead> <tr> <th>Address</th> <th>Deposit Amount</th> </tr> </thead> <tbody> {rows} </tbody> </Table> ); } export default AdjudicationTable;
src/pages/homepage/list/RecommendTopics.js
HeliumLau/Hoop-react
import React from 'react'; import Header from 'components/Header.js'; import ArticleList from 'components/ArticleList.js'; import './normalcontainer.less'; export default class RecommendTopics extends React.Component { constructor(props) { super(props); this.state = { articlelist: [ { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 } ] } } render() { return ( <div className="normal-container"> <Header headerName="我推荐的帖子" /> <ArticleList list={this.state.articlelist} /> </div> ) } }
friday-ui/src/routes.js
freekbrinkhuis/friday
import React, { Component } from 'react'; import { BrowserRouter, Switch, Route } from 'react-router-dom'; import App from './Components/App'; import Dashboard from './Components/Dashboard'; import NotFound from './Components/NotFound'; class Routes extends Component { render(){ return( <BrowserRouter> <div> <Route path="/" component={App} /> <Route path="/dashboard" component={Dashboard} /> </div> </BrowserRouter> ) } }; export default Routes;
client/src/components/TeamsList/TeamsList.js
ccabrales/espn-fantasy-stats
import React from 'react'; import PropTypes from 'prop-types'; import { Table, Image } from 'semantic-ui-react'; import sortBy from 'lodash.sortby'; import { getValue } from '../../services/utility'; /** * Display the teams in a sortable table * @param teamData */ class TeamsList extends React.Component { /** * Set the initial state for the table * @param props */ constructor(props) { super(props); this.state = { column: null, data: getValue('data.teams', props.teamData, []), direction: null }; } /** * Handle the sorting of the teams based on the column clicked * @param clickedColumn */ handleSort = clickedColumn => () => { const { column, data, direction } = this.state; if (column !== clickedColumn) { this.setState({ column: clickedColumn, data: sortBy(data, [ clickedColumn ]), direction: 'ascending', }); return; } this.setState({ data: data.reverse(), direction: direction === 'ascending' ? 'descending' : 'ascending', }); }; render() { const { column, data, direction } = this.state; if (!data || data.length === 0) { return null; } return ( <Table celled padded sortable> <Table.Header> <Table.Row> <Table.HeaderCell>Logo</Table.HeaderCell> <Table.HeaderCell sorted={column === 'teamName' ? direction : null} onClick={this.handleSort('teamName')} > Team Name </Table.HeaderCell> <Table.HeaderCell sorted={column === 'overallStanding' ? direction : null} onClick={this.handleSort('overallStanding')} > Standing </Table.HeaderCell> <Table.HeaderCell sorted={column === 'teamRecord' ? direction : null} onClick={this.handleSort('teamRecord')} > Record </Table.HeaderCell> <Table.HeaderCell sorted={column === 'pointsFor' ? direction : null} onClick={this.handleSort('pointsFor')} > Points For </Table.HeaderCell> <Table.HeaderCell sorted={column === 'pointsAgainst' ? direction : null} onClick={this.handleSort('pointsAgainst')} > Points Against </Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> {data.map(team => { const { logoUrl, teamName, overallStanding, teamRecord, pointsFor, pointsAgainst, teamId } = team; return ( <Table.Row key={teamId}> <Table.Cell> {logoUrl && <Image src={logoUrl} size='small' /> } </Table.Cell> <Table.Cell> {teamName} </Table.Cell> <Table.Cell> {overallStanding} </Table.Cell> <Table.Cell> {teamRecord} </Table.Cell> <Table.Cell> {pointsFor} </Table.Cell> <Table.Cell> {pointsAgainst} </Table.Cell> </Table.Row> ); })} </Table.Body> </Table> ); } } TeamsList.propTypes = { teamData: PropTypes.object.isRequired }; export default TeamsList;
src/client/components/filter/FilterCards/FilterCards.component.js
DBCDK/content-first
import React from 'react'; import Swiper from 'react-id-swiper'; import {isMobile} from 'react-device-detect'; import Heading from '../../base/Heading'; import Icon from '../../base/Icon'; import T from '../../base/T'; import {withTagsFromUrl} from '../../hoc/AdressBar'; import CardList from './templates/CardList.component.js'; import CardRange from './templates/CardRange.component.js'; import './FilterCards.css'; const params = { containerClass: 'Filters__swiper-container', wrapperClass: 'Filters__swiper-wrapper', mousewheel: false, slidesPerView: 'auto', slidesPerGroup: 1, slideToClickedSlide: window.innerWidth < 576, navigation: { nextEl: '.Filters__next', prevEl: '.Filters__prev' }, renderNextButton: () => ( <div className="Filters__next"> <span> <T component="filter" name="forward" /> </span> <Icon name="chevron_right" /> </div> ), renderPrevButton: () => ( <div className="Filters__prev hidden"> <Icon name="chevron_left" /> <span> <T component="filter" name="previous" /> </span> </div> ) }; class FilterCard extends React.Component { getTemplate(template) { switch (template) { case 'CardList': return CardList; case 'CardRange': return CardRange; default: return CardList; } } render() { const {filter, className, expanded} = this.props; const expandedClass = expanded ? 'FilterCard-expanded' : ''; const Template = this.getTemplate(filter.template); const borderColor = filter.border.active ? filter.border.color : null; const borderClass = filter.border.active ? 'border--top' : ''; return ( <div className={`FilterCard__container ${className} ${expandedClass}`} data-cy={ filter.title .toLowerCase() .split(' ') .join('-') || '' } > <div className={`FilterCard`}> <div onClick={e => this.props.onCardClick(e)} className="FilterCard__cover" style={{backgroundImage: `url(/${filter.image})`}} > <Icon name="close" className={ 'FilterCard__close' + (isMobile ? ' increase-touch-area-small' : '') } /> </div> <div className={`FilterCard__content ${borderClass}`} style={{borderTopColor: borderColor}} onClick={e => this.props.onCardClick(e)} tabIndex="0" > <Heading type="title" className="FilterCard__heading mb0 mt0"> {filter.title} </Heading> {<Template {...this.props} />} </div> </div> </div> ); } } class Filters extends React.Component { constructor(props) { super(); this.state = { showDimmer: false, oFilters: props.filterCards }; } componentWillUnmount() { this.closeCards(); } toggleCardExpanded(e, title) { let oFilters = this.state.oFilters; const closeOnSelect = oFilters[title].closeOnSelect; const coverClick = e.target.classList.contains('FilterCard__cover'); const closeClick = e.target.classList.contains('FilterCard__close'); // Close other expanded oFilters = this.changeExpandedProp(false, title); if (coverClick || closeClick) { /* force close on cover or close click */ oFilters[title].expanded = !this.state.oFilters[title].expanded; } else { oFilters[title].expanded = closeOnSelect ? !this.state.oFilters[title].expanded : true; } this.setState({oFilters}); } closeCards() { const oFilters = this.changeExpandedProp(false); this.setState({oFilters}); } changeExpandedProp(status, exclude = '') { let oFilters = this.state.oFilters; for (let key in oFilters) { if (oFilters.hasOwnProperty(key)) { if (oFilters[key] !== oFilters[exclude]) { oFilters[key].expanded = status; } } } return oFilters; } render() { const aFilters = Object.values(this.state.oFilters); const expandedCards = aFilters.filter(card => card.expanded); const dimmerClass = expandedCards.length > 0 ? 'Filters__dimmer-show' : ''; return ( <React.Fragment> <div className="filters--wrap"> <Swiper {...params} ref={node => { if (node) { this.swiper = node.swiper; } }} > {aFilters.map(filter => { if (filter.show) { return ( <FilterCard key={filter.title} expanded={filter.expanded} onCardClick={e => this.toggleCardExpanded(e, filter.title)} filter={filter} {...this.props} /> ); } return null; })} <div className="FilterCard__space" /> </Swiper> </div> <div className={`Filters__dimmer ${dimmerClass}`} onClick={() => this.closeCards()} data-cy="filterDimmer" /> </React.Fragment> ); } } export default withTagsFromUrl(Filters);
app/routes/Course/routes/Announcements/components/Sidebar.js
jefferchang/reactApp
/*globals COURSES:true */ import React from 'react' import { Link } from 'react-router' class AnnouncementsSidebar extends React.Component { render() { let { announcements } = COURSES[this.props.params.courseId] return ( <div> <h3>Sidebar Assignments</h3> <ul> {announcements.map(announcement => ( <li key={announcement.id}> <Link to={`/course/${this.props.params.courseId}/announcements/${announcement.id}`}> {announcement.title} </Link> </li> ))} </ul> </div> ) } } module.exports = AnnouncementsSidebar
src/js/components/app.js
MiladNazeri/stockHelper
import '../stylesheets/main.scss'; import React from 'react'; class App extends React.Component { constructor(props){ super(props); this.state={ } } render(){ return( <div> {this.props.children} </div> ) } } export default App; //input formula to use LAST //Global start and end date //Input to enter stock you want to check //Plus to add another stock //all stocks get put in array //object built from api call on each stock in array //analaysis based on formula // // // // // // <div id="inputSymbol"> // <p>Enter Stock</p> // <input id="startDate" class="datePick required" type="text" Placeholder="From" /> // <input id="endDate" class="datePick" type="text" Placeholder="To" /> // <input id="txtSymbol" class="required" Placeholder="Symbol" /> // <button ID="submit">Submit</button> // </div> // <div class="realtime"> // <div><p>Name</p><span id="symbol"></span></div> // <div><p>RealtimeBid</p><span id="bidRealtime"></span></div> // </div> // <div class="historical"> // <div><p>Date</p><span id="date"></span></div> // <div><p>Price Close</p><span id="closeValue"></span></div> // <div><p>Price High</p><span id="highValue"></span></div> // <div><p>Price Low</p><span id="lowValue"></span></div> // <div><p>Volume</p><span id="volume"></span></div> // </div>
internals/templates/notFoundPage.js
ReelTalkers/reeltalk-web
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route */ import React from 'react' export function NotFound() { return ( <h1>Page Not Found</h1> ) } export default NotFound
packages/reactor-conference-app/src/schedule/Schedule.js
dbuhrman/extjs-reactor
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { toggleSearch, filterByDay, toggleFavorite, filterByFavorites } from './actions'; import { setTitle } from '../actions'; import { loadEvent } from '../event/actions'; import { Container, Button, TabPanel, Panel, Toolbar, SearchField, List } from '@extjs/ext-react'; import ScheduleList from './ScheduleList'; import Event from '../event/Event'; class Schedule extends Component { constructor({ store }) { super(); this.storeDefaults = { source: store, autoDestroy: true, grouper: { property: 'start_time', sortProperty: 'startDate' } }; this.stores = [ Ext.create('Ext.data.ChainedStore', { ...this.storeDefaults, filters: [{ property: 'date', value: 'Monday, November 7' }] }), Ext.create('Ext.data.ChainedStore', { ...this.storeDefaults, filters: [{ property: 'date', value: 'Tuesday, November 8' }] }), Ext.create('Ext.data.ChainedStore', { ...this.storeDefaults, filters: [{ property: 'date', value: 'Wednesday, November 9' }] }), Ext.create('Ext.data.ChainedStore', { ...this.storeDefaults, filters: [{ property: 'favorite', value: true }], grouper: { groupFn: (item) => `${item.get('date')}, ${item.get('start_time')}`, sortProperty: 'startDate' } }) ] } state = { activeItem: 0 } stores = [ Ext.create('Ext.data.ChainedStore', ) ] componentDidMount = () => { this.updateData(); } componentDidUpdate = (prevProps) => { this.updateData(prevProps); } componentWillReceiveProps(nextProps) { if (nextProps.event !== this.props.event) { this.setState({ activeItem: this.activeItemForEvent(nextProps.event) }) } } activeItemForEvent(event) { for (let i=0; i<this.stores.length; i++) { if (this.stores[i].contains(event)) { return i; } } return 0; } updateData = (prevProps) => { const { dispatch } = this.props; const id = this.props.match.params.id; if (!prevProps || prevProps.match.params.id !== id) { dispatch(loadEvent(id, 'Schedule')) } } render() { const { store, event, match } = this.props; const showEvent = match.params.id && (Ext.os.is.Phone || event); const banner = ( <Container docked="top" className="app-banner"> <span className="app-banner-content">ExtReact Conference</span> </Container> ) return ( <Container activeItem={showEvent ? 1 : 0} platformConfig={{ "!phone": { layout: 'hbox' }, "phone": { layout: { type: 'card', animation: 'slide' } } }} > { !Ext.os.is.Phone && banner } <TabPanel flex={1} tabBar={{ shadow: true}} maxWidth={showEvent && 500} activeItem={this.state.activeItem} platformConfig={{ "!phone": { flex: 1 } }} > { Ext.os.is.Phone && banner } <ScheduleList title={Ext.os.is.Phone ? "MON" : 'MONDAY'} event={event} dataStore={this.stores[0]} pinHeaders /> <ScheduleList title={Ext.os.is.Phone ? "TUE" : 'TUESDAY'} event={event} dataStore={this.stores[1]} pinHeaders /> <ScheduleList title={Ext.os.is.Phone ? "WED" : 'WEDNESDAY'} event={event} dataStore={this.stores[2]} pinHeaders /> <ScheduleList iconCls="md-icon-star" tab={{ maxWidth: Ext.os.is.Phone ? 60 : 90 }} dataStore={this.stores[3]} pinHeaders /> </TabPanel> { (Ext.os.is.Phone || showEvent) && <Event event={event} flex={1} header={!Ext.os.is.Phone}/> } </Container> ) } } const mapStateToProps = ({ schedule, event }) => { return { ...schedule, event: (event || {}).record }; } export default connect(mapStateToProps)(Schedule);
test/test_helper.js
mcrice123/simple-react-example
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
docs/site/src/demos/dialogs/AlertDialog.js
und3fined/material-ui
// @flow weak import React, { Component } from 'react'; import Button from 'material-ui/Button'; import { Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, } from 'material-ui/Dialog'; export default class AlertDialog extends Component { state = { open: false, }; handleRequestClose = () => this.setState({ open: false }); render() { return ( <div> <Button onClick={() => this.setState({ open: true })}> Open alert dialog </Button> <Dialog open={this.state.open} onRequestClose={this.handleRequestClose} > <DialogTitle>{"Use Google's location service?"}</DialogTitle> <DialogContent> <DialogContentText> Let Google help apps determine location. This means sending anonymous location data to Google, even when no apps are running. </DialogContentText> </DialogContent> <DialogActions> <Button onClick={this.handleRequestClose} primary>Disagree</Button> <Button onClick={this.handleRequestClose} primary>Agree</Button> </DialogActions> </Dialog> </div> ); } }
public/src/admin/editor/BlockStyleControls.react.js
SLedunois/personal-website
import React from 'react'; import StyleButton from './StyleButton.react'; import BLOCK_TYPES from './blockTypes'; const BlockStyleControls = props => { const { editorState } = props; const selection = editorState.getSelection(); const blockType = editorState .getCurrentContent() .getBlockForKey(selection.getStartKey()) .getType(); return ( <div className="RichEditor-controls"> {BLOCK_TYPES.map(type => <StyleButton key={type.label} active={type.style === blockType} label={type.label} onToggle={props.onToggle} style={type.style} /> )} </div> ); }; export default BlockStyleControls;
src/components/Navigation.js
mgaebler/kicknow-client-web
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { openDrawer, closeDrawer } from '../modules/navigation/actions' import { Toolbar, ToolbarRow, ToolbarTitle, ToolbarSection, Icon } from 'react-mdc-web' import Menu from './Menu' class Navigation extends React.Component { static get propTypes() { return { onInput: PropTypes.func } } ESCAPE_KEY = 27 constructor(props) { super(props) this.toggleDrawer = this.toggleDrawer.bind(this) this._handleKeyDown = this._handleKeyDown.bind(this) } componentWillMount() { document.addEventListener('click', this._handleDocumentClick, false) document.addEventListener('keydown', this._handleKeyDown.bind(this)) } componentWillUnmount() { document.removeEventListener('click', this._handleDocumentClick, false) document.removeEventListener('keydown', this._handleKeyDown.bind(this)) } _handleKeyDown(event) { switch (event.keyCode) { case this.ESCAPE_KEY: this.props.dispatch(closeDrawer()) break default: this.props.dispatch(closeDrawer()) break } } toggleDrawer() { this.props.dispatch(this.props.drawer ? closeDrawer() : openDrawer()) } render() { return ( <div> <Menu open={this.props.drawer} dispatch={this.props.dispatch} /> <Toolbar fixed> <ToolbarRow> <ToolbarSection align="start"> <Icon onClick={this.toggleDrawer} name="menu" /> </ToolbarSection> <ToolbarSection align="start"> <ToolbarTitle>Kicknow</ToolbarTitle> </ToolbarSection> <ToolbarSection align="end"> <ToolbarTitle> <Icon name="account_circle" /> </ToolbarTitle> </ToolbarSection> </ToolbarRow> </Toolbar> </div> ) } } function mapStateToProps(state) { let { drawer } = state return { drawer } } export default connect(mapStateToProps)(Navigation)