path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
components/ShopsAndNotification.js
CoffeeApp/clientSide
import React from 'react' import { Match, hashHistory } from 'react-router' import SelectShop from './SelectShop' import Notification from './Notification' import ToggleButtons from './ToggleButtons' import Cart from './Cart' class ShopsAndNotification extends React.Component { constructor(props) { super(props) } render() { return ( <div> {(this.props.screen === 'shops') ? <ToggleButtons {...this.props} /> : null } {(this.props.screen === 'shops') ? <SelectShop {...this.props} /> : null} { this.props.notification ? <Notification {...this.props} /> : null } </div> ) } } export default ShopsAndNotification
app/app.js
haxorbit/chiron
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { ConnectedRouter } from 'react-router-redux'; import FontFaceObserver from 'fontfaceobserver'; import createHistory from 'history/createHashHistory'; import 'sanitize.css/sanitize.css'; // Import root app import App from 'containers/App'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Load the favicon, the manifest.json file and the .htaccess file /* eslint-disable import/no-webpack-loader-syntax */ import '!file-loader?name=[name].[ext]!./images/favicon.ico'; import '!file-loader?name=[name].[ext]!./images/icon-72x72.png'; import '!file-loader?name=[name].[ext]!./images/icon-96x96.png'; import '!file-loader?name=[name].[ext]!./images/icon-120x120.png'; import '!file-loader?name=[name].[ext]!./images/icon-128x128.png'; import '!file-loader?name=[name].[ext]!./images/icon-144x144.png'; import '!file-loader?name=[name].[ext]!./images/icon-152x152.png'; import '!file-loader?name=[name].[ext]!./images/icon-167x167.png'; import '!file-loader?name=[name].[ext]!./images/icon-180x180.png'; import '!file-loader?name=[name].[ext]!./images/icon-192x192.png'; import '!file-loader?name=[name].[ext]!./images/icon-384x384.png'; import '!file-loader?name=[name].[ext]!./images/icon-512x512.png'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; // eslint-disable-line import/extensions /* eslint-enable import/no-webpack-loader-syntax */ import configureStore from './configureStore'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS reset and Global Styles import './global-styles'; // Observe loading of Open Sans (to remove open sans, remove the <link> tag in // the index.html file and this observer) const openSansObserver = new FontFaceObserver('Open Sans', {}); // When Open Sans is loaded, add a font-family using Open Sans to the body openSansObserver.load().then(() => { document.body.classList.add('fontLoaded'); }, () => { document.body.classList.remove('fontLoaded'); }); // Create redux store with history const initialState = {}; const history = createHistory(); const store = configureStore(initialState, history); const MOUNT_NODE = document.getElementById('app'); const render = (messages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={messages}> <ConnectedRouter history={history}> <App /> </ConnectedRouter> </LanguageProvider> </Provider>, MOUNT_NODE ); }; if (module.hot) { // Hot reloadable React components and translation json files // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept(['./i18n', 'containers/App'], () => { ReactDOM.unmountComponentAtNode(MOUNT_NODE); render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(import('intl')); })) .then(() => Promise.all([ import('intl/locale-data/jsonp/en.js'), import('intl/locale-data/jsonp/de.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require }
App/Components/FullButton.story.js
samuraitruong/react-native-fx260
import React from 'react' import { storiesOf } from '@storybook/react-native' import FullButton from './FullButton' storiesOf('FullButton') .add('Default', () => ( <FullButton text='A simple button' /> )) .add('Custom Style', () => ( <FullButton text='Style Me Up!' styles={{ backgroundColor: 'blue' }} /> ))
node_modules/react-router/es/MemoryRouter.js
webtutorial/builder
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import warning from 'warning'; import React from 'react'; import PropTypes from 'prop-types'; import createHistory from 'history/createMemoryHistory'; import Router from './Router'; /** * The public API for a <Router> that stores location in memory. */ var MemoryRouter = function (_React$Component) { _inherits(MemoryRouter, _React$Component); function MemoryRouter() { var _temp, _this, _ret; _classCallCheck(this, MemoryRouter); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.history = createHistory(_this.props), _temp), _possibleConstructorReturn(_this, _ret); } MemoryRouter.prototype.componentWillMount = function componentWillMount() { warning(!this.props.history, '<MemoryRouter> ignores the history prop. To use a custom history, ' + 'use `import { Router }` instead of `import { MemoryRouter as Router }`.'); }; MemoryRouter.prototype.render = function render() { return React.createElement(Router, { history: this.history, children: this.props.children }); }; return MemoryRouter; }(React.Component); MemoryRouter.propTypes = { initialEntries: PropTypes.array, initialIndex: PropTypes.number, getUserConfirmation: PropTypes.func, keyLength: PropTypes.number, children: PropTypes.node }; export default MemoryRouter;
packages/canvas-rce/src/rce/plugins/shared/Upload/UnsplashSVG.js
djbender/canvas-lms
/* * Copyright (C) 2019 - 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' const UnsplashSVG = props => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 457.19 104.19" {...props}> <path d="M59.88 38.66h27.53v48.75H0V38.66h27.53v24.37h32.35zm93 25c0 8.25-5.45 13.13-12.9 13.13-7.28 0-12.81-4.88-12.81-13.13V24.41h-12.22v39.13c0 15.45 11 25.21 25.06 25.21s25.15-9.76 25.15-25.21V24.41h-12.25zm43.7-21.13c-4.7 0-9.94 2-12.6 6.57v-5.41h-11.45v43.64h11.81v-25.1c0-5 3-9 8.16-9 5.68 0 8.08 3.82 8.08 8.7v25.4h11.8V59.82c.03-9.59-4.94-17.31-15.77-17.31zm43.31 18.37l-6.48-1.33c-2.47-.5-4-1.77-4-3.9 0-2.49 2.23-4.35 5.33-4.35 4.36 0 6.09 2.25 6.51 4.88h10.18c-.08-6-4.83-13.84-16.51-13.84-9.41 0-16.33 6.47-16.33 14.28 0 6.13 3.81 11.19 12.24 13l6.05 1.33c3.37.71 4.7 2.31 4.7 4.26 0 2.31-2.14 4.35-6 4.35-4.71 0-7.27-2.68-7.87-5.79h-10.5c.59 6.53 5.32 14.84 18.46 14.84 11.45 0 17.22-7.28 17.22-14.38-.01-6.36-4.36-11.59-12.97-13.37zm63.19 4.53c0 13.22-8.26 23-20.59 23-6 0-10.48-2.4-12.61-5.33v21.13h-11.8V43.67h11.45v5.41c2-3.37 6.83-6.39 13.4-6.39 12.81 0 20.18 9.76 20.18 22.72zm-11.63.09c0-7.72-4.79-12.25-10.83-12.25s-10.91 4.53-10.91 12.25 4.88 12.33 10.91 12.33 10.91-4.54 10.91-12.35zm68-21.83h11.45v43.64h-11.8v-5.31c-2 3.5-6.57 6.38-12.61 6.38-12.33 0-20.59-9.77-20.59-23 0-13 7.37-22.72 20.15-22.72 6.57 0 11.32 3.05 13.4 6.39zm-.18 21.83c0-7.72-4.88-12.25-10.91-12.25s-10.83 4.51-10.83 12.23 4.79 12.33 10.83 12.33 10.92-4.6 10.92-12.33zm-50.66 21.81h11.8V24.41h-11.8zm132.35-44.81c-4.17 0-9 1.41-11.81 4.78V24.41h-11.8v62.91h11.8V61.68c.27-4.8 3.2-8.52 8.17-8.52 5.68 0 8.08 3.83 8.07 8.71v25.47h11.81V59.82c-.01-9.59-5.15-17.3-16.24-17.3zm-42 18.36l-6.43-1.33c-2.47-.5-4-1.77-4-3.9 0-2.49 2.22-4.35 5.33-4.35 4.35 0 6.08 2.25 6.5 4.88h10.17c-.08-6-4.83-13.84-16.51-13.84-9.41 0-16.33 6.47-16.33 14.28 0 6.13 3.82 11.19 12.25 13l6 1.33c3.37.71 4.7 2.31 4.7 4.26 0 2.31-2.14 4.35-6 4.35-4.71 0-7.27-2.68-7.87-5.79h-10.49c.58 6.53 5.31 14.84 18.45 14.84 11.45 0 17.22-7.28 17.22-14.38 0-6.34-4.35-11.57-12.95-13.35zM59.88 0H27.53v24.37h32.35z" /> </svg> ) export default UnsplashSVG
node_modules/semantic-ui-react/src/views/Statistic/Statistic.js
SuperUncleCat/ServerMonitoring
import cx from 'classnames' import _ from 'lodash' import PropTypes from 'prop-types' import React from 'react' import { childrenUtils, customPropTypes, getElementType, getUnhandledProps, META, SUI, useKeyOnly, useValueAndKey, } from '../../lib' import StatisticGroup from './StatisticGroup' import StatisticLabel from './StatisticLabel' import StatisticValue from './StatisticValue' /** * A statistic emphasizes the current value of an attribute. */ function Statistic(props) { const { children, className, color, floated, horizontal, inverted, label, size, text, value, } = props const classes = cx( 'ui', color, size, useValueAndKey(floated, 'floated'), useKeyOnly(horizontal, 'horizontal'), useKeyOnly(inverted, 'inverted'), 'statistic', className, ) const rest = getUnhandledProps(Statistic, props) const ElementType = getElementType(Statistic, props) if (!childrenUtils.isNil(children)) return <ElementType {...rest} className={classes}>{children}</ElementType> return ( <ElementType {...rest} className={classes}> <StatisticValue text={text} value={value} /> <StatisticLabel label={label} /> </ElementType> ) } Statistic._meta = { name: 'Statistic', type: META.TYPES.VIEW, } Statistic.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** A statistic can be formatted to be different colors. */ color: PropTypes.oneOf(SUI.COLORS), /** A statistic can sit to the left or right of other content. */ floated: PropTypes.oneOf(SUI.FLOATS), /** A statistic can present its measurement horizontally. */ horizontal: PropTypes.bool, /** A statistic can be formatted to fit on a dark background. */ inverted: PropTypes.bool, /** Label content of the Statistic. */ label: customPropTypes.contentShorthand, /** A statistic can vary in size. */ size: PropTypes.oneOf(_.without(SUI.SIZES, 'big', 'massive', 'medium')), /** Format the StatisticValue with smaller font size to fit nicely beside number values. */ text: PropTypes.bool, /** Value content of the Statistic. */ value: customPropTypes.contentShorthand, } Statistic.Group = StatisticGroup Statistic.Label = StatisticLabel Statistic.Value = StatisticValue export default Statistic
ui/src/containers/Visualisations/TemplateMostPopularVerbs/Card.js
LearningLocker/learninglocker
import React from 'react'; import PropTypes from 'prop-types'; import { Map } from 'immutable'; import TemplateCard from '../components/TemplateCard'; import buildModel from './buildModel'; import { title, image } from './constants'; /** * @param {immutable.Map} props.model * @param {() => void} props.saveModel */ const Card = ({ model, saveModel, }) => ( <TemplateCard title={title} srcImage={image} onClick={() => saveModel({ attrs: buildModel(model) })} /> ); Card.propTypes = { model: PropTypes.instanceOf(Map).isRequired, saveModel: PropTypes.func.isRequired, }; export default React.memo(Card);
Realization/frontend/czechidm-core/src/content/audit/loggingEvent/LoggingEventExceptionDetail.js
bcvsolutions/CzechIdMng
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; // import * as Basic from '../../../components/basic'; import * as Advanced from '../../../components/advanced'; import { LoggingEventExceptionManager } from '../../../redux'; const EU_BCVSOLUTIONS_PREFIX = 'eu.bcvsolutions.idm.'; const uiKey = 'loggingEventExceptionUiKey'; /** * Logging event exception detail * * TODO:? there is two redundant get for exception entities (rows), * because advanced table not supported data props and basic table not supported pageable, * is not possible get entities in one request. * * @author Ondřej Kopr */ const manager = new LoggingEventExceptionManager(); class LoggingEventExceptionDetail extends Basic.AbstractContent { constructor(props, context) { super(props, context); this.state = { showRawError: false }; } componentDidMount() { const { eventId } = this.props; this.context.store.dispatch( manager.fetchEntities( manager.getDefaultSearchParameters() .setSize(1000) // setSize(null) not working for now .setFilter('event', eventId), `${uiKey}-${eventId}`) ); } _transformEntitiesToText(entities) { let rawEntities = ''; if (entities) { for (const entity in entities) { if (entities.hasOwnProperty(entity)) { rawEntities += entities[entity].traceLine + '\n'; } } } return rawEntities; } getContentKey() { return 'content.audit.logging-event'; } _showRawError(show) { this.setState({ showRawError: show }); } render() { const { eventId, showLoading, entities } = this.props; const { showRawError } = this.state; const rawEntities = this._transformEntitiesToText(entities); return ( <div> <Advanced.Table ref="table" buttons={ <Basic.Button showLoading={showLoading} className="btn-xs" hidden={!entities && entities.size === 0} onClick={this._showRawError.bind(this, true)}> <Basic.Icon icon="fa:file-code-o" /> {' '} { this.i18n('rawSource') } </Basic.Button> } manager={manager} forceSearchParameters={manager.getDefaultSearchParameters().setFilter('event', eventId)} showId={false} data={entities} showLoading={showLoading} rowClass={({ rowIndex, data }) => { if (data[rowIndex].traceLine.indexOf(EU_BCVSOLUTIONS_PREFIX) + 1) { return 'warning'; } }}> <Advanced.Column property="id" width={ 50 } /> <Advanced.Column property="traceLine" className="pre"/> </Advanced.Table> <Basic.Modal bsSize="large" show={showRawError} onHide={this._showRawError.bind(this, false)} backdrop="static" keyboard={!showLoading}> <Basic.Modal.Header closeButton={!showLoading} text={this.i18n('exceptions')}/> <Basic.Modal.Body> <Basic.ScriptArea showMaximalizationBtn={false} height="50em" value={rawEntities}/> </Basic.Modal.Body> <Basic.Modal.Footer> <Basic.Button level="link" onClick={this._showRawError.bind(this, false)} showLoading={showLoading}> {this.i18n('button.close')} </Basic.Button> </Basic.Modal.Footer> </Basic.Modal> </div> ); } } LoggingEventExceptionDetail.propTypes = { eventId: PropTypes.string }; LoggingEventExceptionDetail.defaultProps = { }; function select(state, component) { const { eventId } = component; // return { entities: manager.getEntities(state, `${uiKey}-${eventId}`), showLoading: manager.isShowLoading(state, `${uiKey}-${eventId}`) }; } export default connect(select)(LoggingEventExceptionDetail);
client/test/components/Group.spec.js
enodi/PostIt
import React from 'react'; import 'materialize-css/dist/js/materialize'; import { Sidebar } from '../../src/components/Dashboard/Sidebar.jsx'; jest.mock('react-dom'); const setup = () => { const props = { currentUser: { id: 1 }, groups: { Groups: [{ id: 1, name: 'general' }], activeGroup: { id: 1, name: 'general' } }, createGroup: jest.fn(), retrieveGroups: jest.fn(), activeGroup: jest.fn(), signoutUser: jest.fn(), getMessages: jest.fn() }; const wrapper = mount(<Sidebar {...props} />); return { props, wrapper }; }; describe('Side bar Container', () => { const { props, wrapper } = setup(); const event = { preventDefault: jest.fn(), target: { value: 'general', name: 'name' } }; it('should setState on input change', () => { wrapper.instance().handleOnChange(event); expect(wrapper.state().name).toEqual('general'); }); it('should dispatch createGroup action when group is created', () => { wrapper.setState({ name: 'random', description: 'for random conversations' }); wrapper.instance().onSubmit(event); expect(props.createGroup.mock.calls.length).toEqual(1); }); it('should dispatch signoutUser action when user signs out', () => { wrapper.instance().handleOnClick(event); expect(props.signoutUser.mock.calls.length).toEqual(1); }); it('should dispatch activeGroup action when user clicks on a group', () => { wrapper.instance().handleActiveGroup(event); expect(props.activeGroup.mock.calls.length).toEqual(1); }); });
example/redux-todomvc/test/components/Footer.spec.js
viclm/jquery-widget
import expect from 'expect' import React from 'react' import TestUtils from 'react-addons-test-utils' import Footer from '../../components/Footer' import { SHOW_ALL, SHOW_ACTIVE } from '../../constants/TodoFilters' function setup(propOverrides) { const props = Object.assign({ completedCount: 0, activeCount: 0, filter: SHOW_ALL, onClearCompleted: expect.createSpy(), onShow: expect.createSpy() }, propOverrides) const renderer = TestUtils.createRenderer() renderer.render(<Footer {...props} />) const output = renderer.getRenderOutput() return { props: props, output: output } } function getTextContent(elem) { const children = Array.isArray(elem.props.children) ? elem.props.children : [ elem.props.children ] return children.reduce(function concatText(out, child) { // Children are either elements or text strings return out + (child.props ? getTextContent(child) : child) }, '') } describe('components', () => { describe('Footer', () => { it('should render container', () => { const { output } = setup() expect(output.type).toBe('footer') expect(output.props.className).toBe('footer') }) it('should display active count when 0', () => { const { output } = setup({ activeCount: 0 }) const [ count ] = output.props.children expect(getTextContent(count)).toBe('No items left') }) it('should display active count when above 0', () => { const { output } = setup({ activeCount: 1 }) const [ count ] = output.props.children expect(getTextContent(count)).toBe('1 item left') }) it('should render filters', () => { const { output } = setup() const [ , filters ] = output.props.children expect(filters.type).toBe('ul') expect(filters.props.className).toBe('filters') expect(filters.props.children.length).toBe(3) filters.props.children.forEach(function checkFilter(filter, i) { expect(filter.type).toBe('li') const a = filter.props.children expect(a.props.className).toBe(i === 0 ? 'selected' : '') expect(a.props.children).toBe({ 0: 'All', 1: 'Active', 2: 'Completed' }[i]) }) }) it('should call onShow when a filter is clicked', () => { const { output, props } = setup() const [ , filters ] = output.props.children const filterLink = filters.props.children[1].props.children filterLink.props.onClick({}) expect(props.onShow).toHaveBeenCalledWith(SHOW_ACTIVE) }) it('shouldnt show clear button when no completed todos', () => { const { output } = setup({ completedCount: 0 }) const [ , , clear ] = output.props.children expect(clear).toBe(undefined) }) it('should render clear button when completed todos', () => { const { output } = setup({ completedCount: 1 }) const [ , , clear ] = output.props.children expect(clear.type).toBe('button') expect(clear.props.children).toBe('Clear completed') }) it('should call onClearCompleted on clear button click', () => { const { output, props } = setup({ completedCount: 1 }) const [ , , clear ] = output.props.children clear.props.onClick({}) expect(props.onClearCompleted).toHaveBeenCalled() }) }) })
source/components/HomeButton.react.js
BeethovensWerkstatt/VideApp
import React from 'react'; import PropTypes from 'prop-types'; const HomeButton = ({ onClick }) => { return ( <img src='./resources/pix/videAppLogo.png' className='videAppLogo' alt='Home' onClick={e => { e.preventDefault(); onClick(); }} /> ); }; HomeButton.propTypes = { onClick: PropTypes.func.isRequired }; export default HomeButton;
pnpm-cached/.pnpm-store/1/registry.npmjs.org/react-bootstrap/0.31.0/es/Tooltip.js
Akkuma/npm-cache-benchmark
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 PropTypes from 'prop-types'; import isRequiredForA11y from 'react-prop-types/lib/isRequiredForA11y'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string|number} * @required */ id: isRequiredForA11y(PropTypes.oneOfType([PropTypes.string, PropTypes.number])), /** * Sets the direction the Tooltip is positioned towards. */ placement: PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Tooltip. */ positionTop: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * The "left" position value for the Tooltip. */ positionLeft: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * The "top" position value for the Tooltip arrow. */ arrowOffsetTop: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * The "left" position value for the Tooltip arrow. */ arrowOffsetLeft: PropTypes.oneOfType([PropTypes.number, PropTypes.string]) }; var defaultProps = { placement: 'right' }; var Tooltip = function (_React$Component) { _inherits(Tooltip, _React$Component); function Tooltip() { _classCallCheck(this, Tooltip); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Tooltip.prototype.render = function render() { var _extends2; var _props = this.props, placement = _props.placement, positionTop = _props.positionTop, positionLeft = _props.positionLeft, arrowOffsetTop = _props.arrowOffsetTop, arrowOffsetLeft = _props.arrowOffsetLeft, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = _extends({ top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return React.createElement( 'div', _extends({}, elementProps, { role: 'tooltip', className: classNames(className, classes), style: outerStyle }), React.createElement('div', { className: prefix(bsProps, 'arrow'), style: arrowStyle }), React.createElement( 'div', { className: prefix(bsProps, 'inner') }, children ) ); }; return Tooltip; }(React.Component); Tooltip.propTypes = propTypes; Tooltip.defaultProps = defaultProps; export default bsClass('tooltip', Tooltip);
docs/src/examples/elements/Step/Groups/StepExampleVertical.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Icon, Step } from 'semantic-ui-react' const StepExampleVertical = () => ( <Step.Group vertical> <Step completed> <Icon name='truck' /> <Step.Content> <Step.Title>Shipping</Step.Title> <Step.Description>Choose your shipping options</Step.Description> </Step.Content> </Step> <Step completed> <Icon name='payment' /> <Step.Content> <Step.Title>Billing</Step.Title> <Step.Description>Enter billing information</Step.Description> </Step.Content> </Step> <Step active> <Icon name='info' /> <Step.Content> <Step.Title>Confirm Order</Step.Title> </Step.Content> </Step> </Step.Group> ) export default StepExampleVertical
components/ParallaxContainer/ParallaxContainer.js
rdjpalmer/bloom
/* global window: true, */ import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { subscribe } from 'subscribe-ui-event'; import cx from 'classnames'; import css from './ParallaxContainer.css'; export default class ParallaxContainer extends Component { static propTypes= { children: PropTypes.node.isRequired, speed: PropTypes.number, topOffset: PropTypes.number, className: PropTypes.string, }; static defaultProps = { speed: 1, topOffset: 0, }; state = { top: 0, }; componentDidMount() { this.updatePosition(); this.scrollEventSubscription = subscribe('scroll', this.updatePosition, { useRAF: true, }); } componentWillUnmount() { this.scrollEventSubscription.unsubscribe(); } updatePosition = () => { const { speed } = this.props; const scrollPosition = (window.pageYOffset || document.scrollTop) - (document.clientTop || 0) || 0; this.setState({ top: scrollPosition * speed, }); } render() { const { children, topOffset, className } = this.props; const { top } = this.state; return ( <div className={ cx(css.root, className) } style={ { top: (0 - top) + topOffset, } } > { children } </div> ); } }
web/src/js/components/Settings/Widgets/WidgetConfigComponent.js
gladly-team/tab
import React from 'react' import PropTypes from 'prop-types' import Toggle from 'material-ui/Toggle' import { RadioButton, RadioButtonGroup } from 'material-ui/RadioButton' class WidgetConfig extends React.Component { render() { const { setting } = this.props switch (setting.type) { case 'boolean': return ( <BooleanWidgetConfig setting={setting} onConfigUpdated={this.props.onConfigUpdated} /> ) case 'choices': return ( <ChoicesWidgetConfig setting={setting} onConfigUpdated={this.props.onConfigUpdated} /> ) default: return null } } } WidgetConfig.propTypes = { setting: PropTypes.object.isRequired, onConfigUpdated: PropTypes.func.isRequired, } export default WidgetConfig class BooleanWidgetConfig extends React.Component { onToggle(event, checked) { const { setting } = this.props this.props.onConfigUpdated(setting.field, checked) } render() { const { setting } = this.props const toggleContainerStyle = { width: '80%', marginLeft: '5%', marginRight: '5%', marginBottom: 16, } return ( <div style={toggleContainerStyle}> <Toggle label={setting.display} defaultToggled={setting.value} onToggle={this.onToggle.bind(this)} /> </div> ) } } class ChoicesWidgetConfig extends React.Component { onChange(event, value) { const { setting } = this.props this.props.onConfigUpdated(setting.field, value) } render() { const { setting } = this.props const choicesContainerStyle = { width: '90%', margin: 'auto', display: 'flex', } const settingDisplayStyle = { flex: 5, } const btnGroupStyle = { display: 'flex', width: 'auto', flex: 1, flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'flex-start', } const radioBtnStyle = { width: 'auto', marginBottom: 6, fontSize: 14, } return ( <div style={choicesContainerStyle}> <span style={settingDisplayStyle}>{setting.display}</span> <RadioButtonGroup onChange={this.onChange.bind(this)} style={btnGroupStyle} name={setting.field + '-choices'} defaultSelected={setting.value} > {setting.choices.map((choice, index) => { return ( <RadioButton key={index} style={radioBtnStyle} value={choice} label={choice} /> ) })} </RadioButtonGroup> </div> ) } }
example/todoReact/views/todoapp.js
coderwin/Fluder
import React from 'react'; import todoStore from '../stores/todoStore'; import todoAction from '../actions/todoAction'; import Lines from './lines'; export default class TodoApp extends React.Component{ constructor(props){ super(props); this.state = { items: todoStore.getAll()||[] }; } componentDidMount(){ todoStore.addChangeListener(this.onChange.bind(this)); } onChange(){ let items = todoStore.getAll(); this.setState({ items: items }); } handleKeyup(e){ if(e.keyCode == "13"){ this.addTodo() } } delAll(){ todoAction.delAll(); } addTodo(){ let addTodoV = this.refs['app-val'].value; todoAction.addTodo(addTodoV); this.refs['app-val'].value = ''; } linesUpdateTodo(i,updateTodoV){ todoAction.updateTodo(updateTodoV,i) } render(){ let items = this.state.items; return ( <div className='app-main'> <div className='app-input'> <input ref='app-val' placeholder='What needs to be done?' autoFocus onKeyUp={this.handleKeyup.bind(this)} /> <button onClick={this.addTodo.bind(this)}>增加</button> </div> <div className='app-items'> <Lines linesUpdateTodo={this.linesUpdateTodo.bind(this)} items={items} /> </div> { items.length>0&& <div className='app-counter'> <span className='counter'>{items.length+' items added'}</span> <span className='clear' onClick={this.delAll.bind(this)}>Clear All</span> </div> } </div> ) } }
react/react-fundamentals/PropsChildrenApp.js
claycarpenter/node-sandbox
import React from 'react'; class PropsChildrenApp extends React.Component { render() { return ( <Button>I Tolerate React</Button> ); } } class Button extends React.Component { render() { return ( <button>{this.props.children}</button> ); } } export default PropsChildrenApp
react/exercises/part_03/src/index.js
jsperts/workshop_unterlagen
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; import './index.css'; import AppContainer from './containers/App'; import store from './store'; const root = ( <Provider store={store}> <AppContainer /> </Provider> ); ReactDOM.render(root, document.getElementById('root'));
src/components/tracks/individual/_blind/index.js
cannoneyed/tmm-glare
import React from 'react' // const timeline = [{ // time: 0, // fact: '' // }] // export default function Blind() { return ( <div className="track-info-page"> <div className="track-text blind" /> </div> ) }
website/core/SnackPlayer.js
Livyli/react-native
/** * 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 SnackPlayer */ 'use strict'; var Prism = require('Prism'); var React = require('React'); const PropTypes = require('prop-types'); const LatestSDKVersion = '16.0.0'; var ReactNativeToExpoSDKVersionMap = { '0.44': '17.0.0', '0.43': '16.0.0', '0.42': '15.0.0', '0.41': '14.0.0', }; /** * Use the SnackPlayer by including a ```SnackPlayer``` block in markdown. * * Optionally, include url parameters directly after the block's language. * Valid options are name, description, and platform. * * E.g. * ```SnackPlayer?platform=android&name=Hello%20world! * import React from 'react'; * import { Text } from 'react-native'; * * export default class App extends React.Component { * render() { * return <Text>Hello World!</Text>; * } * } * ``` */ var SnackPlayer = React.createClass({ contextTypes: { version: PropTypes.number.isRequired, }, componentDidMount() { window.ExpoSnack && window.ExpoSnack.initialize(); }, render() { var code = encodeURIComponent(this.props.children); var params = this.parseParams(this.props.params); var platform = params.platform ? params.platform : 'ios'; var name = params.name ? decodeURIComponent(params.name) : 'Example'; var description = params.description ? decodeURIComponent(params.description) : 'Example usage'; var optionalProps = {}; var { version } = this.context; if (version === 'next') { optionalProps[ 'data-snack-sdk-version' ] = LatestSDKVersion; } else { optionalProps[ 'data-snack-sdk-version' ] = ReactNativeToExpoSDKVersionMap[version] || LatestSDKVersion; } return ( <div className="snack-player"> <div className="mobile-friendly-snack" style={{ display: 'none' }} > <Prism> {this.props.children} </Prism> </div> <div className="desktop-friendly-snack" style={{ marginTop: 15, marginBottom: 15 }} > <div data-snack-name={name} data-snack-description={description} data-snack-code={code} data-snack-platform={platform} data-snack-preview="true" {...optionalProps} style={{ overflow: 'hidden', background: '#fafafa', border: '1px solid rgba(0,0,0,.16)', borderRadius: '4px', height: '514px', width: '880px', }} /> </div> </div> ); }, parseParams: function(paramString) { var params = {}; if (paramString) { var pairs = paramString.split('&'); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split('='); params[pair[0]] = pair[1]; } } return params; }, }); module.exports = SnackPlayer;
src/components/MenuHandle.js
vigetlabs/colonel-kurtz
import React from 'react' import Btn from './Button' const defaultProps = { className: 'col-menu-handle', label: 'Open the menu for this block', type: 'button' } export default class MenuHandle extends React.Component { render() { const { label, ...safe } = this.props return ( <Btn {...safe}> <span className="col-hidden">{label}</span> <svg width="24" height="24" viewBox="0 0 24 24" aria-hidden="true"> <path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z" /> </svg> </Btn> ) } } MenuHandle.defaultProps = defaultProps
docs/app/Examples/collections/Message/Types/MessageExampleMessage.js
aabustamante/Semantic-UI-React
import React from 'react' import { Message } from 'semantic-ui-react' const MessageExampleMessage = () => ( <Message> <Message.Header> Changes in Service </Message.Header> <p> We updated our privacy policy here to better service our customers. We recommend reviewing the changes. </p> </Message> ) export default MessageExampleMessage
app/packs/src/components/report/Setting.js
ComPlat/chemotion_ELN
import React from 'react'; import { Panel } from 'react-bootstrap'; import ReportActions from '../actions/ReportActions'; import CheckBoxs from '../common/CheckBoxs'; const toggleSplSettings = (text, checked) => { ReportActions.updateSplSettings({ text, checked }); }; const toggleSplSettingsAll = () => { ReportActions.toggleSplSettingsCheckAll(); }; const toggleRxnSettings = (text, checked) => { ReportActions.updateRxnSettings({ text, checked }); }; const toggleRxnSettingsAll = () => { ReportActions.toggleRxnSettingsCheckAll(); }; const stdSetting = ({ splSettings, checkedAllSplSettings, rxnSettings, checkedAllRxnSettings }) => ( <div> <Panel bsStyle="default"> <Panel.Heading> <Panel.Title> Sample </Panel.Title> </Panel.Heading> <Panel.Body> <CheckBoxs items={splSettings} toggleCheckbox={toggleSplSettings} toggleCheckAll={toggleSplSettingsAll} checkedAll={checkedAllSplSettings} /> </Panel.Body> </Panel> <Panel bsStyle="default"> <Panel.Heading> <Panel.Title> Reaction </Panel.Title> </Panel.Heading> <Panel.Body> <CheckBoxs items={rxnSettings} checkedAll={checkedAllRxnSettings} toggleCheckbox={toggleRxnSettings} toggleCheckAll={toggleRxnSettingsAll} /> </Panel.Body> </Panel> </div> ); const toggleSiRxnSettings = (text, checked) => { ReportActions.updateSiRxnSettings({ text, checked }); }; const toggleSiRxnSettingsAll = () => { ReportActions.toggleSiRxnSettingsCheckAll(); }; const suiSetting = ({ siRxnSettings, checkedAllSiRxnSettings }) => ( <div> <Panel bsStyle="default"> <Panel.Heading> <Panel.Title> Synthesis Products Information </Panel.Title> </Panel.Heading> <Panel.Body> <CheckBoxs items={siRxnSettings} checkedAll={checkedAllSiRxnSettings} toggleCheckbox={toggleSiRxnSettings} toggleCheckAll={toggleSiRxnSettingsAll} /> </Panel.Body> </Panel> </div> ); const spcSetting = () => ( <div> <h5>Not applicable.</h5> </div> ); const rxlSetting = () => ( <div> <h5>Not applicable.</h5> </div> ); const Setting = (props) => { switch (props.template.value) { case 'standard': return stdSetting(props); case 'spectrum': return spcSetting(); case 'supporting_information': case 'supporting_information_std_rxn': return suiSetting(props); case 'rxn_list_xlsx': case 'rxn_list_csv': case 'rxn_list_html': return rxlSetting(props); default: return stdSetting(props); } }; export default Setting;
core/router.js
CharlesSanford/personal-site
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; function decodeParam(val) { if (!(typeof val === 'string' || val.length === 0)) { return val; } try { return decodeURIComponent(val); } catch (err) { if (err instanceof URIError) { err.message = `Failed to decode param '${val}'`; err.status = 400; } throw err; } } // Match the provided URL path pattern to an actual URI string. For example: // matchURI({ path: '/posts/:id' }, '/dummy') => null // matchURI({ path: '/posts/:id' }, '/posts/123') => { id: 123 } function matchURI(route, path) { const match = route.pattern.exec(path); if (!match) { return null; } const params = Object.create(null); for (let i = 1; i < match.length; i++) { params[route.keys[i - 1].name] = match[i] !== undefined ? decodeParam(match[i]) : undefined; } return params; } // Find the route matching the specified location (context), fetch the required data, // instantiate and return a React component function resolve(routes, context) { for (const route of routes) { const params = matchURI(route, context.error ? '/error' : context.pathname); if (!params) { continue; } // Check if the route has any data requirements, for example: // { path: '/tasks/:id', data: { task: 'GET /api/tasks/$id' }, page: './pages/task' } if (route.data) { // Load page component and all required data in parallel const keys = Object.keys(route.data); return Promise.all([ route.load(), ...keys.map(key => { const query = route.data[key]; const method = query.substring(0, query.indexOf(' ')); // GET const url = query.substr(query.indexOf(' ') + 1); // /api/tasks/$id // TODO: Replace query parameters with actual values coming from `params` return fetch(url, { method }).then(resp => resp.json()); }), ]).then(([Page, ...data]) => { const props = keys.reduce((result, key, i) => ({ ...result, [key]: data[i] }), {}); return <Page route={route} error={context.error} {...props} />; }); } return route.load().then(Page => <Page route={route} error={context.error} />); } const error = new Error('Page not found'); error.status = 404; return Promise.reject(error); } export default { resolve };
example/src/test_checkbox.js
flywingdevelopers/rn-naive
/** * <CheckBox> Control Test * Kevin Lee 19 Sept 2017 **/ import React from 'react' import { Screen, Bar, Roll, Text, CheckBox } from 'rn-naive' export default class App extends React.Component { constructor(props) { super(props) this.state = { DisableAll: false, } } render() { return ( <Screen lines={18} style={{margin:2, padding:4, borderWidth:2, borderRadius:4}}> <Bar title={<Text H3 color='#ddd'>{'<'}CheckBox{'>'} Control Test</Text>} left={<CheckBox iconOnly iconSize={16} iconColor='#ddd' icons={['md-eye-off', 'md-eye']} value={this.state.DisableAll} onValueChange={(DisableAll)=>this.setState({DisableAll})} />} /> <Bar text={<Text H5>CheckBox Element has either TRUE or FALSE value</Text>} /> <Bar text={<Text D4>It has three layouts</Text>} /> <Bar> <CheckBox iconLeft text='checkbox 1' disabled={this.state.DisableAll != 0} /> <CheckBox iconRight text='checkbox 2' disabled={this.state.DisableAll != 0} /> <CheckBox iconOnly text='checkbox 3' disabled={this.state.DisableAll != 0} /> </Bar> <Bar text={<Text D4>Icon can be radio glyph</Text>} /> <Bar> <CheckBox iconLeft boxType='radio' text='checkbox 1' disabled={this.state.DisableAll != 0} /> <CheckBox iconRight boxType='radio' text='checkbox 2' disabled={this.state.DisableAll != 0} /> <CheckBox iconOnly boxType='radio' text='checkbox 3' disabled={this.state.DisableAll != 0} /> </Bar> <Bar text={<Text D4>Icon can be customized</Text>} /> <Bar> <CheckBox iconLeft icons={['md-eye', 'md-eye-off']} text='checkbox 1' disabled={this.state.DisableAll != 0} /> <CheckBox iconRight icons={['md-man', 'md-woman']} text='checkbox 2' disabled={this.state.DisableAll != 0} /> <CheckBox iconOnly icons={['logo-android', 'logo-apple']} text='checkbox 3' disabled={this.state.DisableAll != 0} /> </Bar> </Screen> ) } }
src/components/Feedback/Feedback.js
chaudhryjunaid/chaudhryjunaid.com
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Feedback.css'; class Feedback extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <a className={s.link} href="https://gitter.im/kriasoft/react-starter-kit" > Ask a question </a> <span className={s.spacer}>|</span> <a className={s.link} href="https://github.com/kriasoft/react-starter-kit/issues/new" > Report an issue </a> </div> </div> ); } } export default withStyles(s)(Feedback);
xcessiv/ui/src/DatasetExtraction/DataExtractionTabs.js
reiinakano/xcessiv
import React, { Component } from 'react'; import './MainDataExtraction.css'; import { Tab, Tabs, TabList, TabPanel } from 'react-tabs'; import MainDataExtraction from './MainDataExtraction'; //import TestDataExtraction from './TestDataExtraction'; import MetaFeatureExtraction from './MetaFeatureExtraction'; import StackedEnsembleCV from './StackedEnsembleCV' import DataVerificationResult from './DataVerificationResult'; class DataExtractionTabs extends Component { constructor(props) { super(props); this.state = { "selectedIndex": 0, "sameMde": true, "sameTde": true, "sameMfe": true, "sameSecv": true, "mfeConfig": "", "mdeConfig": "", "secvConfig": "" }; } componentDidMount() { this.fetchMfe(this.props.path); this.fetchMde(this.props.path); this.fetchSecv(this.props.path); } fetchMfe(path) { fetch('/ensemble/extraction/meta-feature-generation/?path=' + path) .then(response => response.json()) .then(json => { console.log(json); this.setState({ mfeConfig: json, sameMfe: true }) }); } // Save all changes to server saveMfe(config) { var payload = config; fetch( '/ensemble/extraction/meta-feature-generation/?path=' + this.props.path, { method: "PATCH", body: JSON.stringify( payload ), headers: new Headers({ 'Content-Type': 'application/json' }) } ) .then(response => response.json()) .then(json => { console.log(json); this.setState({ mfeConfig: json, sameMfe: true }); this.props.addNotification({ title: 'Success', message: 'Saved base learner cross-validation method', level: 'success' }); }); } fetchMde(path) { fetch('/ensemble/extraction/main-dataset/?path=' + path) .then(response => response.json()) .then(json => { console.log(json); this.setState({ mdeConfig: json, sameMde: true }) }); } // Save all changes to server saveMde(config) { var payload = config; fetch( '/ensemble/extraction/main-dataset/?path=' + this.props.path, { method: "PATCH", body: JSON.stringify( payload ), headers: new Headers({ 'Content-Type': 'application/json' }) } ) .then(response => response.json()) .then(json => { console.log(json); this.setState({ mdeConfig: json, sameMde: true }); this.props.addNotification({ title: 'Success', message: 'Saved main dataset extraction method', level: 'success' }); }); } fetchSecv(path) { fetch('/ensemble/extraction/stacked-ensemble-cv/?path=' + path) .then(response => response.json()) .then(json => { console.log(json); this.setState({ secvConfig: json, sameSecv: true }) }); } // Save all changes to server saveSecv(config) { var payload = config; fetch( '/ensemble/extraction/stacked-ensemble-cv/?path=' + this.props.path, { method: "PATCH", body: JSON.stringify( payload ), headers: new Headers({ 'Content-Type': 'application/json' }) } ) .then(response => response.json()) .then(json => { console.log(json); this.setState({ secvConfig: json, sameSecv: true }); this.props.addNotification({ title: 'Success', message: 'Saved stacked ensemble cross-validation method', level: 'success' }); }); } componentWillReceiveProps(nextProps) { if (this.props.path !== nextProps.path) { this.setState({ 'sameTde': true }); this.fetchMfe(nextProps.path); this.fetchMde(nextProps.path); } } render() { return( <div className='MainDataExtraction'> <h2>Extract your dataset into Xcessiv</h2> <Tabs forceRenderTabPanel={false} selectedIndex={this.state.selectedIndex} onSelect={(idx) => this.setState({selectedIndex: idx})} > <TabList> <Tab>Main Dataset Extraction{!this.state.sameMde && '*'}</Tab> {/*<Tab>Test Dataset Extraction{!this.state.sameTde && '*'}</Tab>*/} <Tab>Base learner Cross-validation{!this.state.sameMfe && '*'}</Tab> <Tab>Stacked Ensemble Cross-validation{!this.state.sameSecv && '*'}</Tab> </TabList> <TabPanel className='TabPanel'> <MainDataExtraction addNotification={(notif) => this.props.addNotification(notif)} same={this.state.sameMde} setSame={(x) => this.setState({sameMde: x})} config={this.state.mdeConfig} saveConfig={(x) => this.saveMde(x)} /> </TabPanel> {/* <TabPanel className='TabPanel'> <TestDataExtraction path={this.props.path} addNotification={(notif) => this.props.addNotification(notif)} same={this.state.sameTde} setSame={(x) => this.setState({sameTde: x})} /> </TabPanel> */} <TabPanel className='TabPanel'> <MetaFeatureExtraction addNotification={(notif) => this.props.addNotification(notif)} same={this.state.sameMfe} setSame={(x) => this.setState({sameMfe: x})} config={this.state.mfeConfig} saveConfig={(x) => this.saveMfe(x)} presetCVs={this.props.presetCVs} /> </TabPanel> <TabPanel className='TabPanel'> <StackedEnsembleCV addNotification={(notif) => this.props.addNotification(notif)} same={this.state.sameSecv} setSame={(x) => this.setState({sameSecv: x})} config={this.state.secvConfig} saveConfig={(x) => this.saveSecv(x)} presetCVs={this.props.presetCVs} /> </TabPanel> </Tabs> <DataVerificationResult path={this.props.path} same={this.state.sameMde && this.state.sameTde && this.state.sameMfe} addNotification={(notif) => this.props.addNotification(notif)} /> </div> ) } } export default DataExtractionTabs;
src/svg-icons/av/remove-from-queue.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvRemoveFromQueue = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-7v2H8v-2h8z"/> </SvgIcon> ); AvRemoveFromQueue = pure(AvRemoveFromQueue); AvRemoveFromQueue.displayName = 'AvRemoveFromQueue'; AvRemoveFromQueue.muiName = 'SvgIcon'; export default AvRemoveFromQueue;
node_modules/react-router/es/Route.js
furgat/sabertoot
import React from 'react'; import invariant from 'invariant'; import { createRouteFromReactElement } from './RouteUtils'; import { component, components } from './InternalPropTypes'; var _React$PropTypes = React.PropTypes, string = _React$PropTypes.string, func = _React$PropTypes.func; /** * A <Route> is used to declare which components are rendered to the * page when the URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is * requested, the tree is searched depth-first to find a route whose * path matches the URL. When one is found, all routes in the tree * that lead to it are considered "active" and their components are * rendered into the DOM, nested in the same order as in the tree. */ /* eslint-disable react/require-render-return */ var Route = React.createClass({ displayName: 'Route', statics: { createRouteFromReactElement: createRouteFromReactElement }, propTypes: { path: string, component: component, components: components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Route> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default Route;
components/Roster.js
alexxpan/calwtcrew
import React from 'react'; import '../css/roster.scss'; const Roster = ({ rosterName, names, sides, years, hometowns, majors }) => ( <div className="roster-container"> <header> <h1>{rosterName}</h1> </header> <div className="column-container"> <div className="roster__column"> <h3>Name</h3> {names.map((name) => ( <div className="roster__item"> {name} </div> ))} </div> <div className="roster__column"> <h3>Side</h3> {sides.map((side) => ( <div className="roster__item"> {side} </div> ))} </div> <div className="roster__column"> <h3>Year</h3> {years.map((year) => ( <div className="roster__item"> {year} </div> ))} </div> <div className="roster__column"> <h3>Hometown</h3> {hometowns.map((hometown) => ( <div className="roster__item"> {hometown} </div> ))} </div> <div className="roster__column"> <h3>Major</h3> {majors.map((major) => ( <div className="roster__item"> {major} </div> ))} </div> </div> </div> ); Roster.propTypes = { rosterName: React.PropTypes.string.isRequired, names: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, sides: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, years: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, hometowns: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, majors: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, }; export default Roster;
web/src/client/main.js
zanj2006/este
import React from 'react'; import ReactDOM from 'react-dom'; import Router from 'react-router'; import {configureStore} from '@este/common'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import createRoutes from './createRoutes'; import {IntlProvider} from 'react-intl'; import {Provider} from 'react-redux'; const app = document.getElementById('app'); const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const routes = createRoutes(() => store.getState()); ReactDOM.render( <Provider store={store}> <IntlProvider> <Router history={createBrowserHistory()}> {routes} </Router> </IntlProvider> </Provider>, app );
packages/material-ui-icons/src/Snooze.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Snooze = props => <SvgIcon {...props}> <path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm-3-9h3.63L9 15.2V17h6v-2h-3.63L15 10.8V9H9v2z" /> </SvgIcon>; Snooze = pure(Snooze); Snooze.muiName = 'SvgIcon'; export default Snooze;
src/js/components/Overview.js
bryanjacquot/theme-designer-capstone
import React, { Component } from 'react'; import Section from 'grommet/components/Section'; import Anchor from 'grommet/components/Anchor'; import Pdf from 'grommet/components/icons/base/DocumentPdf'; export default class Overview extends Component { constructor() { super(); } render () { return ( <Section> <h2>Overview</h2> <p> The Grommet Theme Designer is a web-based application which enables designers, the primary stakeholders, to create themes for websites and web-based applications. Themes created with the Grommet Theme Designer will cover the spectrum of web design needs, including colors, fonts, element style (button, checkbox, etc.), and icon style (line width and end caps). </p> <p> The theme designer will ensure the theme meets certain accessibility standards with notifications of inadequate contrast between colors for users with color deficiency (WCAG 2008). This is a significant capability because according to Dix (2004), approximately 8% of males and 1% of females suffer from colorblindness. These figures do not include users who rely on assistive technologies such as screen readers. The importance of this capability cannot be understated as none of the designers initially interviewed for this project had taken accessibility into account when designing themes. </p> <p> When the designer is satisfied with the theme, it can be imported into Sketch. A new Sketch plugin will customize the&nbsp; <a href="https://github.com/grommet/grommet-design/raw/master/grommet/grommet-sticker-sheet-apps-general-0-3.sketch"> Grommet Sticker Sheet</a> with the theme’s settings, which makes it easy for designers to begin designing their website or application. </p> <p> Finally, the theme designer streamlines the handoff to developers by providing developers with the customized theme for the&nbsp; <a href="http://grommet.io">Grommet</a> web development library. This enables developers to efficiently implement the application as designed. </p> <p> This project was authored by Bryan Jacquot as part of a Master of Science degree in <a href="http://www.vrac.iastate.edu/hci/">Human-Computer Interaction</a> from&nbsp; <a href="http://iastate.edu">Iowa State University</a>.&nbsp; <a href="https://courses.elo.iastate.edu/HCI/598/XE/2016/spring/overview">HCI 598 XE</a>&nbsp; <i>HCI Design, Implementation and Implications</i> is the capstone course for the online degree program. </p> <p> <Anchor icon={<Pdf/>} href="https://github.com/bryanjacquot/theme-designer-capstone/raw/master/docs/M1-JacquotBryan.pdf" label="Proposal Document" primary={true} /> </p> </Section> ); } };
step6-serviceapi/node_modules/react-router/es6/Route.js
jintoppy/react-training
'use strict'; import React from 'react'; import invariant from 'invariant'; import { createRouteFromReactElement } from './RouteUtils'; import { component, components } from './PropTypes'; var _React$PropTypes = React.PropTypes; var string = _React$PropTypes.string; var func = _React$PropTypes.func; /** * A <Route> is used to declare which components are rendered to the * page when the URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is * requested, the tree is searched depth-first to find a route whose * path matches the URL. When one is found, all routes in the tree * that lead to it are considered "active" and their components are * rendered into the DOM, nested in the same order as in the tree. */ var Route = React.createClass({ displayName: 'Route', statics: { createRouteFromReactElement: createRouteFromReactElement }, propTypes: { path: string, component: component, components: components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Route> elements are for router configuration only and should not be rendered') : invariant(false) : undefined; } }); export default Route;
packages/reactor-kitchensink/src/examples/DragAndDrop/Files/Files.js
dbuhrman/extjs-reactor
import React, { Component } from 'react'; import { Panel } from '@extjs/ext-react'; import './styles.css'; Ext.require(['Ext.drag.*']); const DEFAULT_TEXT = 'Drag a file from your computer here'; export default class Files extends Component { state = { iconCls: 'drag-file-icon', labelText: DEFAULT_TEXT } render() { const {iconCls, labelText} = this.state; return ( <Panel ref="mainPanel" padding={5} shadow > <div ref="label" className="drag-file-label">{labelText}</div> <div ref="icon" className={iconCls}></div> </Panel> ) } onDragEnter() { this.setState({ iconCls: 'drag-file-icon active' }); } onDragLeave() { this.setState({ iconCls: 'drag-file-icon' }); } onDrop(target, info) { const files = info.files; this.setState({ iconCls: 'drag-file-icon dropped fa-spin', labelText: files.length > 1 ? `Dropped ${files.length} files.` : `Dropped ${files[0].name}` }); this.timer = setTimeout(() => { if(!this.refs.mainPanel.destroyed) { this.setState({ iconCls: 'drag-file-icon drag-file-fadeout', labelText: DEFAULT_TEXT }); } this.timer = null; }, 2000); } componentDidMount() { this.target = new Ext.drag.Target({ element: this.refs.mainPanel.element, listeners: { dragenter: this.onDragEnter.bind(this), dragleave: this.onDragLeave.bind(this), drop: this.onDrop.bind(this) } }); } componentWillUnmount() { clearInterval(this.timer); Ext.destroy(this.target); } }
step02/App/src/components/Loader/index.android.js
grokbot/intro-to-react-native
import React, { Component } from 'react'; import { ActivityIndicator } from 'react-native'; import { Theme, Color } from "../../theme"; export class Loader extends Component { render() { return ( <ActivityIndicator size={45} style={[Theme.loader, Theme.centered]} color={Color.yellow} /> ) } }
Realization/frontend/czechidm-core/src/components/advanced/ModalProgressBar/ModalProgressBar.js
bcvsolutions/CzechIdMng
import React from 'react'; import PropTypes from 'prop-types'; // import * as Basic from '../../basic'; import ProgressBar from '../ProgressBar/ProgressBar'; /** * Progressbar in modal window. * * @author Radek Tomiška */ export default function ModalProgressBar(props) { const { rendered, showLoading, show, counter, count, text } = props; // if (!rendered) { return null; } // return ( <Basic.Modal show={ show } showLoading={ showLoading } bsSize="large" backdrop="static"> <Basic.Modal.Header text={ text }/> <Basic.Modal.Body> <ProgressBar max={ count } now={ counter } rendered={ !showLoading }/> </Basic.Modal.Body> </Basic.Modal> ); } ModalProgressBar.propTypes = { ...Basic.AbstractContextComponent.propTypes, /** * ProgressBar is shown */ show: PropTypes.bool, /** * Main title - modal header text */ text: PropTypes.string, /** * Current processed counter */ counter: PropTypes.number, /** * Size / maximum */ count: PropTypes.number }; ModalProgressBar.defaultProps = { ...Basic.AbstractContextComponent.defaultProps, show: false, counter: 0, count: 0, text: 'Probíhá zpracování' // TODO: locale };
packages/reactor-tests/src/tests/SenchaTestHooks.js
markbrocato/extjs-reactor
import React from 'react'; import { Button } from '@extjs/ext-react'; export default function SenchaTestHooks() { return <Button text="Target" itemId="target"/> }
src/index.js
tolylya/octoberry
/* eslint-disable import/default */ import React from 'react'; import { render } from 'react-dom'; import { browserHistory } from 'react-router'; import { AppContainer } from 'react-hot-loader'; import Root from './components/Root'; import configureStore from './store/configureStore'; require('./favicon.ico'); // Tell webpack to load favicon.ico import './styles/styles.scss'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page. import { syncHistoryWithStore } from 'react-router-redux'; const store = configureStore(); // Create an enhanced history that syncs navigation events with the store const history = syncHistoryWithStore(browserHistory, store); render( <AppContainer> <Root store={store} history={history} /> </AppContainer>, document.getElementById('app') ); if (module.hot) { module.hot.accept('./components/Root', () => { const NewRoot = require('./components/Root').default; render( <AppContainer> <NewRoot store={store} history={history} /> </AppContainer>, document.getElementById('app') ); }); }
src/main/js/my-app/src/components/NotFound.js
myapos/ClientManagerSpringBoot
import React from 'react'; const NotFound = () => <div> The page that you requested has not found </div>; NotFound.contextTypes = { router: React.PropTypes.object.isRequired, }; export default NotFound;
src/index.js
Maachi/Admin-FrontEnd
import React from 'react'; import { Router, Route, browserHistory } from 'react-router'; import { render } from 'react-dom'; import Login from './pages/Login'; import Dashboard from './pages/Dashboard'; import CreateProcess from './pages/CreateProcess'; import './static/sass/main.scss'; render(( <Router history={browserHistory}> <Route path="/" component={Login}/> <Route path="/:firm/dashboard" component={Dashboard}/> <Route path="/:firm/create/process" component={CreateProcess}/> </Router> ), document.getElementById('gestion-app'));
imports/ui/components/form/remove-giveaway-dialog.js
irvinlim/free4all
import React from 'react'; import ConfirmDialog from '../../layouts/confirm-dialog'; const RemoveGiveawayDialog = (props) => ( <ConfirmDialog title="Are you sure?" {...props}> Are you sure you would like to remove this giveaway? </ConfirmDialog> ); export default RemoveGiveawayDialog;
AirFront/point/profile.js
sunshinezxf/Airburg
import React from 'react'; import { NavBar, Button, List, WhiteSpace, WingBlank, InputItem, Toast, } from 'antd-mobile'; const Item = List.Item; var profile = {id: '', name: '', phone: '', point: '123'}; export const PointCenter = React.createClass({ getDefaultProps(){ return {profile:profile} }, render(){ const {profile}=this.props; return ( <div> <NavBar iconName="" mode="light">我的积分</NavBar> <WhiteSpace/> <Item> <div className="bigTile" style={{height:'30vh'}}> <p>当前积分</p> {profile.point} </div> </Item> <WhiteSpace size="lg"/> <Item> <div className="bigTile" style={{height:'40vh'}}> 积分商城建设中<br/><br/> 敬请期待 </div> </Item> </div> ); } });
src/containers/NotFound/NotFound.js
martinrp/reduxgitresume
import React from 'react'; export default function NotFound() { return ( <div className="container"> <h1>Doh! 404!</h1> <p>These are <em>not</em> the droids you are looking for!</p> </div> ); }
src/components/Statement.js
lukebelliveau/aclu-matchers
import React from 'react'; import { StyleSheet, css } from 'aphrodite'; const styles = StyleSheet.create({ wrapperStyle: { padding: '50px', paddingTop: 0, '@media (max-width: 740px)': { padding: '0px', } }, body: { borderBottom: '2px solid #eee', borderTop: '2px solid #eee', paddingTop: 25, paddingBottom: 60, margin: '0 auto', marginTop: 40, maxWidth: 1024, '@media (max-width: 740px)': { padding: '15px', width: '90%' } }, h2: { textAlign: 'left', margin: '30px 0' }, p: { textAlign: 'left', marginTop: 30, marginBottom: 0 }, strong: { textAlign: 'left', display: 'block', marginTop: 30, fontSize: 18, '@media (max-width: 740px)': { fontSize: 14, } }, quote: { borderLeft: '5px solid #96989B' } }); export default () => ( <div className={css(styles.wrapperStyle)}> <div className={css(styles.body)}> <h2 className={css(styles.h2)}>Why donate?</h2> <blockquote className={css(styles.quote)}> <p> Extreme vetting is just a euphemism for discrimination against Muslims. Identifying specific countries with Muslim majorities and carving out exceptions for minority religions flies in the face of the constitutional principle that bans the government from either favoring or discriminating against particular religions. Any effort to discriminate against Muslims and favor other religions runs afoul of the First Amendment. </p> <footer> - Anthony D. Romero, Executive Director, American Civil Liberties Union </footer> </blockquote> <strong className={css(styles.strong)}>We wholeheartedly agree with this statement - and we're not alone.</strong> <p className={css(styles.p)}> People around the nation have offered to match our donations to the ACLU; all they need from us is a tweet with the donation receipt. Among others, we have matched donations with Ajay Chopra, Sia, and Jesse Tyler. </p> </div> </div> );
example/superchatExample/App.js
super-chat/react-native-superchat
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { Chat } from 'react-native-superchat'; import messages from './data/messages' import { Platform, StyleSheet, Text, View } from 'react-native'; export default class App extends Component { state = { messages: messages } constructor(props) { super(props); this.handleOnSend = this.handleOnSend.bind(this); } render() { return ( <Chat messages={this.state.messages} user={{id: 1}} onSend={this.handleOnSend} /> ); } handleOnSend(msg) { this.setState({messages: this.state.messages.concat(msg)}, () => { const response = { text: 'OK', messageId: (new Date()).getTime(), user: { ...msg.user, id: 2} }; setTimeout(() => { this.setState({messages: this.state.messages.concat(response)}); }, 1000); }); } } 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, }, });
packages/react-ui-components/src/_lib/injectProps.spec.js
dimaip/neos-ui
import React from 'react'; import {shallow} from 'enzyme'; import injectProps from './injectProps.js'; const WrappedComponent = props => <div {...props}/>; test('should return a curried function.', () => { const fn = injectProps(); expect(typeof fn).toBe('function'); }); test('should return yet another curried function when calling with a React component.', () => { const fn = injectProps({ foo: 'bar' })(WrappedComponent); expect(typeof fn).toBe('function'); }); test('should render the wrapped React component with the initially passed props as well as any props which are specified directly on the render call.', () => { const Component = injectProps({ foo: 'bar' })(WrappedComponent); const node = shallow(<Component baz="qux"/>); expect(node.prop('foo')).toBe('bar'); expect(node.prop('baz')).toBe('qux'); });
pkg/interface/chat/src/js/components/lib/welcome.js
jfranklin9000/urbit
import React, { Component } from 'react'; export class Welcome extends Component { constructor() { super(); this.state = { show: true } this.disableWelcome = this.disableWelcome.bind(this); } disableWelcome() { this.setState({ show: false }); localStorage.setItem("urbit-chat:wasWelcomed", JSON.stringify(true)); } render() { let wasWelcomed = localStorage.getItem("urbit-chat:wasWelcomed"); if (wasWelcomed === null) { localStorage.setItem("urbit-chat:wasWelcomed", JSON.stringify(false)); return wasWelcomed = false; } else { wasWelcomed = JSON.parse(wasWelcomed); } let inbox = !!this.props.inbox ? this.props.inbox : {}; return ((!wasWelcomed && this.state.show) && (inbox.length !== 0)) ? ( <div className="ma4 pa2 bg-welcome-green bg-gray1-d white-d"> <p className="f8 lh-copy">Chats are instant, linear modes of conversation. Many chats can be bundled under one group.</p> <p className="f8 pt2 dib pointer bb" onClick={(() => this.disableWelcome())}> Close this </p> </div> ) : <div/> } } export default Welcome
www/containers/BlogsPage.js
DremyGit/dremy-blog
import React from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; import BlogItem from '../components/BlogPanel/BlogItem'; import BlogListTitle from '../components/BlogPanel/BlogListTitle'; import Pager from '../components/Pager/Pager'; import config from '../config'; import { fetchBlogListIfNeed, } from '../actions/blog'; import { dispatchFetch } from '../helpers/fetchUtils'; import Loading from '../components/Loading/Loading'; @connect(state => ({ blogEntities: state.getIn(['blog', 'entities']), isBlogListFetched: state.getIn(['blog', 'isFetched']), categoryEntities: state.getIn(['category', 'entities']), tagEntities: state.getIn(['tag', 'entities']), })) export default class BlogPage extends React.Component { static fetches = [ fetchBlogListIfNeed, ]; componentDidMount() { dispatchFetch(BlogPage.fetches, this.props); } render() { const { blogEntities, isBlogListFetched, categoryEntities, tagEntities, params, location, } = this.props; if (!isBlogListFetched) { return <Loading />; } const pathArr = location.pathname.split('/'); const pageType = pathArr[1]; let filtedBlogs; let title; let baseUrl = pageType; if (pageType === 'category') { filtedBlogs = blogEntities.filter(blog => blog.get('category') === params.categoryName); title = `分类「${categoryEntities.getIn([params.categoryName, 'name'])}」`; baseUrl += `/${pathArr[2]}`; } else if (pageType === 'tag') { filtedBlogs = blogEntities.filter(blog => blog.get('tags').includes(params.tagName)); title = `标签「${tagEntities.getIn([params.tagName, 'name'])}」`; baseUrl += `/${pathArr[2]}`; } else if (pageType === 'archive') { filtedBlogs = blogEntities.filter(blog => new Date(blog.get('create_at')).getFullYear() === +params.year); title = `${+params.year} 年`; baseUrl += `/${pathArr[2]}`; } else if (pageType === 'search') { const words = new RegExp(params.words, 'i'); filtedBlogs = blogEntities.filter(blog => blog.get('title').search(words) !== -1 || blog.getIn(['html', 'summary']).replace(/<*.?>/g, '').search(words) !== -1); title = `搜索「${params.words}」`; baseUrl += `/${pathArr[2]}`; } else { filtedBlogs = blogEntities; } const page = +params.pageNum || 1; const size = config.blogItemPerPage; const showBlogs = filtedBlogs .sort((a, b) => { if (a.get('create_at') < b.get('create_at')) return 1; if (a.get('create_at') > b.get('create_at')) return -1; return 0; }) .valueSeq() .skip((page - 1) * size) .take(size); return ( <div> <Helmet title={`${title || '首页'} Dremy_博客`} meta={[ { name: 'description', content: 'Dremy_博客 博客列表' }, ]} /> { title && <BlogListTitle title={title} count={filtedBlogs.size} /> } <div> {showBlogs.map(blog => <BlogItem key={blog.get('code')} blog={blog} category={categoryEntities.get(blog.get('category'))} tags={blog.get('tags').map(tag => tagEntities.get(tag))} />, ).toArray()} </div> <Pager totalNum={filtedBlogs.size} currentPage={page} perPage={config.blogItemPerPage} showPage={config.showPageNum} baseUrl={`/${baseUrl || 'blog'}`} /> </div> ); } }
05_ES6/Code/fork-es6/app/components/StorePane.js
joacoleonelli/react-zerotohero
import React from 'react'; import Store from './Store'; import autoBind from 'react-autobind'; class StorePane extends React.Component { constructor(props) { super(props); autoBind(this); } renderStore(store){ return <Store key={store} index={store} details={this.props.stores[store]} />; } render() { return ( <div id="stores-pane" className="column"> <h1>Stores & Ovens</h1> <ul> {Object.keys(this.props.stores).map(this.renderStore)} </ul> </div> ) } }; export default StorePane;
src/GoalInfoNavigation/index.js
christianalfoni/ducky-components
import React from 'react'; import PropTypes from 'prop-types'; import Wrapper from '../Wrapper'; import Typography from '../Typography'; import IconAvaWrapper from '../IconAvaWrapper'; import styles from './styles.css'; function GoalInfoNavigation(props) { return ( <Wrapper className={styles.outerWrapper} size={"short"} > <IconAvaWrapper className={props.currentSlide === 1 ? styles.iconInactive : styles.iconActive} icon={'icon-keyboard_arrow_left'} onClick={props.handleLeftClick} /> <Typography className={styles.typo} type={"caption2Normal"} > {props.currentSlide}{" / "}{props.slideCount} </Typography> <IconAvaWrapper className={props.currentSlide === props.slideCount ? styles.iconInactive : styles.iconActive} icon={'icon-keyboard_arrow_right'} onClick={props.handleRightClick} /> </Wrapper> ); } GoalInfoNavigation.propTypes = { currentSlide: PropTypes.number, handleLeftClick: PropTypes.func, handleRightClick: PropTypes.func, slideCount: PropTypes.number }; export default GoalInfoNavigation;
app/components/PreSplash/PreSplash.js
heptaman/Voluncheering
import React, { Component } from 'react'; import PropTypes from 'prop-types' import { View, Text, StyleSheet, TouchableOpacity, Animated } from 'react-native' import { connect } from 'react-redux' import { colors, fontSizes } from '~/styles' import { logout } from '~/actions/auth' class PreSplash extends Component { state = { rotation: new Animated.Value(0) } handleCancel = () => { this.props.dispatch(logout()) } componentDidMount() { this.interval = setInterval(() => { Animated.sequence([ Animated.timing(this.state.rotation, {toValue: -1, duration: 150}), Animated.timing(this.state.rotation, {toValue: 1, duration: 150}), Animated.timing(this.state.rotation, {toValue: 0, duration: 250}) ]).start() }, 1000) } componentWillUnmount() { window.clearInterval(this.interval) } getTransform() { return { transform: [{ rotate: this.state.rotation.interpolate({ inputRange: [-1, 1], outputRange: ['-20deg', '20deg'] }) }] } } render() { return ( <View style={styles.container}> <Animated.Image style={[styles.image, this.getTransform()]} source={require('../../images/logo.gif')} /> <Text style={styles.message}>We are logging you in...</Text> {/* <View style={styles.buttonContainer}> <TouchableOpacity onPress={this.handleCancel} style={styles.cancelButton}> <Text style={styles.cancelText}>Cancel</Text> </TouchableOpacity> </View> */} </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: colors.white, alignItems: 'center', justifyContent: 'center' }, image: { resizeMode: 'contain', height: 300 }, message: { marginTop: 32, fontSize: fontSizes.secondary, }, buttonContainer: { marginTop: 48, width: '100%', alignItems: 'center' }, cancelButton: { height: 40, width: 240, backgroundColor: colors.red, alignItems: 'center', borderRadius: 8, padding: 10, }, cancelText: { color: colors.background, fontSize: fontSizes.secondary, }, }) export default connect()(PreSplash)
electronApp/node_modules/react-element-to-jsx-string/AnonymousStatelessComponent.js
eyang414/superFriend
import React from 'react'; export default function(props) { let {children} = props; // eslint-disable-line react/prop-types return <div>{children}</div>; }
docs/app/Examples/modules/Modal/Types/index.js
mohammed88/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import { Message } from 'semantic-ui-react' const ModalExamples = () => ( <ExampleSection title='Types'> <ComponentExample title='Modal' description='A standard modal.' examplePath='modules/Modal/Types/ModalExampleModal' /> <ComponentExample title='Basic' description='A modal can reduce its complexity.' examplePath='modules/Modal/Types/ModalExampleBasic' /> <ComponentExample title='Scrolling Modal' description={[ 'When your modal content exceeds the height of the browser the scrollable area will automatically', 'expand to include just enough space for scrolling, without scrolling the page below.', ].join(' ')} examplePath='modules/Modal/Types/ModalExampleScrolling' > <Message warning> <code>&lt;Modal.Content image /&gt;</code> requires an image with wrapped markup: <code>&lt;Image wrapped /&gt; </code> </Message> </ComponentExample> <ComponentExample title='Multiple Modals' description='Multiple modals can be displayed on top of one another.' examplePath='modules/Modal/Types/ModalExampleMultiple' /> <ComponentExample title='Controlled' description='A modal can be a controlled component' examplePath='modules/Modal/Types/ModalExampleControlled' /> </ExampleSection> ) export default ModalExamples
packages/material-ui-icons/src/SpeakerNotes.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM8 14H6v-2h2v2zm0-3H6V9h2v2zm0-3H6V6h2v2zm7 6h-5v-2h5v2zm3-3h-8V9h8v2zm0-3h-8V6h8v2z" /></g> , 'SpeakerNotes');
website/core/WebPlayer.js
skevy/react-native
/** * 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 WebPlayer */ 'use strict'; var Prism = require('Prism'); var React = require('React'); var WEB_PLAYER_VERSION = '1.2.6'; /** * Use the WebPlayer by including a ```ReactNativeWebPlayer``` block in markdown. * * Optionally, include url parameters directly after the block's language. For * the complete list of url parameters, see: https://github.com/dabbott/react-native-web-player * * E.g. * ```ReactNativeWebPlayer?platform=android * import React from 'react'; * import { AppRegistry, Text } from 'react-native'; * * const App = () => <Text>Hello World!</Text>; * * AppRegistry.registerComponent('MyApp', () => App); * ``` */ var WebPlayer = React.createClass({ parseParams: function(paramString) { var params = {}; if (paramString) { var pairs = paramString.split('&'); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split('='); params[pair[0]] = pair[1]; } } return params; }, render: function() { var hash = `#code=${encodeURIComponent(this.props.children)}`; if (this.props.params) { hash += `&${this.props.params}`; } return ( <div className={'web-player'}> <Prism>{this.props.children}</Prism> <iframe style={{marginTop: 4}} width="880" height={this.parseParams(this.props.params).platform === 'android' ? '425' : '420'} data-src={`//cdn.rawgit.com/dabbott/react-native-web-player/gh-v${WEB_PLAYER_VERSION}/index.html${hash}`} frameBorder="0" /> </div> ); }, }); module.exports = WebPlayer;
client-web/client-web/src/components/ListViewProperty.js
ppsari/final
import React from 'react' import { Link } from 'react-router-dom' import axios from 'axios' import prettyMoney from '../helpers/prettyMoney' const api = 'https://api.room360.ga/api' class ListViewProperty extends React.Component { constructor(props){ super(props) this.state={ properties:[] } } render () { return ( <div className="ListViewProperty"> {this.state.properties.map((prp,index)=>{ console.log(prp); return <div className="media m-t-20 shadow" key={index}> <div className="media-left" style={{minHeight: 124}}> <div style={{width: 120, height: 160, overflow: 'hidden'}}> <img style={{height: '100%'}} src={prp.image} alt="64x64" /> </div> </div> <div className="media-body padding-15"> <h5 className="extra-bold">{prp.name}</h5> <span className="lnr lnr-map-marker m-r-5 green"></span><span>{prp.city}</span> | <span className="lnr lnr-home m-r-5 m-l-5 green"></span><span> For {prp.status}</span><br/> <small className="excerpt italic">Price : {prettyMoney(prp.price.amount)}</small><br/> <small className="excerpt italic">Posted At : {prp.createdDate.split('T')[0]}</small> </div> <div className="media-right padding-15"> <div className="pull-right"> <Link to={`/dashboard/property/detail/${prp.status}/${prp._id}`}> <button type="submit" className="btn-round m-t-0 p-l-20 p-r-20 p-t-5 p-b-5 btn-primary btn-same"> <small>See Detail</small> </button> </Link> <Link to={`/dashboard/property/add-room/${prp.status}/${prp._id}`}> <button type="submit" className="btn-round m-t-0 p-l-20 p-r-20 p-t-5 p-b-5 btn-line btn-same"> <small>Add Room</small> </button> </Link> <button type="submit" className="btn-round m-t-0 p-l-20 p-r-20 p-t-5 p-b-5 btn-danger btn-same" onClick={()=>this.deleteProp(prp.status,prp._id,index)}> <small>Delete Room</small> </button> </div> </div> </div> })} </div> ) } deleteProp(status,id,index){ if(window.confirm(`Are you sure you want to delete this property?`)){ const token = JSON.parse(localStorage.getItem('token')).token if(status === 'rent'){ axios.delete(api+`/propertyRent/${id}`,{headers:{token: token}}) .then(response=>{ this.state.properties.splice(index,1) this.setState({ properties: this.state.properties }) }) } else{ axios.delete(api+`/propertySell/${id}`,{headers:{token: token}}) .then(response=>{ this.state.properties.splice(index,1) this.setState({ properties: this.state.properties }) }) } } else { return false } } componentDidMount(){ let token = JSON.parse(localStorage.getItem(`token`)).token axios.get(api+`/propertyRent/owner`,{headers:{token:token}}) .then(pr=>{ if(pr.data.length > 0){ this.setState({ properties: this.state.properties.concat(pr.data) }) } }) axios.get(api+`/propertySell/owner`,{headers:{token:token}}) .then(ps=>{ if(ps.data.length > 0){ this.setState({ properties: this.state.properties.concat(ps.data) }) } }) } } export default ListViewProperty
app/components/map-canvas.js
laynemcnish/walksafely-react
import React from 'react'; import PureComponent from 'react-pure-render/component'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { ActionCreators } from '../actions'; const { initMap } = ActionCreators; export class MapCanvas extends PureComponent { constructor(props) { super(props); } render () { return ( <div> <h1>Map Canvas</h1> </div> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ initMap }, dispatch); } export default connect(undefined, mapDispatchToProps)(MapCanvas);
old_examples/dyno/app.js
mzabriskie/react-tabs
import React from 'react'; import { render } from 'react-dom'; import Modal from 'react-modal'; import { Tab, Tabs, TabList, TabPanel } from '../../src/index'; import '../../style/react-tabs.css'; Modal.setAppElement(document.getElementById('example')); class App extends React.Component { constructor(props) { super(props); this.state = { isModalOpen: false, selectedIndex: -1, tabs: [ { label: 'Foo', content: 'This is foo' }, { label: 'Bar', content: 'This is bar' }, { label: 'Baz', content: 'This is baz' }, { label: 'Zap', content: 'This is zap' }, ], }; } openModal = () => { this.setState({ isModalOpen: true, }); } closeModal = () => { this.setState({ isModalOpen: false, }); } addTab = () => { const label = this.refs.label.value; const content = this.refs.content.value; this.setState({ tabs: [ ...this.state.tabs, { label, content }, ], selectedIndex: this.state.tabs.length, }); this.closeModal(); } removeTab = (index) => { this.setState({ tabs: this.state.tabs.filter((tab, i) => i !== index), selectedIndex: Math.max(this.state.selectedIndex - 1, 0), }); } render() { return ( <div style={{ padding: 50 }}> <p> <button onClick={this.openModal}>+ Add</button> </p> <Tabs selectedIndex={this.state.selectedIndex} onSelect={selectedIndex => this.setState({ selectedIndex })} > <TabList> {this.state.tabs.map((tab, i) => ( <Tab key={i}> {tab.label} <a href="#" onClick={() => this.removeTab(i)}>✕</a> </Tab> ))} </TabList> {this.state.tabs.map((tab, i) => <TabPanel key={i}>{tab.content}</TabPanel>)} </Tabs> <Modal isOpen={this.state.isModalOpen} onRequestClose={this.closeModal} style={{ width: 400, height: 350, margin: '0 auto' }} contentLabel="tabs" > <h2>Add a Tab</h2> <label htmlFor="label">Label:</label><br /> <input id="label" type="text" ref="label" /><br /><br /> <label htmlFor="content">Content:</label><br /> <textarea id="content" ref="content" rows="10" cols="50" /><br /><br /> <button onClick={this.addTab}>OK</button>{' '} <button onClick={this.closeModal}>Cancel</button> </Modal> </div> ); } } render(<App />, document.getElementById('example'));
app/assets/scripts/main.js
thadk/oc-map
'use strict'; import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import MapWidget from './views/map-widget'; import TableWidget from './views/table-widget'; window.OC_MAP = { initMapWidget: containerEl => { render(( <MapWidget /> ), containerEl); }, initTableWidget: containerEl => { render(( <TableWidget /> ), containerEl); } };
js/components/ClinicTab.js
tausifmuzaffar/bisApp
import React, { Component } from 'react'; import { connect } from 'react-redux'; var moment = require('moment'); import { actions } from 'react-native-navigation-redux-helpers'; import { Image, WebView, AsyncStorage, Linking } from 'react-native'; import { Container, Header, Subtitle, Title, Content, H2, Button, Footer, FooterTab,Card, CardItem, Text, Body, Left, Right, Icon, Segment, Spinner, Separator, List, ListItem, Toast } from 'native-base'; import { Actions } from 'react-native-router-flux'; import PrayerTimes from './PrayerTimes'; import JummahTimes from './JummahTimes'; import { openDrawer } from '../actions/drawer'; import { Col, Row, Grid } from 'react-native-easy-grid'; import styles from './styles'; const { popRoute, } = actions; class ClinicTab extends Component { constructor(props) { super(props); this.state = { schedule: {}, }; } getAnnouncement(){ fetch("http://rcca.aleemstudio.com/MobileSupport/Get6MonthSchedule") .then((response) => response.json()) .then((responseJson) => { this.setState({schedule: responseJson}); }) .done(); } componentWillMount() { this.getAnnouncement(); } render() { function replaceAll(str, find, replace) { return str.replace(new RegExp(find, 'g'), replace); } function cleanString(javaString){ let output; output = replaceAll(javaString, "\r\n", ''); output = replaceAll(output, "\n", ''); output = replaceAll(output, "\r", ''); output = replaceAll(output, "&nbsp;", ' '); return output; } var sche = this.state.schedule; if(sche !== {}){ return ( <Content style={{ backgroundColor: '#F5F5F5' }} > <CardItem style={{ backgroundColor: '#9575CD' }}> <Text style={{ color: '#FFF', fontSize: 16 }}>For appointments call </Text> <Text style={{ color: '#FFF', fontSize: 16, textDecorationLine: 'underline'}} onPress={() => Linking.openURL('tel:2058794247')}>(205) 879 - 4247</Text> <Text style={{ color: '#FFF', fontSize: 16 }}> option 4</Text> </CardItem> {Object.keys(sche).map(function(key,i) { return( <Content key={i}> {((sche[key].doc1 !== null)||(sche[key].nur1 !== null)|| (sche[key].doc1 !== null))&&(moment(key)>=moment()) ? <Content> <Separator bordered noTopBorder> <Text style={{fontSize: 14}}>{moment(key).format('MMMM D, YYYY')}</Text> </Separator> <ListItem> <Text style={{fontSize: 15, fontWeight: 'bold'}}>Doctor{sche[key].doc2 !== null ? '(s)' : ''}:</Text> <Text style={{fontSize: 15}}> {sche[key].doc1}{sche[key].doc2 !== null ? ',' : ''} {sche[key].doc2}</Text> </ListItem> <ListItem> <Text style={{fontSize: 15, fontWeight: 'bold'}}>Nurse{sche[key].nur2 !== null ? '(s)' : ''}:</Text> <Text style={{fontSize: 15}}> {sche[key].nur1}{sche[key].nur2 !== null ? ',' : ''} {sche[key].nur2}</Text> </ListItem> <ListItem> <Text style={{fontSize: 15, fontWeight: 'bold'}}>Volunteer{sche[key].vol2 !== null ? '(s)' : ''}:</Text> <Text style={{fontSize: 15}}> {sche[key].vol1}{sche[key].vol2 !== null ? ',' : ''} {sche[key].vol2}</Text> </ListItem> </Content> : <Content></Content>} </Content> ); })} </Content> ); } else { return (<Spinner color="blue" />); } } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(ClinicTab);
packages/bonde-admin-canary/src/scenes/Auth/scenes/ResetPassword/InvalidToken.spec.js
ourcities/rebu-client
import test from 'ava' import React from 'react' import { shallow } from 'enzyme' import { Trans } from 'react-i18next' import { Title } from 'bonde-styleguide' import Link, { ButtonLink } from 'components/Link' import InvalidToken from './InvalidToken' test.beforeEach(t => { const i18n = key => key t.context.node = shallow(<InvalidToken t={i18n} />) }) test('should render header infos', t => { const { node } = t.context const title = node.find(Title.H2) const subtitle = node.find(Title.H4).at(0) t.is(title.props().children, 'resetPassword.invalidToken.title') t.is(subtitle.props().children, 'resetPassword.invalidToken.subtitle') }) test('should render a link to forget password', t => { const { node } = t.context const description = node.find(Title.H4).at(1) const trans = description.find(Trans) const link = trans.find(Link) t.is(link.props().to, '/auth/forget-password') t.is(trans.props().i18nKey, 'resetPassword.invalidToken.resendToken') }) test('should render a link to login', t => { const { node } = t.context const link = node.find(ButtonLink) t.is(link.props().to, '/auth/login') t.is(link.props().children, 'resetPassword.invalidToken.goBackLogin') })
fields/types/location/LocationColumn.js
pr1ntr/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; const SUB_FIELDS = ['street1', 'suburb', 'state', 'postcode', 'country']; var LocationColumn = React.createClass({ displayName: 'LocationColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value || !Object.keys(value).length) return null; const output = []; SUB_FIELDS.map((i) => { if (value[i]) { output.push(value[i]); } }); return ( <ItemsTableValue field={this.props.col.type} title={output.join(', ')}> {output.join(', ')} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = LocationColumn;
RNDemo/RNComment/node_modules/react-navigation/src/navigators/DrawerNavigator.js
995996812/Web
/* @flow */ import React from 'react'; import { Dimensions, Platform } from 'react-native'; import createNavigator from './createNavigator'; import createNavigationContainer from '../createNavigationContainer'; import TabRouter from '../routers/TabRouter'; import DrawerScreen from '../views/Drawer/DrawerScreen'; import DrawerView from '../views/Drawer/DrawerView'; import DrawerItems from '../views/Drawer/DrawerNavigatorItems'; import NavigatorTypes from './NavigatorTypes'; import type { DrawerViewConfig } from '../views/Drawer/DrawerView'; import type { NavigationRouteConfigMap, NavigationTabRouterConfig, } from '../TypeDefinition'; export type DrawerNavigatorConfig = { containerConfig?: void, } & NavigationTabRouterConfig & DrawerViewConfig; const DefaultDrawerConfig = { /* * Default drawer width is screen width - header width * https://material.io/guidelines/patterns/navigation-drawer.html */ drawerWidth: Dimensions.get('window').width - (Platform.OS === 'android' ? 56 : 64), contentComponent: DrawerItems, drawerPosition: 'left', }; const DrawerNavigator = ( routeConfigs: NavigationRouteConfigMap, config: DrawerNavigatorConfig ) => { const mergedConfig = { ...DefaultDrawerConfig, ...config }; const { containerConfig, drawerWidth, contentComponent, contentOptions, drawerPosition, ...tabsConfig } = mergedConfig; const contentRouter = TabRouter(routeConfigs, tabsConfig); const drawerRouter = TabRouter( { DrawerClose: { screen: createNavigator( contentRouter, routeConfigs, config, NavigatorTypes.DRAWER )((props: *) => <DrawerScreen {...props} />), }, DrawerOpen: { screen: () => null, }, }, { initialRouteName: 'DrawerClose', } ); const navigator = createNavigator( drawerRouter, routeConfigs, config, NavigatorTypes.DRAWER )((props: *) => ( <DrawerView {...props} drawerWidth={drawerWidth} contentComponent={contentComponent} contentOptions={contentOptions} drawerPosition={drawerPosition} /> )); return createNavigationContainer(navigator, containerConfig); }; export default DrawerNavigator;
src/components/GlobalSearchResults.js
FiviumAustralia/RNSH-Pilot
import React, { Component } from 'react'; import { Link } from 'react-router'; import SearchResultRow from 'components/SearchResultRow'; import GlobalSearchFilters from 'components/GlobalSearchFilters'; import styles from './GlobalSearchResults.scss'; export default class GlobalSearchResults extends Component { render () { if (this.props.searchResultsVisibility === 'expanded') { var patientList = () => { return this.props.results.map((p) => { return ( <SearchResultRow key={p.id} patient={p}/> ); }); }; return ( <div className={styles['gs-result-container']}> <GlobalSearchFilters toggleTumorFilter={this.props.toggleTumorFilter} tumorFilter={this.props.tumorFilter} mainClass='gs-result-filters' selectedClass='gs-tumor-filter-selected' /> <div className={styles['gs-results']}> <div className={styles['chrome-workaround']}> <ul className={styles['gs-patient-search-results']}> {patientList()} </ul> </div> </div> <div className={styles['gs-results-footer']}> <Link className={styles['gs-advanced-search']} to={`/`} >Advanced Search</Link> </div> </div> ); } else { return null; } }; }; GlobalSearchResults.propTypes = { searchResultsVisibility: React.PropTypes.string, toggleTumorFilter: React.PropTypes.func.isRequired, results: React.PropTypes.array, tumorFilter: React.PropTypes.string, styles: React.PropTypes.object, };
src/containers/todo_item_detail.js
vijayviji/react-native-redux-todoapp
import React, { Component } from 'react'; import TodoItemDetailComp from '../components/todo_item_detail' import { MarkTodo } from '../action_creators'; import { TodoStates } from '../constants'; export default class TodoItemDetail extends Component { constructor(props) { super(props); } componentDidMount() { this.unsubscribe = this.props.store.subscribe(() => { this.forceUpdate(); }); } componentWillUnmount() { this.unsubscribe(); } render() { const todo = this._getTodo(this.props.id, this.props.store.getState().todos); return ( <TodoItemDetailComp todo = { todo } onMarkStateClicked = {() => { const next_todo_state = (todo.state === TodoStates.ACTIVE) ? TodoStates.COMPLETED : TodoStates.ACTIVE; this._markState(todo.id, next_todo_state); }} /> ); } _getTodo(id, todos) { return todos.filter(item => { if (id === item.id) { return item; } })[0]; } _markState(id, todo_state) { this.props.store.dispatch( MarkTodo(id, todo_state) ); } }
demo/sections/Example/Prop.js
joshq00/react-mdl
import React from 'react'; import Code from './Code'; function getJSON( value ) { const json = JSON.stringify( value, 0, 2 ); return json.replace( /"([^"]+)":/g, '$1:' ).trim(); } const Prop = ( props ) => { let { attr, value } = props; attr = ` ${ attr }`; if ( value === true ) { return <span>{ attr }</span>; } if ( React.isValidElement( value ) ) { return <span>{ attr }={`{ `}<Code el={ value } style={{ marginLeft: '1em' }} />{` }`}</span>; } switch ( typeof value ) { case 'string': value = `"${ value }"`; break; case 'object': // value = `{${ getJSON( value ) }}`; value = <span style={{ whiteSpace: 'pre' }}>{`{`}{ getJSON( value ) }{`}`}</span>; break; case 'function': value = `{ this._${ props.attr } }`; break; case 'boolean': case 'number': default: value = `{ ${ value } }`; } return <span>{ attr }={ value }</span>; }; Prop.propTypes = { attr: React.PropTypes.string, value: React.PropTypes.any }; export default Prop;
src/components/groups/Edit.js
dhruv-kumar-jha/productivity-frontend
'use strict'; import React, { Component } from 'react'; import { browserHistory } from 'react-router'; import { Modal, Spin, Icon, message, Button, Form, Input } from 'antd'; import ModalHeader from 'app/components/productivity/modal/Header'; const FormItem = Form.Item; import { graphql } from 'react-apollo'; import UpdateGroupMutation from 'app/graphql/mutations/groups/Update'; import GetAllGroupsQuery from 'app/graphql/queries/groups/All'; import Loading from 'app/components/common/Loading'; import _ from 'lodash'; import update from 'immutability-helper'; class EditGroup extends Component { constructor(props) { super(props); this.state = { processing: false, }; this.handleFormSubmit = this.handleFormSubmit.bind(this); this.resetForm = this.resetForm.bind(this); } handleCancel() { browserHistory.push('/settings/groups'); } handleFormSubmit(e) { e.preventDefault(); this.props.form.validateFields( (err, fields) => { if ( ! err ) { const group = _.find( this.props.data.groups, { id: this.props.params.id } ); if ( fields.name === group.name && fields.description === group.description ) { return message.warning('Please make changes first before updating.'); } this.setState({ processing: true }); this.props.mutate({ variables: { id: group.id, name: fields.name, description: fields.description, }, optimisticResponse: { __typename: 'Mutation', updateGroup: { __typename: 'Group', id: group.id, name: fields.name, description: fields.description, status: group.status, }, }, // updateQueries: { // AllGroups: (previousResult, { mutationResult }) => { // const updateGroup = mutationResult.data.updateGroup; // const groupIndex = _.findIndex( previousResult.groups, { id: group.id } ); // const updated = update(previousResult, { // groups: { // $splice: [[ groupIndex, 1, updateGroup ]] // }, // }); // return updated; // } // }, }) .then( res => { this.setState({ processing: false }); message.success('Group details has been successfully updated.'); }) .catch( res => { if ( res.graphQLErrors ) { const errors = res.graphQLErrors.map( error => error.message ); } }); } }); } resetForm() { this.props.form.resetFields(); } render() { if ( this.props.data.loading ) { return <Loading /> } const { groups } = this.props.data; const group = _.find( groups, { id: this.props.params.id } ); const { getFieldDecorator } = this.props.form; return ( <Modal wrapClassName="modal__primary" visible={ true } maskClosable={ false } onCancel={ this.handleCancel } footer={[]} > <Spin spinning={ this.state.processing } size="large" tip="Updating group, Please wait..." > <ModalHeader title={ <div><span>Update Group:</span> { group.name }</div> } subtitle="Change the details below and click on Update to save changes.." editable={ false } icon="plus-square-o" /> <div className="container"> <div className="content full"> <Form layout="vertical" onSubmit={ this.handleFormSubmit }> <FormItem label="Group Name" hasFeedback> { getFieldDecorator('name', { rules: [{ required: true, message: 'Please enter group name' }], initialValue: group.name, })( <Input placeholder="Group Name" autoComplete="off" autoFocus={true} /> ) } </FormItem> <FormItem label="Group Description" hasFeedback > { getFieldDecorator('description', { initialValue: group.description, })( <Input type="textarea" placeholder="Group Description" autosize={{ minRows: 3, maxRows: 6 }} /> ) } </FormItem> <FormItem className="m-b-0"> <Button type="primary" size="default" icon="check" htmlType="submit">Update Group</Button> <Button type="ghost" size="default" icon="reload" onClick={ this.resetForm } className="m-l-10">Reset</Button> </FormItem> </Form> </div> </div> </Spin> </Modal> ); } } EditGroup = Form.create()(EditGroup); export default graphql(GetAllGroupsQuery)( graphql(UpdateGroupMutation, { name: 'mutate' })(EditGroup) );
app/javascript/mastodon/features/favourites/index.js
hyuki0000/mastodon
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 { fetchFavourites } from '../../actions/interactions'; import { ScrollContainer } from 'react-router-scroll'; import AccountContainer from '../../containers/account_container'; import Column from '../ui/components/column'; import ColumnBackButton from '../../components/column_back_button'; import ImmutablePureComponent from 'react-immutable-pure-component'; const mapStateToProps = (state, props) => ({ accountIds: state.getIn(['user_lists', 'favourited_by', Number(props.params.statusId)]), }); @connect(mapStateToProps) export default class Favourites extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, accountIds: ImmutablePropTypes.list, }; componentWillMount () { this.props.dispatch(fetchFavourites(Number(this.props.params.statusId))); } componentWillReceiveProps (nextProps) { if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) { this.props.dispatch(fetchFavourites(Number(nextProps.params.statusId))); } } render () { const { accountIds } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } return ( <Column> <ColumnBackButton /> <ScrollContainer scrollKey='favourites'> <div className='scrollable'> {accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)} </div> </ScrollContainer> </Column> ); } }
RNApp/app/components/GenericTextInput/GenericTextInput.js
abhaytalreja/react-native-telescope
import React from 'react'; import { View, TextInput } from 'react-native'; import styles from './styles'; const GenericTextInput = (props) => { return ( <View> {props.borderTop ? <View style={styles.divider} /> : null} <TextInput style={styles.input} autoCapitalize="none" autoCorrect={false} {...props} /> </View> ); }; GenericTextInput.propTypes = { borderTop: React.PropTypes.bool, }; export default GenericTextInput;
tests/components/circular-grid-lines-tests.js
Apercu/react-vis
import test from 'tape'; import React from 'react'; import {mount} from 'enzyme'; import CircularGridLines from 'plot/circular-grid-lines'; import {testRenderWithProps, GENERIC_XYPLOT_SERIES_PROPS} from '../test-utils'; import FauxRadialScatterplot from '../../showcase/plot/faux-radial-scatterplot'; testRenderWithProps(CircularGridLines, GENERIC_XYPLOT_SERIES_PROPS); test('CircularGridLines: Showcase Example - FauxRadialScatterplot', t => { const $ = mount(<FauxRadialScatterplot />); t.equal($.text(), '-3-2-10123-3-2-10123', 'should find the right text content'); t.equal($.find('.rv-xy-plot__circular-grid-lines__line').length, 7, 'should find the right number of circles'); t.end(); });
src/InfoPanel.js
honmanyau/muup-story
import React, { Component } from 'react'; import './GameController.css'; class InfoPanel extends React.Component { render() { let player = this.props.player; let HPPercentage = player.hp / player.mhp * 100; const HPBarFillWidth = { width: HPPercentage + "%" }; return( <div className="GameController-infoPanel"> <div className="GameController-infoPanelLabel">{this.props.floor}<small>F</small></div> <div className="GameController-infoPanelLabel"><small>Lv</small>{player.level}</div> <div className="GameController-infoPanelLabel"> <small>HP</small>{player.hp}/{player.mhp} <div className="GameController-infoPanelLabel-HPBar"> <div className="GameController-infoPanelLabel-HPBarFill" style={HPBarFillWidth}></div> </div> </div> <div className="GameController-infoPanelLabel"> <small>ATK</small>{player.attack} <div className="GameController-extraSmallText">{player.weapon}</div> </div> </div> ); } }; export default InfoPanel
assets/jqwidgets/demos/react/app/grid/bindingtoremotedata/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js'; class App extends React.Component { render() { let source = { datatype: 'jsonp', datafields: [ { name: 'countryName', type: 'string' }, { name: 'name', type: 'string' }, { name: 'population', type: 'float' }, { name: 'continentCode', type: 'string' } ], url: 'http://api.geonames.org/searchJSON' }; let dataAdapter = new $.jqx.dataAdapter(source, { formatData: (data) => { $.extend(data, { featureClass: 'P', style: 'full', maxRows: 50, username: 'jqwidgets' }); return data; } } ); let columns = [ { text: 'Country Name', datafield: 'countryName', width: 200 }, { text: 'City', datafield: 'name', width: 170 }, { text: 'Population', datafield: 'population', cellsformat: 'f', width: 170 }, { text: 'Continent Code', datafield: 'continentCode', minwidth: 110 } ]; return ( <div style={{ fontSize: 13, fontFamily: 'Verdana', float: 'left' }}> <JqxGrid width={850} source={dataAdapter} columnsresize={true} columns={columns} /> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
client/modules/App/components/DevTools.js
tranphong001/BIGVN
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-w" > <LogMonitor /> </DockMonitor> );
source/server/routes/main/index.js
ericelliott/universal-react-boilerplate
import React from 'react'; import { match } from 'react-router'; import renderLayout from 'server/render-layout'; import render from 'server/render'; import settings from 'server/settings'; import configureStore from 'shared/configure-store'; import createRoutes from 'shared/routes'; const store = configureStore(); const routes = createRoutes(React); const initialState = store.getState(); export default (req, res) => { match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { if (error) { res.status(500).send(error.message); } else if (redirectLocation) { res.redirect(302, redirectLocation.pathname + redirectLocation.search); } else if (renderProps) { const rootMarkup = render(React)(renderProps, store); res.status(200).send(renderLayout({ settings, rootMarkup, initialState })); } else { res.status(404).send('Not found'); } }); };
src/demo/field.js
react-entanglement/react-entanglement
import React from 'react' export default function Field({ value, onChange }) { return <input onChange={e => onChange(e.target.value)} value={value} /> }
_experiment/react-fetch-github-repo/v1-external-fetch-file/src/Repo.js
David-Castelli/react-testing
// Render of single element import React from 'react'; import {render} from 'react-dom'; // Single element const Repo = ({repo, item}) => <article> <div className='article-content'> {item} <a href={repo.url}> <h3 className='title'>{repo.name}</h3> </a> <p className='description'>{repo.description}</p> <span className='created_at'>{repo.created_at}</span> <span className='updated_at'>{repo.updated_at}</span> <br/> <span className='open_issues'>{repo.open_issues}</span> <span className='watchers'>{repo.watchers}</span> <p className='language'>{repo.language}</p> </div> </article> export default Repo;
src/js/ui/components/entryListFilter.js
hiddentao/heartnotes
import _ from 'lodash'; import React from 'react'; import { connectRedux } from '../helpers/decorators'; import Loading from './loading'; var Component = React.createClass({ propTypes: { searchKeyword: React.PropTypes.string, }, getDefaultProps: function() { return { searchKeyword: null, }; }, getInitialState: function() { return { keyword: null, }; }, render: function() { let filter = null, summary = null; let searchIndexing = this.props.data.diary.searchIndexing; if (!searchIndexing.success) { filter = ( <Loading text="Rebuilding search..." /> ); } else { let filterText = null; let keyword = this.state.keyword; filter = ( <input ref="input" value={keyword} type="text" placeholder="Search..." onChange={this._onChange} /> ); if (keyword) { summary = ( <span className="filter-summary">Filter by: {keyword}</span> ); } } return ( <div className="entry-list-filter"> {filter} {summary} </div> ); }, componentWillReceiveProps: function(newProps) { if (newProps.searchKeyword !== this.state.keyword) { this.setState({ keyword: newProps.searchKeyword }); } }, _onChange: function(e) { let keyword = e.currentTarget.value; this.setState({ keyword: keyword, }); this.props.actions.search(keyword); }, }); module.exports = connectRedux([ 'search' ])(Component);
node_modules/react-bootstrap/es/Well.js
geng890518/editor-ui
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 { bsClass, bsSizes, getClassSet, splitBsProps } from './utils/bootstrapUtils'; import { Size } from './utils/StyleConfig'; var Well = function (_React$Component) { _inherits(Well, _React$Component); function Well() { _classCallCheck(this, Well); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Well.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('div', _extends({}, elementProps, { className: classNames(className, classes) })); }; return Well; }(React.Component); export default bsClass('well', bsSizes([Size.LARGE, Size.SMALL], Well));
app/components/layout/newProject/imageUploader.js
communicode-source/communicode
import React from 'react'; import styles from './../../../assets/css/pages/createProject.scss'; class ImageUpload extends React.Component { constructor() { super(); this.state = {file: '', imagePreviewUrl: ''}; } _handleSubmit(e) { e.preventDefault(); } _handleImageChange(e) { e.preventDefault(); const reader = new FileReader(); const file = e.target.files[0]; reader.onloadend = () => { this.setState({ file: file, imagePreviewUrl: reader.result }); }; reader.readAsDataURL(file); } render() { let {imagePreviewUrl} = this.state; let $imagePreview = null; if (imagePreviewUrl) { $imagePreview = (<img className={styles.cover} src={imagePreviewUrl} />); } else { $imagePreview = (<div>Please select an Image for Preview</div>); } return ( <div className={styles.question}> <h4>Cover Photo:</h4> <form onSubmit={this._handleSubmit.bind(this)}> <label className={styles.fileUploaderLabel} htmlFor="file">Choose a file <input id="file" name="file" type="file" onChange={(e)=>this._handleImageChange(e)} className={styles.fileUploadInput} /> </label> </form> <div> {$imagePreview} </div> {imagePreviewUrl !== '' && <button onClick={this._handleSubmit.bind(this)}>Upload Image</button>} </div> ); } } export default ImageUpload;
src/svg-icons/hardware/phonelink-off.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwarePhonelinkOff = (props) => ( <SvgIcon {...props}> <path d="M22 6V4H6.82l2 2H22zM1.92 1.65L.65 2.92l1.82 1.82C2.18 5.08 2 5.52 2 6v11H0v3h17.73l2.35 2.35 1.27-1.27L3.89 3.62 1.92 1.65zM4 6.27L14.73 17H4V6.27zM23 8h-6c-.55 0-1 .45-1 1v4.18l2 2V10h4v7h-2.18l3 3H23c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1z"/> </SvgIcon> ); HardwarePhonelinkOff = pure(HardwarePhonelinkOff); HardwarePhonelinkOff.displayName = 'HardwarePhonelinkOff'; HardwarePhonelinkOff.muiName = 'SvgIcon'; export default HardwarePhonelinkOff;
frontend/src/routes/Home/components/HomeView.js
qurben/mopidy-jukebox
import React from 'react' import DuckImage from '../assets/Duck.jpg' import classes from './HomeView.scss' export const HomeView = () => ( <div> <h4>Welcome!</h4> <img alt='This is a duck, because Redux!' className={classes.duck} src={DuckImage} /> </div> ) export default HomeView
docs/src/app/components/pages/components/Snackbar/ExampleTwice.js
skarnecki/material-ui
import React from 'react'; import Snackbar from 'material-ui/Snackbar'; import RaisedButton from 'material-ui/RaisedButton'; export default class SnackbarExampleTwice extends React.Component { constructor(props) { super(props); this.state = { message: 'Event 1 added to your calendar', open: false, }; this.timer = undefined; } componentWillUnMount() { clearTimeout(this.timer); } handleTouchTap = () => { this.setState({ open: true, }); this.timer = setTimeout(() => { this.setState({ message: `Event ${Math.round(Math.random() * 100)} added to your calendar`, }); }, 1500); }; handleRequestClose = () => { this.setState({ open: false, }); }; render() { return ( <div> <RaisedButton onTouchTap={this.handleTouchTap} label="Add to my calendar two times" /> <Snackbar open={this.state.open} message={this.state.message} action="undo" autoHideDuration={3000} onRequestClose={this.handleRequestClose} /> </div> ); } }
src/action-button.js
lonord/react-marked-editor
import React, { Component } from 'react'; import propTypes from 'prop-types'; class ActionButton extends Component { render() { const styles = { wrapper: { height: this.props.height, width: this.props.width }, btn: { height: this.props.height - 2, width: this.props.width - 2, lineHeight: (this.props.width - 2) + 'px' } } return ( <div style={styles.wrapper} className="wrapper" title={this.props.title}> <div className={this.props.isSelect ? 'btn btn-select' : 'btn'} style={styles.btn} onClick={this.props.onClick}> {this.props.text ? <i className={`fa ${this.props.iconClass ? 'fa-' + this.props.iconClass : ''} text-btn`}>{this.props.text}</i> : <i className={`fa ${this.props.iconClass ? 'fa-' + this.props.iconClass : ''}`}></i>} </div> <style jsx>{` .wrapper { cursor: pointer; } .btn { border-radius: 3px; border: 1px solid transparent; text-align: center; color: #777; } .btn:hover { border: 1px solid #eee; background: #fafafa; } .btn-select { border: 1px solid #eee; background: #f0f0f0; } .text-btn { font-weight: bold; } `}</style> </div> ); } } ActionButton.propTypes = { text: propTypes.string, iconClass: propTypes.string, width: propTypes.number, height: propTypes.number, onClick: propTypes.func, title: propTypes.string, isSelect: propTypes.bool }; ActionButton.defaultProps = { iconClass: '', width: 24, height: 24, isSelect: false } export default ActionButton;
app/components/FileList.js
zoo1/fil
import _ from 'underscore'; import React from 'react'; import {connect} from 'react-redux'; import classNames from 'classnames'; import {createFile, deleteFile, renameFile, openFile} from 'actions/files'; class FileRenameForm extends React.Component { constructor(props) { super(props); this.state = { path: props.path }; } componentDidMount() { React.findDOMNode(this.refs.fileName).select(); } onSubmit(event) { event.preventDefault(); this.props.onRename(this.state.path); } handleChange(event) { this.setState({ path: event.target.value }); } render() { const block = this.props.block + "__rename-form"; return ( <form className={block} onSubmit={this.onSubmit.bind(this)}> <input className={block + "__input"} value={this.state.path} ref="fileName" onChange={this.handleChange.bind(this)} /> </form> ); } } class FileItem extends React.Component { constructor(props) { super(props); this.state = { rename: props.rename }; } handleFileRename(event) { const {files, dispatch} = this.props; this.setState({rename: true}); event.preventDefault(); } handleClick(event) { const {path} = this.props; this.props.onOpenFile(path); event.preventDefault(); } renameFile(newPath) { const {dispatch} = this.props; dispatch(renameFile(this.props.path, newPath)); dispatch(openFile(newPath)); this.setState({rename: false}); } handleRemove() { const {path, dispatch, files} = this.props; dispatch(deleteFile(path)); } render() { const {path, current, block} = this.props; const isCurrent = path == current; return ( <li className={classNames({ [block + "__item"]: true, [block + "__item--current"]: isCurrent })}> <a href="#" onDoubleClick={this.handleFileRename.bind(this)} onClick={this.handleClick.bind(this)}> {this.state.rename && ( <FileRenameForm block={block} path={path} onRename={this.renameFile.bind(this)} /> )} {!this.state.rename && path} </a> {isCurrent && ( <button onClick={this.handleRemove.bind(this)} className={block + "__remove-button"}> {String.fromCharCode(10799)} </button> )} </li> ); } } class FileList extends React.Component { constructor() { super(); this.state = { renamingPath: null }; } handleNewFileButtonClick(event) { const {files, dispatch} = this.props; const files = _.keys(files).filter(name => name.startsWith(file)).length let fileName = 'module.py'; if(files !== 0) fileName = 'module' + files + '.py'; dispatch(createFile(fileName)) this.setState({renamingPath: fileName}); event.preventDefault(); } render() { const {files, current, dispatch} = this.props; const block = "file-list"; return ( <ul className={block}> {_.keys(files).map( (path) => <FileItem key={path} block={block} path={path} rename={this.state.renamingPath === path} {...this.props} /> )} <li className={classNames(block + "__item", block + "__item--new")}> <a onClick={this.handleNewFileButtonClick.bind(this)} href="#" >+</a> </li> </ul> ); } } function select(state) { return { files: state.files }; } export default connect(select)(FileList);
src/components/AddClient/components/ClientRole/StaffRole.js
TheModevShop/craft-app
import React from 'react'; import _ from 'lodash'; import Radio from 'components/uiElements/Radio/Radio'; import './staff-role.less'; class StaffRole extends React.Component { constructor(...args) { super(...args); this.state = {}; } render() { return ( <div className="staff-role-wrapper"> <section> <Radio value={'agent-restricted'} name={'agent-restricted'} active={this.props.permission} onChangeRadio={this.props.onPermissionsUpdated.bind(this)}> <span> <h4 className="bold">Restricted</h4> <h5 className="darkGray">Restricted Cannot manage their calendar (others must book appointments on their behalf). No access to Appointments Dashboard and Appointments App.</h5> </span> </Radio> <Radio value={'agent-self'} name={'agent-self'} active={this.props.permission} onChangeRadio={this.props.onPermissionsUpdated.bind(this)}> <span> <h4 className="bold">Self Access <span className="regular">- Ideal for single staff member.</span></h4> <h5 className="darkGray">View, accept and decline their own appointments and view their own calendars.</h5> </span> </Radio> <Radio value={'agent-staff'} name={'agent-staff'} active={this.props.permission} onChangeRadio={this.props.onPermissionsUpdated.bind(this)}> <span> <h4 className="bold">All Staff Access <span className="regular">- Ideal for the front desk.</span></h4> <h5 className="darkGray">Restricted Cannot manage their calendar (others must book appointments on their behalf). No access to Appointments Dashboard and Appointments App.</h5> </span> </Radio> <Radio value={'resource-admin'} name={'resource-admin'} active={this.props.permission} onChangeRadio={this.props.onPermissionsUpdated.bind(this)}> <span> <h4 className="bold">Full Access <span className="regular">- Ideal for partners.</span></h4> <h5 className="darkGray">Access to everything.</h5> </span> </Radio> </section> <section></section> <section></section> </div> ); } } StaffRole.propTypes = {}; export default StaffRole;
src/components/top-menu/switch.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 React from 'react'; import WelcomeGuestTopMessage from './welcome-guest'; import WelcomeUserTopMessage from './welcome-user'; import WelcomeFirstLoginTopMessage from './welcome-first-login'; export default class TopMessageSwitch extends React.Component { static displayName = 'TopMessageSwitch'; shouldComponentUpdate(nextProps) { return nextProps !== this.props; } render() { const { message, ...props } = this.props; switch (message[1].get('message')) { case 'welcome-guest': return ( <WelcomeGuestTopMessage {...props} /> ); case 'welcome-user': return ( <WelcomeUserTopMessage {...props} /> ); case 'welcome-first-login': return ( <WelcomeFirstLoginTopMessage {...props} /> ); default: return false; } } }
packages/mineral-ui-icons/src/IconWbIridescent.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 IconWbIridescent(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M5 14.5h14v-6H5v6zM11 .55V3.5h2V.55h-2zm8.04 2.5l-1.79 1.79 1.41 1.41 1.8-1.79-1.42-1.41zM13 22.45V19.5h-2v2.95h2zm7.45-3.91l-1.8-1.79-1.41 1.41 1.79 1.8 1.42-1.42zM3.55 4.46l1.79 1.79 1.41-1.41-1.79-1.79-1.41 1.41zm1.41 15.49l1.79-1.8-1.41-1.41-1.79 1.79 1.41 1.42z"/> </g> </Icon> ); } IconWbIridescent.displayName = 'IconWbIridescent'; IconWbIridescent.category = 'image';
frontend/app_v2/src/components/WidgetArea/WidgetAreaContainer.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' // FPCC import WidgetAreaData from 'components/WidgetArea/WidgetAreaData' import Widget from 'components/Widget' import LazyLoader from 'components/LazyLoader' function WidgetAreaContainer({ id }) { const { widgets } = WidgetAreaData({ id }) return ( <section> {widgets?.length > 0 && widgets.map((widget, index) => { return ( <LazyLoader key={`${widget?.uid ? widget?.uid : 'widget'}_${index}`}> <Widget.Container widgetType={widget?.type} data={widget} /> </LazyLoader> ) })} </section> ) } // PROPTYPES const { string } = PropTypes WidgetAreaContainer.propTypes = { id: string, // The id of the 'widgetAware' document } export default WidgetAreaContainer
js/components/AlertBar.js
msldiarra/signals-ui
import React from 'react'; export default class AlertBar extends React.Component { render() { let progressBarClass = (this.props.tank.fillingrate > 50) ? "progress-bar progress-bar-success" : (this.props.tank.fillingrate > 30) ? "progress-bar progress-bar-warning": "progress-bar progress-bar-danger"; return (<div> <a className="black" href="#"> <div> <div> <h5><i className="fa fa-filter"></i> {this.props.tank.tank} (<b>{this.props.tank.liquidtype}</b>) dans la station de <b>{this.props.tank.station}</b> </h5> </div> <div className="progress"> <div className={progressBarClass} role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style={{width:this.props.tank.fillingrate + '%'}}> <span>{this.props.tank.fillingrate}%</span> </div> </div> </div> </a> </div>); } }
packages/material-ui-icons/src/CompareArrows.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M9.01 14H2v2h7.01v3L13 15l-3.99-4v3zm5.98-1v-3H22V8h-7.01V5L11 9l3.99 4z" /></g> , 'CompareArrows');
src/MeetingLink/__tests__/MeetingLink.js
Detaysoft/react-chat-elements
import React, { Component } from 'react'; import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import MeetingLink from '../MeetingLink'; describe('MeetingLink component', () => { it('should render without issues', () => { const component = shallow(<MeetingLink status='read'/>); expect(component.length).toBe(1); expect(toJson(component)).toMatchSnapshot(); }); });
components/Layout/Layout.js
tbescherer/TrumpAnxietyHotline
import {connect} from 'react-redux'; import React from 'react'; import Header from './Header'; import s from './Layout.css'; import store from '../../core/store.js'; class Layout extends React.Component { constructor(props) { super(props); } componentDidMount() { window.componentHandler.upgradeElement(this.root); } componentWillUnmount() { window.componentHandler.downgradeElements(this.root); } render() { return ( <div className="mdl-layout mdl-js-layout mdl-layout--fixed-header" ref={node => (this.root = node)}> <div className="mdl-layout__inner-container"> <Header> <span className="mdl-layout-title" onClick={() => {window.location.href=window.location.origin}} style={{cursor: 'pointer'}}>Trump Anxiety Hotline</span> <div className="mdl-layout-spacer"></div> </Header> <div className="mdl-layout__drawer"> <span className="mdl-layout-title" style={{cursor: 'pointer'}} onClick={() => {window.location.href=window.location.origin}}>Home</span> <nav className="mdl-navigation" style={{cursor: 'pointer'}}> <div className="mdl-navigation__link" onClick={() => {window.location.href="/messages"}}>Start A Conversation</div> <div className="mdl-navigation__link" onClick={() => {window.location.href="/analytics"}}>Analytics</div> <div className="mdl-navigation__link" onClick={() => {window.location.href="/links"}}>Quick Links</div> <div className="mdl-navigation__link" onClick={() => {window.location.href="/about"}}>About</div> <div className="mdl-navigation__link" onClick={() => {window.location.href="http://www.zazzle.com/trumpanxietyhotline"}}>Buy a Hat</div> </nav> </div> <main className="mdl-layout__content"> <div className={s.content} {...this.props} /> </main> </div> </div> ); } } export default Layout;
modules/__tests__/History-test.js
okcoker/react-router
/*eslint-env mocha */ import expect from 'expect' import React from 'react' import History from '../History' import Router from '../Router' import Route from '../Route' import createHistory from 'history/lib/createMemoryHistory' describe('History Mixin', function () { let node beforeEach(function () { node = document.createElement('div') }) afterEach(function () { React.unmountComponentAtNode(node) }) it('assigns the history to the component instance', function (done) { let history = createHistory('/') function assertHistory() { expect(this.history).toExist() } let Component = React.createClass({ mixins: [ History ], componentWillMount: assertHistory, render () { return null } }) React.render(( <Router history={history}> <Route path="/" component={Component} /> </Router> ), node, done) }) })
frontend/teg-web-ui/src/common/topNavigation/StaticTopNavigation.js
tegh/tegh-daemon
import React from 'react' import { Link } from 'react-router-dom' import classnames from 'classnames' import Typography from '@mui/material/Typography' import Hidden from '@mui/material/Hidden' import IconButton from '@mui/material/IconButton' import MenuIcon from '@mui/icons-material/Menu' import useStyle from './TopNavigationStyles' import WordMark from '../WordMark' import UserProfileMenu from './UserProfileMenu' const StaticTopNavigation = ({ title = () => <WordMark/>, onMenuButtonClick, className, avatar = localStorage.getItem('avatar'), }) => { const classes = useStyle() const hasMenu = onMenuButtonClick != null return ( <div className={className}> <div className={classnames( classes.mainMenu, hasMenu && classes.withMenu, )} > <Hidden mdDown={!hasMenu} mdUp> <IconButton className={classes.buttonClass} aria-label="Menu" onClick={onMenuButtonClick} size="large"> <MenuIcon /> </IconButton> </Hidden> <Typography variant="h4" className={classes.title} component={React.forwardRef((props, ref) => ( <Link to="/" innerRef={ref} {...props} /> ))} > {title()} </Typography> <div className={classes.userProfileMenu} > <UserProfileMenu avatar={avatar}/> </div> </div> </div> ); } export default StaticTopNavigation
client/src/App.js
teenoh/Hello-Books
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
docs/app/Examples/views/Statistic/Types/StatisticExampleBottomLabel.js
mohammed88/Semantic-UI-React
import React from 'react' import { Statistic } from 'semantic-ui-react' const StatisticExampleBottomLabel = () => ( <div> <Statistic> <Statistic.Value>5,550</Statistic.Value> <Statistic.Label>Downloads</Statistic.Label> </Statistic> <Statistic value='5,500' label='Downloads' /> </div> ) export default StatisticExampleBottomLabel
node_modules/antd/es/button/button.js
yhx0634/foodshopfront
import _extends from 'babel-runtime/helpers/extends'; import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; var __rest = this && this.__rest || function (s, e) { var t = {}; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; }if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; }return t; }; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import omit from 'omit.js'; import Icon from '../icon'; var rxTwoCNChar = /^[\u4e00-\u9fa5]{2}$/; var isTwoCNChar = rxTwoCNChar.test.bind(rxTwoCNChar); function isString(str) { return typeof str === 'string'; } // Insert one space between two chinese characters automatically. function insertSpace(child, needInserted) { // Check the child if is undefined or null. if (child == null) { return; } var SPACE = needInserted ? ' ' : ''; // strictNullChecks oops. if (typeof child !== 'string' && typeof child !== 'number' && isString(child.type) && isTwoCNChar(child.props.children)) { return React.cloneElement(child, {}, child.props.children.split('').join(SPACE)); } if (typeof child === 'string') { if (isTwoCNChar(child)) { child = child.split('').join(SPACE); } return React.createElement( 'span', null, child ); } return child; } var Button = function (_React$Component) { _inherits(Button, _React$Component); function Button(props) { _classCallCheck(this, Button); var _this = _possibleConstructorReturn(this, (Button.__proto__ || Object.getPrototypeOf(Button)).call(this, props)); _this.handleClick = function (e) { // Add click effect _this.setState({ clicked: true }); clearTimeout(_this.timeout); _this.timeout = setTimeout(function () { return _this.setState({ clicked: false }); }, 500); var onClick = _this.props.onClick; if (onClick) { onClick(e); } }; _this.state = { loading: props.loading }; return _this; } _createClass(Button, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var _this2 = this; var currentLoading = this.props.loading; var loading = nextProps.loading; if (currentLoading) { clearTimeout(this.delayTimeout); } if (typeof loading !== 'boolean' && loading && loading.delay) { this.delayTimeout = setTimeout(function () { return _this2.setState({ loading: loading }); }, loading.delay); } else { this.setState({ loading: loading }); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (this.timeout) { clearTimeout(this.timeout); } if (this.delayTimeout) { clearTimeout(this.delayTimeout); } } }, { key: 'render', value: function render() { var _classNames; var _a = this.props, type = _a.type, shape = _a.shape, _a$size = _a.size, size = _a$size === undefined ? '' : _a$size, className = _a.className, htmlType = _a.htmlType, children = _a.children, icon = _a.icon, prefixCls = _a.prefixCls, ghost = _a.ghost, others = __rest(_a, ["type", "shape", "size", "className", "htmlType", "children", "icon", "prefixCls", "ghost"]);var _state = this.state, loading = _state.loading, clicked = _state.clicked; // large => lg // small => sm var sizeCls = ''; switch (size) { case 'large': sizeCls = 'lg'; break; case 'small': sizeCls = 'sm'; default: break; } var classes = classNames(prefixCls, className, (_classNames = {}, _defineProperty(_classNames, prefixCls + '-' + type, type), _defineProperty(_classNames, prefixCls + '-' + shape, shape), _defineProperty(_classNames, prefixCls + '-' + sizeCls, sizeCls), _defineProperty(_classNames, prefixCls + '-icon-only', !children && icon && !loading), _defineProperty(_classNames, prefixCls + '-loading', loading), _defineProperty(_classNames, prefixCls + '-clicked', clicked), _defineProperty(_classNames, prefixCls + '-background-ghost', ghost), _classNames)); var iconType = loading ? 'loading' : icon; var iconNode = iconType ? React.createElement(Icon, { type: iconType }) : null; var needInserted = React.Children.count(children) === 1 && (!iconType || iconType === 'loading'); var kids = React.Children.map(children, function (child) { return insertSpace(child, needInserted); }); return React.createElement( 'button', _extends({}, omit(others, ['loading', 'clicked']), { type: htmlType || 'button', className: classes, onClick: this.handleClick }), iconNode, kids ); } }]); return Button; }(React.Component); export default Button; Button.__ANT_BUTTON = true; Button.defaultProps = { prefixCls: 'ant-btn', loading: false, clicked: false, ghost: false }; Button.propTypes = { type: PropTypes.string, shape: PropTypes.oneOf(['circle', 'circle-outline']), size: PropTypes.oneOf(['large', 'default', 'small']), htmlType: PropTypes.oneOf(['submit', 'button', 'reset']), onClick: PropTypes.func, loading: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]), className: PropTypes.string, icon: PropTypes.string };
.history/src/components/GKM/Category_20170624164531.js
oded-soffrin/gkm_viewer
import React from 'react'; import _ from 'lodash' const Category = ({ category }) => { const items = _.map(category.items, (i) => (<div style={{ display: 'inline-block', padding: '10px' }}>{i.text}</div>)) console.log(items); return ( <div> <div> {category.type}: {category.text} </div> <div>Items:</div> {items} </div> ) }; /* Item.propTypes = { }; */ export default Category
client/components/TodoTextInput.spec.js
Pennsy/todolist
import React from 'react' import { createRenderer } from 'react-test-renderer/shallow'; import TodoTextInput from './TodoTextInput' const setup = propOverrides => { const props = Object.assign({ onSave: jest.fn(), text: 'Use Redux', placeholder: 'What needs to be done?', editing: false, newTodo: false }, propOverrides) const renderer = createRenderer() renderer.render( <TodoTextInput {...props} /> ) const output = renderer.getRenderOutput() return { props: props, output: output, renderer: renderer } } describe('components', () => { describe('TodoTextInput', () => { it('should render correctly', () => { const { output } = setup() expect(output.props.placeholder).toEqual('What needs to be done?') expect(output.props.value).toEqual('Use Redux') expect(output.props.className).toEqual('') }) it('should render correctly when editing=true', () => { const { output } = setup({ editing: true }) expect(output.props.className).toEqual('edit') }) it('should render correctly when newTodo=true', () => { const { output } = setup({ newTodo: true }) expect(output.props.className).toEqual('new-todo') }) it('should update value on change', () => { const { output, renderer } = setup() output.props.onChange({ target: { value: 'Use Radox' } }) const updated = renderer.getRenderOutput() expect(updated.props.value).toEqual('Use Radox') }) it('should call onSave on return key press', () => { const { output, props } = setup() output.props.onKeyDown({ which: 13, target: { value: 'Use Redux' } }) expect(props.onSave).toBeCalledWith('Use Redux') }) it('should reset state on return key press if newTodo', () => { const { output, renderer } = setup({ newTodo: true }) output.props.onKeyDown({ which: 13, target: { value: 'Use Redux' } }) const updated = renderer.getRenderOutput() expect(updated.props.value).toEqual('') }) it('should call onSave on blur', () => { const { output, props } = setup() output.props.onBlur({ target: { value: 'Use Redux' } }) expect(props.onSave).toBeCalledWith('Use Redux') }) it('shouldnt call onSave on blur if newTodo', () => { const { output, props } = setup({ newTodo: true }) output.props.onBlur({ target: { value: 'Use Redux' } }) expect(props.onSave).not.toBeCalled() }) }) })