path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/app.js
prajapati-parth/glitchy
import React from 'react' import ReactDOM from 'react-dom' //import application main component import AppComponent from '../app/components/app_component' class App extends React.Component { render() { return ( <AppComponent /> ) } } //render back to mark-up file ReactDOM.render( <App />, document.getElementById('content') )
client/src/app/routes.js
jhuntoo/starhackit
import React from 'react'; import {Route, IndexRoute} from 'react-router'; import Login from 'views/login'; import Signup from 'views/signup'; import Forgot from 'views/forgot'; import Application from 'views/application'; import Logout from 'views/logout'; import MainLanding from 'views/mainLanding'; import RegistrationComplete from 'views/registrationComplete'; import ResetPassword from 'views/resetPassword'; import MyProfile from 'views/myProfile'; import Authenticated from 'components/authenticatedComponent'; import UsersView from 'parts/admin/usersView'; let routes = ( <Route component={Application} name="home" path="/"> <IndexRoute component={MainLanding}/> <Route component={Login} path="login"/> <Route component={Signup} path="signup"/> <Route component={Logout} path="logout"/> <Route component={Forgot} path="forgot"/> <Route component={RegistrationComplete} name="verifyEmail" path="verifyEmail/:code"/> <Route component={ResetPassword} name="ResetPasswordToken" path="resetPassword/:token"/> <Route path="/admin" component={Authenticated}> <IndexRoute component={UsersView}/> <Route component={UsersView} path="users"/> </Route> <Route path="/app" component={Authenticated}> <IndexRoute component={MyProfile}/> <Route name="account" path="my"> <Route component={MyProfile} path="profile"/> </Route> </Route> </Route> ); export default routes;
examples/ModalWithBottomSheet.js
chris-gooley/react-materialize
import React from 'react'; import Modal from '../src/Modal'; import Button from '../src/Button'; export default <Modal header='Modal Header' bottomSheet trigger={<Button>MODAL BUTTOM SHEET STYLE</Button>}> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum </Modal>;
app/javascript/mastodon/features/compose/components/poll_form.js
salvadorpla/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import IconButton from 'mastodon/components/icon_button'; import Icon from 'mastodon/components/icon'; import AutosuggestInput from 'mastodon/components/autosuggest_input'; import classNames from 'classnames'; const messages = defineMessages({ option_placeholder: { id: 'compose_form.poll.option_placeholder', defaultMessage: 'Choice {number}' }, add_option: { id: 'compose_form.poll.add_option', defaultMessage: 'Add a choice' }, remove_option: { id: 'compose_form.poll.remove_option', defaultMessage: 'Remove this choice' }, poll_duration: { id: 'compose_form.poll.duration', defaultMessage: 'Poll duration' }, minutes: { id: 'intervals.full.minutes', defaultMessage: '{number, plural, one {# minute} other {# minutes}}' }, hours: { id: 'intervals.full.hours', defaultMessage: '{number, plural, one {# hour} other {# hours}}' }, days: { id: 'intervals.full.days', defaultMessage: '{number, plural, one {# day} other {# days}}' }, }); @injectIntl class Option extends React.PureComponent { static propTypes = { title: PropTypes.string.isRequired, index: PropTypes.number.isRequired, isPollMultiple: PropTypes.bool, onChange: PropTypes.func.isRequired, onRemove: PropTypes.func.isRequired, onToggleMultiple: PropTypes.func.isRequired, suggestions: ImmutablePropTypes.list, onClearSuggestions: PropTypes.func.isRequired, onFetchSuggestions: PropTypes.func.isRequired, onSuggestionSelected: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleOptionTitleChange = e => { this.props.onChange(this.props.index, e.target.value); }; handleOptionRemove = () => { this.props.onRemove(this.props.index); }; handleToggleMultiple = e => { this.props.onToggleMultiple(); e.preventDefault(); e.stopPropagation(); }; onSuggestionsClearRequested = () => { this.props.onClearSuggestions(); } onSuggestionsFetchRequested = (token) => { this.props.onFetchSuggestions(token); } onSuggestionSelected = (tokenStart, token, value) => { this.props.onSuggestionSelected(tokenStart, token, value, ['poll', 'options', this.props.index]); } render () { const { isPollMultiple, title, index, intl } = this.props; return ( <li> <label className='poll__text editable'> <span className={classNames('poll__input', { checkbox: isPollMultiple })} onClick={this.handleToggleMultiple} role='button' tabIndex='0' /> <AutosuggestInput placeholder={intl.formatMessage(messages.option_placeholder, { number: index + 1 })} maxLength={25} value={title} onChange={this.handleOptionTitleChange} suggestions={this.props.suggestions} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSuggestionSelected} searchTokens={[':']} /> </label> <div className='poll__cancel'> <IconButton disabled={index <= 1} title={intl.formatMessage(messages.remove_option)} icon='times' onClick={this.handleOptionRemove} /> </div> </li> ); } } export default @injectIntl class PollForm extends ImmutablePureComponent { static propTypes = { options: ImmutablePropTypes.list, expiresIn: PropTypes.number, isMultiple: PropTypes.bool, onChangeOption: PropTypes.func.isRequired, onAddOption: PropTypes.func.isRequired, onRemoveOption: PropTypes.func.isRequired, onChangeSettings: PropTypes.func.isRequired, suggestions: ImmutablePropTypes.list, onClearSuggestions: PropTypes.func.isRequired, onFetchSuggestions: PropTypes.func.isRequired, onSuggestionSelected: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleAddOption = () => { this.props.onAddOption(''); }; handleSelectDuration = e => { this.props.onChangeSettings(e.target.value, this.props.isMultiple); }; handleToggleMultiple = () => { this.props.onChangeSettings(this.props.expiresIn, !this.props.isMultiple); }; render () { const { options, expiresIn, isMultiple, onChangeOption, onRemoveOption, intl, ...other } = this.props; if (!options) { return null; } return ( <div className='compose-form__poll-wrapper'> <ul> {options.map((title, i) => <Option title={title} key={i} index={i} onChange={onChangeOption} onRemove={onRemoveOption} isPollMultiple={isMultiple} onToggleMultiple={this.handleToggleMultiple} {...other} />)} </ul> <div className='poll__footer'> {options.size < 4 && ( <button className='button button-secondary' onClick={this.handleAddOption}><Icon id='plus' /> <FormattedMessage {...messages.add_option} /></button> )} <select value={expiresIn} onChange={this.handleSelectDuration}> <option value={300}>{intl.formatMessage(messages.minutes, { number: 5 })}</option> <option value={1800}>{intl.formatMessage(messages.minutes, { number: 30 })}</option> <option value={3600}>{intl.formatMessage(messages.hours, { number: 1 })}</option> <option value={21600}>{intl.formatMessage(messages.hours, { number: 6 })}</option> <option value={86400}>{intl.formatMessage(messages.days, { number: 1 })}</option> <option value={259200}>{intl.formatMessage(messages.days, { number: 3 })}</option> <option value={604800}>{intl.formatMessage(messages.days, { number: 7 })}</option> </select> </div> </div> ); } }
docs/src/components/nav.js
optimizely/nuclear-js
import React from 'react' import { BASE_URL } from '../globals' function urlize(uri) { return BASE_URL + uri } export default React.createClass({ render() { const logo = this.props.includeLogo ? <a href={BASE_URL} className="brand-logo">NuclearJS</a> : null const homeLink = this.props.includeLogo ? <li className="hide-on-large-only"><a href={urlize("")}>Home</a></li> : null return <div className="navbar-fixed"> <nav className="nav"> <div className="hide-on-large-only"> <ul className="right"> {homeLink} <li><a href={urlize("docs/01-getting-started.html")}>Docs</a></li> <li><a href={urlize("docs/07-api.html")}>API</a></li> <li><a href="https://github.com/optimizely/nuclear-js">Github</a></li> </ul> </div> <div className="nav-wrapper hide-on-med-and-down"> {logo} <ul className="right"> <li><a href={urlize("docs/01-getting-started.html")}>Docs</a></li> <li><a href={urlize("docs/07-api.html")}>API</a></li> <li><a href="https://github.com/optimizely/nuclear-js">Github</a></li> </ul> </div> </nav> </div> } })
src/routes/About/components/Resume.js
mjchamoures/personalPortfolio
import React from 'react'; import { Panel } from 'react-bootstrap'; import ResumeImg from '../assets/Michael_Chamoures_Resume.png'; import ResumeImg2 from '../assets/Michael_Chamoures_Resume_2.png'; import './About.scss'; export const Resume = (props) => ( <Panel header="Resume"> <img alt='' className='resumeImg' src={ResumeImg} /> <img alt='' className='resumeImg' src={ResumeImg2} /> </Panel> ); export default Resume;
node_modules/react-router/es6/Link.js
FrancoCotter/ReactWeatherApp
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import warning from './routerWarning'; var _React$PropTypes = React.PropTypes; var bool = _React$PropTypes.bool; var object = _React$PropTypes.object; var string = _React$PropTypes.string; var func = _React$PropTypes.func; var oneOfType = _React$PropTypes.oneOfType; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } function isEmptyObject(object) { for (var p in object) { if (object.hasOwnProperty(p)) return false; }return true; } function createLocationDescriptor(to, _ref) { var query = _ref.query; var hash = _ref.hash; var state = _ref.state; if (query || hash || state) { return { pathname: to, query: query, hash: hash, state: state }; } return to; } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets the value of its * activeClassName prop. * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along location state and/or query string parameters * in the state/query props, respectively. * * <Link ... query={{ show: true }} state={{ the: 'state' }} /> */ var Link = React.createClass({ displayName: 'Link', contextTypes: { router: object }, propTypes: { to: oneOfType([string, object]).isRequired, query: object, hash: string, state: object, activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, onClick: func }, getDefaultProps: function getDefaultProps() { return { onlyActiveOnIndex: false, className: '', style: {} }; }, handleClick: function handleClick(event) { var allowTransition = true; if (this.props.onClick) this.props.onClick(event); if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; if (event.defaultPrevented === true) allowTransition = false; // If target prop is set (e.g. to "_blank") let browser handle link. /* istanbul ignore if: untestable with Karma */ if (this.props.target) { if (!allowTransition) event.preventDefault(); return; } event.preventDefault(); if (allowTransition) { var _props = this.props; var to = _props.to; var query = _props.query; var hash = _props.hash; var state = _props.state; var _location = createLocationDescriptor(to, { query: query, hash: hash, state: state }); this.context.router.push(_location); } }, render: function render() { var _props2 = this.props; var to = _props2.to; var query = _props2.query; var hash = _props2.hash; var state = _props2.state; var activeClassName = _props2.activeClassName; var activeStyle = _props2.activeStyle; var onlyActiveOnIndex = _props2.onlyActiveOnIndex; var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']); process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : undefined; // Ignore if rendered outside the context of router, simplifies unit testing. var router = this.context.router; if (router) { var _location2 = createLocationDescriptor(to, { query: query, hash: hash, state: state }); props.href = router.createHref(_location2); if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) { if (router.isActive(_location2, onlyActiveOnIndex)) { if (activeClassName) props.className += props.className === '' ? activeClassName : ' ' + activeClassName; if (activeStyle) props.style = _extends({}, props.style, activeStyle); } } } return React.createElement('a', _extends({}, props, { onClick: this.handleClick })); } }); export default Link;
Console/app/node_modules/rc-trigger/es/index.js
RisenEsports/RisenEsports.github.io
import _extends from 'babel-runtime/helpers/extends'; import React from 'react'; import PropTypes from 'prop-types'; import { findDOMNode } from 'react-dom'; import createReactClass from 'create-react-class'; import contains from 'rc-util/es/Dom/contains'; import addEventListener from 'rc-util/lib/Dom/addEventListener'; import Popup from './Popup'; import { getAlignFromPlacement, getPopupClassNameFromAlign as _getPopupClassNameFromAlign } from './utils'; import getContainerRenderMixin from 'rc-util/lib/getContainerRenderMixin'; function noop() {} function returnEmptyString() { return ''; } function returnDocument() { return window.document; } var ALL_HANDLERS = ['onClick', 'onMouseDown', 'onTouchStart', 'onMouseEnter', 'onMouseLeave', 'onFocus', 'onBlur']; var Trigger = createReactClass({ displayName: 'Trigger', propTypes: { children: PropTypes.any, action: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]), showAction: PropTypes.any, hideAction: PropTypes.any, getPopupClassNameFromAlign: PropTypes.any, onPopupVisibleChange: PropTypes.func, afterPopupVisibleChange: PropTypes.func, popup: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired, popupStyle: PropTypes.object, prefixCls: PropTypes.string, popupClassName: PropTypes.string, popupPlacement: PropTypes.string, builtinPlacements: PropTypes.object, popupTransitionName: PropTypes.oneOfType([PropTypes.string, PropTypes.object]), popupAnimation: PropTypes.any, mouseEnterDelay: PropTypes.number, mouseLeaveDelay: PropTypes.number, zIndex: PropTypes.number, focusDelay: PropTypes.number, blurDelay: PropTypes.number, getPopupContainer: PropTypes.func, getDocument: PropTypes.func, destroyPopupOnHide: PropTypes.bool, mask: PropTypes.bool, maskClosable: PropTypes.bool, onPopupAlign: PropTypes.func, popupAlign: PropTypes.object, popupVisible: PropTypes.bool, maskTransitionName: PropTypes.oneOfType([PropTypes.string, PropTypes.object]), maskAnimation: PropTypes.string }, mixins: [getContainerRenderMixin({ autoMount: false, isVisible: function isVisible(instance) { return instance.state.popupVisible; }, getContainer: function getContainer(instance) { var props = instance.props; var popupContainer = document.createElement('div'); popupContainer.style.position = 'absolute'; popupContainer.style.top = '0'; popupContainer.style.left = '0'; popupContainer.style.width = '100%'; var mountNode = props.getPopupContainer ? props.getPopupContainer(findDOMNode(instance)) : props.getDocument().body; mountNode.appendChild(popupContainer); return popupContainer; } })], getDefaultProps: function getDefaultProps() { return { prefixCls: 'rc-trigger-popup', getPopupClassNameFromAlign: returnEmptyString, getDocument: returnDocument, onPopupVisibleChange: noop, afterPopupVisibleChange: noop, onPopupAlign: noop, popupClassName: '', mouseEnterDelay: 0, mouseLeaveDelay: 0.1, focusDelay: 0, blurDelay: 0.15, popupStyle: {}, destroyPopupOnHide: false, popupAlign: {}, defaultPopupVisible: false, mask: false, maskClosable: true, action: [], showAction: [], hideAction: [] }; }, getInitialState: function getInitialState() { var props = this.props; var popupVisible = void 0; if ('popupVisible' in props) { popupVisible = !!props.popupVisible; } else { popupVisible = !!props.defaultPopupVisible; } return { popupVisible: popupVisible }; }, componentWillMount: function componentWillMount() { var _this = this; ALL_HANDLERS.forEach(function (h) { _this['fire' + h] = function (e) { _this.fireEvents(h, e); }; }); }, componentDidMount: function componentDidMount() { this.componentDidUpdate({}, { popupVisible: this.state.popupVisible }); }, componentWillReceiveProps: function componentWillReceiveProps(_ref) { var popupVisible = _ref.popupVisible; if (popupVisible !== undefined) { this.setState({ popupVisible: popupVisible }); } }, componentDidUpdate: function componentDidUpdate(_, prevState) { var props = this.props; var state = this.state; this.renderComponent(null, function () { if (prevState.popupVisible !== state.popupVisible) { props.afterPopupVisibleChange(state.popupVisible); } }); if (state.popupVisible) { var currentDocument = void 0; if (!this.clickOutsideHandler && this.isClickToHide()) { currentDocument = props.getDocument(); this.clickOutsideHandler = addEventListener(currentDocument, 'mousedown', this.onDocumentClick); } if (!this.touchOutsideHandler) { currentDocument = currentDocument || props.getDocument(); this.touchOutsideHandler = addEventListener(currentDocument, 'touchstart', this.onDocumentClick); } return; } this.clearOutsideHandler(); }, componentWillUnmount: function componentWillUnmount() { this.clearDelayTimer(); this.clearOutsideHandler(); }, onMouseEnter: function onMouseEnter(e) { this.fireEvents('onMouseEnter', e); this.delaySetPopupVisible(true, this.props.mouseEnterDelay); }, onMouseLeave: function onMouseLeave(e) { this.fireEvents('onMouseLeave', e); this.delaySetPopupVisible(false, this.props.mouseLeaveDelay); }, onPopupMouseEnter: function onPopupMouseEnter() { this.clearDelayTimer(); }, onPopupMouseLeave: function onPopupMouseLeave(e) { if (e.relatedTarget && !e.relatedTarget.setTimeout && this._component && contains(this._component.getPopupDomNode(), e.relatedTarget)) { return; } this.delaySetPopupVisible(false, this.props.mouseLeaveDelay); }, onFocus: function onFocus(e) { this.fireEvents('onFocus', e); this.clearDelayTimer(); if (this.isFocusToShow()) { this.focusTime = Date.now(); this.delaySetPopupVisible(true, this.props.focusDelay); } }, onMouseDown: function onMouseDown(e) { this.fireEvents('onMouseDown', e); this.preClickTime = Date.now(); }, onTouchStart: function onTouchStart(e) { this.fireEvents('onTouchStart', e); this.preTouchTime = Date.now(); }, onBlur: function onBlur(e) { this.fireEvents('onBlur', e); this.clearDelayTimer(); if (this.isBlurToHide()) { this.delaySetPopupVisible(false, this.props.blurDelay); } }, onClick: function onClick(event) { this.fireEvents('onClick', event); if (this.focusTime) { var preTime = void 0; if (this.preClickTime && this.preTouchTime) { preTime = Math.min(this.preClickTime, this.preTouchTime); } else if (this.preClickTime) { preTime = this.preClickTime; } else if (this.preTouchTime) { preTime = this.preTouchTime; } if (Math.abs(preTime - this.focusTime) < 20) { return; } this.focusTime = 0; } this.preClickTime = 0; this.preTouchTime = 0; event.preventDefault(); var nextVisible = !this.state.popupVisible; if (this.isClickToHide() && !nextVisible || nextVisible && this.isClickToShow()) { this.setPopupVisible(!this.state.popupVisible); } }, onDocumentClick: function onDocumentClick(event) { if (this.props.mask && !this.props.maskClosable) { return; } var target = event.target; var root = findDOMNode(this); var popupNode = this.getPopupDomNode(); if (!contains(root, target) && !contains(popupNode, target)) { this.close(); } }, getPopupDomNode: function getPopupDomNode() { if (this._component && this._component.getPopupDomNode) { return this._component.getPopupDomNode(); } return null; }, getRootDomNode: function getRootDomNode() { return findDOMNode(this); }, getPopupClassNameFromAlign: function getPopupClassNameFromAlign(align) { var className = []; var props = this.props; var popupPlacement = props.popupPlacement, builtinPlacements = props.builtinPlacements, prefixCls = props.prefixCls; if (popupPlacement && builtinPlacements) { className.push(_getPopupClassNameFromAlign(builtinPlacements, prefixCls, align)); } if (props.getPopupClassNameFromAlign) { className.push(props.getPopupClassNameFromAlign(align)); } return className.join(' '); }, getPopupAlign: function getPopupAlign() { var props = this.props; var popupPlacement = props.popupPlacement, popupAlign = props.popupAlign, builtinPlacements = props.builtinPlacements; if (popupPlacement && builtinPlacements) { return getAlignFromPlacement(builtinPlacements, popupPlacement, popupAlign); } return popupAlign; }, getComponent: function getComponent() { var props = this.props, state = this.state; var mouseProps = {}; if (this.isMouseEnterToShow()) { mouseProps.onMouseEnter = this.onPopupMouseEnter; } if (this.isMouseLeaveToHide()) { mouseProps.onMouseLeave = this.onPopupMouseLeave; } return React.createElement( Popup, _extends({ prefixCls: props.prefixCls, destroyPopupOnHide: props.destroyPopupOnHide, visible: state.popupVisible, className: props.popupClassName, action: props.action, align: this.getPopupAlign(), onAlign: props.onPopupAlign, animation: props.popupAnimation, getClassNameFromAlign: this.getPopupClassNameFromAlign }, mouseProps, { getRootDomNode: this.getRootDomNode, style: props.popupStyle, mask: props.mask, zIndex: props.zIndex, transitionName: props.popupTransitionName, maskAnimation: props.maskAnimation, maskTransitionName: props.maskTransitionName }), typeof props.popup === 'function' ? props.popup() : props.popup ); }, setPopupVisible: function setPopupVisible(popupVisible) { this.clearDelayTimer(); if (this.state.popupVisible !== popupVisible) { if (!('popupVisible' in this.props)) { this.setState({ popupVisible: popupVisible }); } this.props.onPopupVisibleChange(popupVisible); } }, delaySetPopupVisible: function delaySetPopupVisible(visible, delayS) { var _this2 = this; var delay = delayS * 1000; this.clearDelayTimer(); if (delay) { this.delayTimer = setTimeout(function () { _this2.setPopupVisible(visible); _this2.clearDelayTimer(); }, delay); } else { this.setPopupVisible(visible); } }, clearDelayTimer: function clearDelayTimer() { if (this.delayTimer) { clearTimeout(this.delayTimer); this.delayTimer = null; } }, clearOutsideHandler: function clearOutsideHandler() { if (this.clickOutsideHandler) { this.clickOutsideHandler.remove(); this.clickOutsideHandler = null; } if (this.touchOutsideHandler) { this.touchOutsideHandler.remove(); this.touchOutsideHandler = null; } }, createTwoChains: function createTwoChains(event) { var childPros = this.props.children.props; var props = this.props; if (childPros[event] && props[event]) { return this['fire' + event]; } return childPros[event] || props[event]; }, isClickToShow: function isClickToShow() { var _props = this.props, action = _props.action, showAction = _props.showAction; return action.indexOf('click') !== -1 || showAction.indexOf('click') !== -1; }, isClickToHide: function isClickToHide() { var _props2 = this.props, action = _props2.action, hideAction = _props2.hideAction; return action.indexOf('click') !== -1 || hideAction.indexOf('click') !== -1; }, isMouseEnterToShow: function isMouseEnterToShow() { var _props3 = this.props, action = _props3.action, showAction = _props3.showAction; return action.indexOf('hover') !== -1 || showAction.indexOf('mouseEnter') !== -1; }, isMouseLeaveToHide: function isMouseLeaveToHide() { var _props4 = this.props, action = _props4.action, hideAction = _props4.hideAction; return action.indexOf('hover') !== -1 || hideAction.indexOf('mouseLeave') !== -1; }, isFocusToShow: function isFocusToShow() { var _props5 = this.props, action = _props5.action, showAction = _props5.showAction; return action.indexOf('focus') !== -1 || showAction.indexOf('focus') !== -1; }, isBlurToHide: function isBlurToHide() { var _props6 = this.props, action = _props6.action, hideAction = _props6.hideAction; return action.indexOf('focus') !== -1 || hideAction.indexOf('blur') !== -1; }, forcePopupAlign: function forcePopupAlign() { if (this.state.popupVisible && this._component && this._component.alignInstance) { this._component.alignInstance.forceAlign(); } }, fireEvents: function fireEvents(type, e) { var childCallback = this.props.children.props[type]; if (childCallback) { childCallback(e); } var callback = this.props[type]; if (callback) { callback(e); } }, close: function close() { this.setPopupVisible(false); }, render: function render() { var props = this.props; var children = props.children; var child = React.Children.only(children); var newChildProps = {}; if (this.isClickToHide() || this.isClickToShow()) { newChildProps.onClick = this.onClick; newChildProps.onMouseDown = this.onMouseDown; newChildProps.onTouchStart = this.onTouchStart; } else { newChildProps.onClick = this.createTwoChains('onClick'); newChildProps.onMouseDown = this.createTwoChains('onMouseDown'); newChildProps.onTouchStart = this.createTwoChains('onTouchStart'); } if (this.isMouseEnterToShow()) { newChildProps.onMouseEnter = this.onMouseEnter; } else { newChildProps.onMouseEnter = this.createTwoChains('onMouseEnter'); } if (this.isMouseLeaveToHide()) { newChildProps.onMouseLeave = this.onMouseLeave; } else { newChildProps.onMouseLeave = this.createTwoChains('onMouseLeave'); } if (this.isFocusToShow() || this.isBlurToHide()) { newChildProps.onFocus = this.onFocus; newChildProps.onBlur = this.onBlur; } else { newChildProps.onFocus = this.createTwoChains('onFocus'); newChildProps.onBlur = this.createTwoChains('onBlur'); } return React.cloneElement(child, newChildProps); } }); export default Trigger;
client/src/components/FormWiget/KeywordSelect.js
Nonsoft/crdweb
import React from 'react'; import PropTypes from 'prop-types'; import { Form, Select} from 'antd'; const FormItem = Form.Item; const Option = Select.Option; const KeywordSelect = (props) => ( <FormItem label="关键字"> {props.getFieldDecorator('keyword')( <Select style={{width: '100%'}} size="default" allowClear showSearch optionFilterProp="children" filterOption> <Option value="-1">缺省</Option> <Option value="0">全部</Option> {props.keywordSelect.map(data => ( <Option key={data.id} value={data.id.toString()}>{data.keyword}</Option> ))} </Select> )} </FormItem> ) KeywordSelect.propTypes = { keywordSelect: PropTypes.array, getFieldDecorator: PropTypes.func.isRequired, } export default KeywordSelect;
internals/templates/containers/NotFoundPage/index.js
projectcashmere/web-server
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
lib/shared/components/link/index.js
relax/relax
import Component from 'components/component'; import React from 'react'; import PropTypes from 'prop-types'; import {dataConnect} from 'relate-js'; import Link from './link'; @dataConnect( (state) => ({ editing: state.pageBuilder && state.pageBuilder.editing }), (props) => { const {link} = props; let result = {}; if (link && link.options && link.type === 'internal') { const options = link.options; if (options.page) { result = { fragments: { page: { _id: 1, slug: 1 } }, variablesTypes: { page: { _id: 'ID!' } }, initialVariables: { page: { _id: options.page } } }; } } return result; } ) export default class LinkContainer extends Component { static propTypes = { link: PropTypes.object, page: PropTypes.object, editing: PropTypes.bool, relate: PropTypes.object.isRequired }; componentWillReceiveProps (nextProps) { if (this.props.link !== nextProps.link && nextProps.link) { this.props.relate.refresh(nextProps); } } render () { const {link, page, editing, ...props} = this.props; return ( <Link link={link} item={page} editing={editing} {...props} /> ); } }
app/routes/index.js
rclai/redux-blog-example
import React from 'react'; import { Route } from 'react-router'; import App from './App'; import SignupRoute from './SignupRoute'; import LoginRoute from './LoginRoute'; import ProfileRoute from './ProfileRoute'; import NotFound from '../components/NotFound'; import redirectBackAfter from '../utils/redirectBackAfter'; import fillStore from '../utils/fillStore'; import DashboardRoute from './DashboardRoute'; import * as Posts from './Posts'; const routes = ( <Route component={App}> <Route path="/signup" component={SignupRoute} /> <Route path="/login" component={LoginRoute} /> <Route path="/" component={Posts.List} /> <Route path="/posts/:id" component={Posts.View} /> <Route requireAuth> <Route path="/profile" component={ProfileRoute} /> <Route path="/dashboard" component={DashboardRoute} /> <Route path="/dashboard/add" component={Posts.Edit} /> <Route path="/dashboard/edit/:id" component={Posts.Edit} /> </Route> <Route path="*" component={NotFound} /> </Route> ); function walk(routes, cb) { cb(routes); if (routes.childRoutes) { routes.childRoutes.forEach(route => walk(route, cb)); } return routes; } export default (store, client) => { return walk(Route.createRouteFromReactElement(routes), route => { route.onEnter = (nextState, transition) => { const loggedIn = !!store.getState().auth.token; if (route.requireAuth && !loggedIn) { transition.to(...redirectBackAfter('/login', nextState)); } else if (client) { fillStore(store, nextState, [route.component]); } }; }); };
projects/twitch-ui/src/components/GridCell.js
unindented/twitch-x
import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-components' import ImageWithPlaceholder from './ImageWithPlaceholder' import {truncate} from '../utils/css' const GridCellRoot = styled.a` display: block; overflow: hidden; flex: 1; padding: ${props => props.theme.layout.gaps.medium}; color: inherit; text-decoration: none; &:hover { color: ${props => props.theme.colors.highlight}; } ` const GridCellFrame = styled.div` padding: ${props => props.theme.layout.borders.small}; /* stylelint-disable-next-line */ ${GridCellRoot}:hover & { border: ${props => props.theme.layout.borders.medium} solid; margin: -${props => props.theme.layout.borders.medium}; } ` const GridCellName = styled.h3` margin: ${props => props.theme.layout.gaps.small} 0 0; font-size: ${props => props.theme.font.sizes.secondary}; font-weight: normal; ${truncate} ` const GridCellInfo = styled.p` margin: 0; font-size: ${props => props.theme.font.sizes.tertiary}; ${truncate} ` export default function GridCell (props) { const {href, image, name, viewers, channels, width, height, focused} = props return ( <GridCellRoot href={href} > <GridCellFrame focused={focused} > <ImageWithPlaceholder src={image} width={width} height={height} /> </GridCellFrame> <GridCellName> {name} </GridCellName> {viewers && ( <GridCellInfo> {viewers} viewers </GridCellInfo> )} {channels && ( <GridCellInfo> {channels} channels </GridCellInfo> )} </GridCellRoot> ) } GridCell.propTypes = { href: PropTypes.string.isRequired, image: PropTypes.string.isRequired, name: PropTypes.string.isRequired, viewers: PropTypes.number, channels: PropTypes.number, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, focused: PropTypes.bool } GridCell.defaultProps = { focused: false }
src/icons/AndroidPeople.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class AndroidPeople extends React.Component { render() { if(this.props.bare) { return <g> <path d="M337.454,232c33.599,0,61.092-27.002,61.092-60c0-32.997-27.493-60-61.092-60s-61.09,27.003-61.09,60 C276.364,204.998,303.855,232,337.454,232z M174.546,232c33.599,0,61.09-27.002,61.09-60c0-32.997-27.491-60-61.09-60 s-61.092,27.003-61.092,60C113.454,204.998,140.947,232,174.546,232z M174.546,276C126.688,276,32,298.998,32,346v54h288v-54 C320,298.998,222.401,276,174.546,276z M337.454,287.003c-6.105,0-10.325,0-17.454,0.997c23.426,17.002,32,28,32,58v54h128v-54 C480,298.998,385.312,287.003,337.454,287.003z"></path> </g>; } return <IconBase> <path d="M337.454,232c33.599,0,61.092-27.002,61.092-60c0-32.997-27.493-60-61.092-60s-61.09,27.003-61.09,60 C276.364,204.998,303.855,232,337.454,232z M174.546,232c33.599,0,61.09-27.002,61.09-60c0-32.997-27.491-60-61.09-60 s-61.092,27.003-61.092,60C113.454,204.998,140.947,232,174.546,232z M174.546,276C126.688,276,32,298.998,32,346v54h288v-54 C320,298.998,222.401,276,174.546,276z M337.454,287.003c-6.105,0-10.325,0-17.454,0.997c23.426,17.002,32,28,32,58v54h128v-54 C480,298.998,385.312,287.003,337.454,287.003z"></path> </IconBase>; } };AndroidPeople.defaultProps = {bare: false}
src/components/login.js
lizarraldeignacio/personal-website
import React, { Component } from 'react'; import { reduxForm } from 'redux-form'; import { compose } from 'redux'; import { connect } from 'react-redux'; import FieldGroup from './fieldgroup'; import Recaptcha from 'react-recaptcha'; import { verifyReCaptcha } from '../actions/index'; import _ from 'lodash'; import { firebaseConnect, pathToJS } from 'react-redux-firebase'; /** Login component --TODO: Refactoring **/ /** Form Fields **/ const FIELDS = { email: { type: 'email', label: 'Email address', name: "email", placeholder: 'Enter email', inputIconClass: 'glyphicon glyphicon-user' }, password: { type: 'password', label: 'Password', name: "password", placeholder: '', inputIconClass: 'glyphicon glyphicon-lock' } } class Login extends Component { constructor(props) { super(props); this.state = {error : null}; } renderField(fieldConfig) { return ( <FieldGroup type={fieldConfig.type} key={fieldConfig.name} name={fieldConfig.name} label={fieldConfig.label} placeholder={fieldConfig.placeholder} inputIconClass={fieldConfig.inputIconClass} inputClass={"input-field col s4 offset-s4"} /> ); } handleFormSubmit(values) { if (!this.props.login.recaptcha) { this.setState({ error: "Invalid captcha." }); return; } this.props.firebase.login({ email: values.email, password: values.password }) .then((authData) => { this.props.history.push('/'); }).catch((error) => { const searchPattern = new RegExp('^' + 'auth/', 'i'); if (searchPattern.test(error.code)) { this.setState({ error: "User or password is invalid." }); } else { this.setState({ error: "Try again later." }); } }); } renderAlert() { console.log("Devuelvo mensaje"); } render() { return ( <div className="materialize-iso"> <div className="valign-wrapper"> <div className="container"> <form onSubmit={this.props.handleSubmit(this.handleFormSubmit.bind(this))}> {_.map(FIELDS, (this.renderField.bind(this)))} <div className="row"> <div className="col s4 offset-s4"> {this.state.error && <div className="red-text"> <strong>Oops!</strong> { this.state.error } </div> } <Recaptcha render="explicit" onloadCallback={() => {}} sitekey="6LeffSMUAAAAAFxpA7nvHyhRMrr3iKvBoAyolC7u" verifyCallback={recaptchaCallback.bind(this)} /> <br/> </div> </div> <div className="row"> <div className="center-btn"> {!this.props.auth && <button className="waves-effect waves-light btn blue darken-1" type="submit" name="action" disabled={!this.props.login.recaptcha}> Login </button>} </div> </div> </form> </div> </div> </div> ); } } function recaptchaCallback(response) { this.props.verifyReCaptcha(response); } function mapStateToProps(state) { return { login: state.login, auth: pathToJS(state.firebase, 'auth') }; } /** Validiation function, it validates each field on the form **/ function validate(values) { const errors = {}; _.each(FIELDS, (type, field) => { if (!values[field]) { errors[field] = `Please Enter a ${type['label']}`; } }); return errors; } /** Redux form decorator params: form: The name of the form fields: The fields of the form validate: the validation function **/ export default compose( connect(mapStateToProps, { verifyReCaptcha }), firebaseConnect(), reduxForm({ validate, form: 'LoginForm' }))(Login);
src/plugins/position/components/SpacerRow.js
GriddleGriddle/Griddle
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from '../../../utils/griddleConnect'; import compose from 'recompose/compose'; import mapProps from 'recompose/mapProps'; import getContext from 'recompose/getContext'; import withHandlers from 'recompose/withHandlers'; const spacerRow = compose( getContext({ selectors: PropTypes.object, }), connect((state, props) => { const { topSpacerSelector, bottomSpacerSelector } = props.selectors; const { placement } = props; return { spacerHeight: placement === 'top' ? topSpacerSelector(state, props) : bottomSpacerSelector(state, props), }; }), mapProps(props => ({ placement: props.placement, spacerHeight: props.spacerHeight, })) )(class extends Component { static propTypes = { placement: PropTypes.string, spacerHeight: PropTypes.number, } static defaultProps = { placement: 'top' } // shouldComponentUpdate(nextProps) { // const { currentPosition: oldPosition, placement: oldPlacement } = this.props; // const { currentPosition, placement } = nextProps; // // return oldPosition !== currentPosition || oldPlacement !== placement; // } render() { const { placement, spacerHeight } = this.props; let spacerRowStyle = { height: `${spacerHeight}px`, }; return ( <tr key={placement + '-' + spacerHeight} style={spacerRowStyle}></tr> ); } }); export default spacerRow;
app/javascript/mastodon/features/account_gallery/index.js
dunn/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { fetchAccount } from 'mastodon/actions/accounts'; import { expandAccountMediaTimeline } from '../../actions/timelines'; import LoadingIndicator from 'mastodon/components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButton from 'mastodon/components/column_back_button'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { getAccountGallery } from 'mastodon/selectors'; import MediaItem from './components/media_item'; import HeaderContainer from '../account_timeline/containers/header_container'; import { ScrollContainer } from 'react-router-scroll-4'; import LoadMore from 'mastodon/components/load_more'; import MissingIndicator from 'mastodon/components/missing_indicator'; import { openModal } from 'mastodon/actions/modal'; const mapStateToProps = (state, props) => ({ isAccount: !!state.getIn(['accounts', props.params.accountId]), attachments: getAccountGallery(state, props.params.accountId), isLoading: state.getIn(['timelines', `account:${props.params.accountId}:media`, 'isLoading']), hasMore: state.getIn(['timelines', `account:${props.params.accountId}:media`, 'hasMore']), }); class LoadMoreMedia extends ImmutablePureComponent { static propTypes = { shouldUpdateScroll: PropTypes.func, maxId: PropTypes.string, onLoadMore: PropTypes.func.isRequired, }; handleLoadMore = () => { this.props.onLoadMore(this.props.maxId); } render () { return ( <LoadMore disabled={this.props.disabled} onClick={this.handleLoadMore} /> ); } } export default @connect(mapStateToProps) class AccountGallery extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, attachments: ImmutablePropTypes.list.isRequired, isLoading: PropTypes.bool, hasMore: PropTypes.bool, isAccount: PropTypes.bool, multiColumn: PropTypes.bool, }; state = { width: 323, }; componentDidMount () { this.props.dispatch(fetchAccount(this.props.params.accountId)); this.props.dispatch(expandAccountMediaTimeline(this.props.params.accountId)); } componentWillReceiveProps (nextProps) { if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) { this.props.dispatch(fetchAccount(nextProps.params.accountId)); this.props.dispatch(expandAccountMediaTimeline(this.props.params.accountId)); } } handleScrollToBottom = () => { if (this.props.hasMore) { this.handleLoadMore(this.props.attachments.size > 0 ? this.props.attachments.last().getIn(['status', 'id']) : undefined); } } handleScroll = e => { const { scrollTop, scrollHeight, clientHeight } = e.target; const offset = scrollHeight - scrollTop - clientHeight; if (150 > offset && !this.props.isLoading) { this.handleScrollToBottom(); } } handleLoadMore = maxId => { this.props.dispatch(expandAccountMediaTimeline(this.props.params.accountId, { maxId })); }; handleLoadOlder = e => { e.preventDefault(); this.handleScrollToBottom(); } handleOpenMedia = attachment => { if (attachment.get('type') === 'video') { this.props.dispatch(openModal('VIDEO', { media: attachment, status: attachment.get('status') })); } else if (attachment.get('type') === 'audio') { this.props.dispatch(openModal('AUDIO', { media: attachment, status: attachment.get('status') })); } else { const media = attachment.getIn(['status', 'media_attachments']); const index = media.findIndex(x => x.get('id') === attachment.get('id')); this.props.dispatch(openModal('MEDIA', { media, index, status: attachment.get('status') })); } } handleRef = c => { if (c) { this.setState({ width: c.offsetWidth }); } } render () { const { attachments, shouldUpdateScroll, isLoading, hasMore, isAccount, multiColumn } = this.props; const { width } = this.state; if (!isAccount) { return ( <Column> <MissingIndicator /> </Column> ); } if (!attachments && isLoading) { return ( <Column> <LoadingIndicator /> </Column> ); } let loadOlder = null; if (hasMore && !(isLoading && attachments.size === 0)) { loadOlder = <LoadMore visible={!isLoading} onClick={this.handleLoadOlder} />; } return ( <Column> <ColumnBackButton multiColumn={multiColumn} /> <ScrollContainer scrollKey='account_gallery' shouldUpdateScroll={shouldUpdateScroll}> <div className='scrollable scrollable--flex' onScroll={this.handleScroll}> <HeaderContainer accountId={this.props.params.accountId} /> <div role='feed' className='account-gallery__container' ref={this.handleRef}> {attachments.map((attachment, index) => attachment === null ? ( <LoadMoreMedia key={'more:' + attachments.getIn(index + 1, 'id')} maxId={index > 0 ? attachments.getIn(index - 1, 'id') : null} onLoadMore={this.handleLoadMore} /> ) : ( <MediaItem key={attachment.get('id')} attachment={attachment} displayWidth={width} onOpenMedia={this.handleOpenMedia} /> ))} {loadOlder} </div> {isLoading && attachments.size === 0 && ( <div className='scrollable__append'> <LoadingIndicator /> </div> )} </div> </ScrollContainer> </Column> ); } }
src/components/PlayerControls.js
jeremyfry/init-tracker
import React from 'react'; import PropTypes from 'prop-types'; const setColor = (color, led) => () => fetch(`/led/${led}/${color}`); const PlayerControls = (props) =>{ return ( <div className="player-card__controls"> <button onClick={setColor('255/0/0', props.player.ledPosition)} className="player-card__red"></button> <button onClick={setColor('0/0/255', props.player.ledPosition)} className="player-card__blue"></button> <button onClick={setColor('0/255/0', props.player.ledPosition)} className="player-card__green"></button> </div> ); }; PlayerControls.propTypes = { player: PropTypes.object.isRequired }; export default PlayerControls;
src/index.js
zacfukuda/universal-app-react-router
import React from 'react' import { render } from 'react-dom' import { BrowserRouter } from 'react-router-dom' import App from './App' import './index.css' render(( <BrowserRouter> <App /> </BrowserRouter> ), document.getElementById('root'))
codes/chapter05/react-router-v4/basic/demo04/app/components/About.js
atlantis1024/react-step-by-step
import React from 'react'; class About extends React.PureComponent { render() { return <h2>关于</h2> } } export default About;
src/charts/Scatterplot.js
rsamec/react-pathjs-chart
import React from 'react'; import _ from 'lodash'; import Options from '../component/Options.js'; import fontAdapt from '../fontAdapter.js'; import styleSvg from '../styleSvg'; var Stock = require('paths-js/stock'); var Axis = require('../component/Axis'); var Path = require('paths-js/path'); export default class Scatterplot extends React.Component { constructor(props) { super(props); this.state = {finished:true}; } getMaxAndMin(chart, key,scale) { var maxValue; var minValue; _.each(chart.curves, function (serie) { var values = _.map(serie.item, function (item) { return item[key] }); var max = _.max(values); if (maxValue === undefined || max > maxValue) maxValue = max; var min = _.min(values); if (minValue === undefined || min < minValue) minValue = min; }); return { minValue: minValue, maxValue: maxValue, min:scale(minValue), max:scale(maxValue) } } onEnter(index,event) { this.props.data[0][index].selected = true; this.setState({data: this.props.data}); } onLeave(index,event){ this.props.data[0][index].selected = false; this.setState({data:this.props.data}); } render() { var noDataMsg = this.props.noDataMessage || "No data available"; if (this.props.data === undefined) return (<span>{noDataMsg}</span>); var options = new Options(this.props); var palette = this.props.palette || ["#3E90F0", "#7881C2", "#707B82"]; var accessor = function (key) { return function (x) { return x[key]; } }; var chart = Stock({ data: this.props.data, xaccessor: accessor(this.props.xKey), yaccessor: accessor(this.props.yKey), width: options.chartWidth, height: options.chartHeight, closed: false }); var chartArea = { x:this.getMaxAndMin(chart,this.props.xKey,chart.xscale), y:this.getMaxAndMin(chart,this.props.yKey,chart.yscale), margin:options.margin }; var sec = options.animate.fillTransition || 0; var fillOpacityStyle = {fillOpacity:this.state.finished?1:0,transition: this.state.finished?'fill-opacity ' + sec + 's':''}; var textStyle = fontAdapt(options.label); var colors = styleSvg({},options); var points = _.map(chart.curves, function (c, i) { return _.map(c.line.path.points(),function(p,j) { var item = c.item[j]; return (<g key={'k' + j} transform={"translate(" + p[0] + "," + p[1] + ")"}> <circle {...colors} cx={0} cy={0} r={options.r || 5} style={fillOpacityStyle} onMouseEnter={this.onEnter.bind(this,j)} onMouseLeave={this.onLeave.bind(this,j)}/> {item.selected?<text style={textStyle} transform="translate(15, 5)" text-anchor="start">{item.title}</text>:null} </g>) },this) },this); return (<svg ref="vivus" width={options.width} height={options.height}> <g transform={"translate(" + options.margin.left + "," + options.margin.top + ")"}> { points } <Axis scale ={chart.xscale} options={options.axisX} chartArea={chartArea} /> <Axis scale ={chart.yscale} options={options.axisY} chartArea={chartArea} /> </g> </svg>); } } Scatterplot.defaultProps= { xKey:'', yKey:'', options: { width: 600, height: 600, margin: {top: 40, left: 60, bottom: 30, right: 30}, fill: "#2980B9", stroke: "#3E90F0", animate: { type: 'delayed', duration: 200, fillTransition:3 }, label: { fontFamily: 'Arial', fontSize: 14, bold: true, color: '#34495E' }, axisX: { showAxis: true, showLines: true, showLabels: true, showTicks: true, zeroAxis: false, orient: 'bottom', label: { fontFamily: 'Arial', fontSize: 14, bold: true, color: '#34495E' } }, axisY: { showAxis: true, showLines: true, showLabels: true, showTicks: true, zeroAxis: false, orient: 'left', label: { fontFamily: 'Arial', fontSize: 14, bold: true, color: '#34495E' } } } }
src/server.js
ThatCheck/AutoLib
import Express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import config from './config'; import favicon from 'serve-favicon'; import compression from 'compression'; import httpProxy from 'http-proxy'; import path from 'path'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import Html from './helpers/Html'; import PrettyError from 'pretty-error'; import http from 'http'; import SocketIo from 'socket.io'; import cookie from 'react-cookie';import {IntlProvider} from 'react-intl'; import { intlDataHash, getCurrentLocale } from './utils/intl'; import {ReduxRouter} from 'redux-router'; import createHistory from 'history/lib/createMemoryHistory'; import {reduxReactRouter, match} from 'redux-router/server'; import {Provider} from 'react-redux'; import qs from 'query-string'; import getRoutes from './routes'; import getStatusFromRoutes from './helpers/getStatusFromRoutes'; import BodyClassName from 'react-body-classname'; /** * Flatten the message locales * @param ob * @returns {*} */ function flattenMessages(ob) { const toReturn = {}; for (let i in ob) { if (!ob.hasOwnProperty(i)) continue; if (typeof ob[i] === 'object') { const flatObject = flattenMessages(ob[i]); for (let x in flatObject) { if (!flatObject.hasOwnProperty(x)) continue; toReturn[i + '.' + x] = flatObject[x]; } } else { toReturn[i] = ob[i]; } } return toReturn; } const pretty = new PrettyError(); const app = new Express(); const server = new http.Server(app); const proxy = httpProxy.createProxyServer({ target: 'http://' + config.apiHost + ':' + config.apiPort, ws: true }); var areIntlLocalesSupported = require('intl-locales-supported'); var localesMyAppSupports = config.locales; if (global.Intl) { // Determine if the built-in `Intl` has the locale data we need. if (!areIntlLocalesSupported(localesMyAppSupports)) { // `Intl` exists, but it doesn't have the data we need, so load the // polyfill and replace the constructors with need with the polyfill's. require('intl'); Intl.NumberFormat = IntlPolyfill.NumberFormat; Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat; } } else { // No `Intl`, so use and load the polyfill. global.Intl = require('intl'); } app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.use(Express.static(path.join(__dirname, '..', 'static'))); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res); }); // added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 proxy.on('error', (error, req, res) => { let json; if (error.code !== 'ECONNRESET') { console.error('proxy error', error); } if (!res.headersSent) { res.writeHead(500, {'content-type': 'application/json'}); } json = {error: 'proxy_error', reason: error.message}; res.end(JSON.stringify(json)); }); app.use((req, res) => { cookie.plugToRequest(req, res); if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } BodyClassName.rewind(); const lang = cookie.load('locale') || 'fr'; const localeFromRoute = getCurrentLocale(lang); const locale = intlDataHash[localeFromRoute].locale; const localeFileName = intlDataHash[localeFromRoute].file; const localeMessages = flattenMessages(require(`./intl/${localeFromRoute}`)); const localeData = require(`react-intl/dist/locale-data/${localeFileName}`); const client = new ApiClient(req); const store = createStore(reduxReactRouter, getRoutes, createHistory, client); function hydrateOnClient() { res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html locale={locale} localeData={localeData} localeMessages={localeMessages} assets={webpackIsomorphicTools.assets()} store={store}/>)); } if (__DISABLE_SSR__) { hydrateOnClient(); return; } store.dispatch(match(req.originalUrl, (error, redirectLocation, routerState) => { if (redirectLocation) { res.redirect(redirectLocation.pathname + redirectLocation.search); } else if (error) { console.error('ROUTER ERROR:', pretty.render(error)); res.status(500); hydrateOnClient(); } else if (!routerState) { res.status(500); hydrateOnClient(); } else { // Workaround redux-router query string issue: // https://github.com/rackt/redux-router/issues/106 if (routerState.location.search && !routerState.location.query) { routerState.location.query = qs.parse(routerState.location.search); } store.getState().router.then(() => { const component = ( <Provider store={store} key="provider"> <IntlProvider locale={locale} messages={localeMessages}> <ReduxRouter/> </IntlProvider> </Provider> ); const status = getStatusFromRoutes(routerState.routes); if (status) { res.status(status); } res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html locale={locale} localeData={localeData} localeMessages={localeMessages} assets={webpackIsomorphicTools.assets()} component={component} store={store}/>)); }).catch((err) => { console.error('DATA FETCHING ERROR:', pretty.render(err)); res.status(500); hydrateOnClient(); }); } })); }); if (config.port) { if (config.isProduction) { const io = new SocketIo(server); io.path('/api/ws'); } server.listen(config.port, (err) => { if (err) { console.error(err); } console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.title, config.apiPort); console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
src/components/common/svg-icons/notification/sim-card-alert.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSimCardAlert = (props) => ( <SvgIcon {...props}> <path d="M18 2h-8L4.02 8 4 20c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-5 15h-2v-2h2v2zm0-4h-2V8h2v5z"/> </SvgIcon> ); NotificationSimCardAlert = pure(NotificationSimCardAlert); NotificationSimCardAlert.displayName = 'NotificationSimCardAlert'; NotificationSimCardAlert.muiName = 'SvgIcon'; export default NotificationSimCardAlert;
plugins/react/frontend/components/form/RandomButton/index.js
pure-ui/styleguide
import React from 'react'; import Button from '../Button'; import styles from './styles.css'; const RandomButton = ({ groupType = 'right', ...otherProps }) => ( <Button {...otherProps} groupType={groupType}> <svg className={styles.svg} width="16px" height="13px" viewBox="0 0 16 13" version="1.1" > <g stroke="none" strokeWidth="1" fill="none" fill-rule="evenodd"> <g transform="translate(1.000000, 0.000000)"> <path d="M10.9831425,0.248038552 L10.9831425,5.66105236 L15.0588235,2.95454545 L10.9831425,0.248038552 Z" // eslint-disable-line max-len fill="#999999" /> <path d="M10.9831425,7.33894764 L10.9831425,12.7519614 L15.0588235,10.0454545 L10.9831425,7.33894764 Z" // eslint-disable-line max-len fill="#999999" /> <path d="M0.739722594,10.0454545 L3.48285708,10.0454545 C4.03747416,10.0454545 4.72728114,9.66421648 5.01712405,9.20418863 L8.42469998,3.79581137 C8.71743515,3.33119303 9.40462323,2.95454545 9.95374013,2.95454545 L11.6791444,2.95454545" // eslint-disable-line max-len stroke="#979797" strokeWidth="2" strokeLinecap="square" /> <path d="M0.739722594,10.0454545 L3.48285708,10.0454545 C4.03747416,10.0454545 4.72728114,9.66421648 5.01712405,9.20418863 L8.42469998,3.79581137 C8.71743515,3.33119303 9.40462323,2.95454545 9.95374013,2.95454545 L11.6791444,2.95454545" // eslint-disable-line max-len stroke="#979797" strokeWidth="2" strokeLinecap="square" transform="translate(6.209433, 6.500000) scale(1, -1) translate(-6.209433, -6.500000) " /> </g> </g> </svg> </Button> ); export default RandomButton;
client/js/components/profile.js
D3VBAS3/DevBase
import React, { Component } from 'react'; import { connect } from 'react-redux'; import logout from './../actions/logout'; import { browserHistory } from 'react-router'; import DbTable from './db-table'; import StepBox from './stepBox'; import fetch from 'isomorphic-fetch'; class Profile extends Component { constructor() { super(); this.handleLogOut = this.handleLogOut.bind(this); this.state = { profile_token: '', profile_username: '' } } componentDidMount() { if (localStorage.getItem('devBase_user_token') === null) { browserHistory.push('/'); } else { this.setState({ profile_token: localStorage.getItem('devBase_user_token'), profile_username: localStorage.getItem('devBase_username') }); } } handleLogOut() { this.props.dispatch(logout()); } handleReset() { // fetch post request to drop table // fetch('/login',{ // method: 'post', // headers: { // 'Content-Type': 'application/json' // }, // body: JSON.stringify(userData) // }) // .then((response) => { // if (response.status !== 200) { // console.log('ERRROORRR not 200'); // throw new Error(response.statusText); // } // return response.json(); // }) // .then((data) => { // dispatch(loginSuccess(data.token, data.username)); // browserHistory.push('/profile'); // }) } render() { return ( <div> <div> <button onClick={this.handleLogOut}>LOG OUT</button> </div> <DbTable /> <StepBox username={this.state.profile_username} token={this.state.profile_token}/> <button onClick={this.handleReset}>Reset</button> </div> ) } } export default connect()(Profile);
server/sonar-web/src/main/js/apps/account/projects/propTypes.js
Builders-SonarSource/sonarqube-bis
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; const { shape, string, array, arrayOf } = React.PropTypes; export const projectType = shape({ id: string.isRequired, key: string.isRequired, name: string.isRequired, lastAnalysisDate: string, description: string, links: array.isRequired, qualityGate: string }); export const projectsListType = arrayOf(projectType);
packages/icons/src/md/action/HourglassEmpty.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdHourglassEmpty(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M12 5h24v10l-9 9 9 9v10H12V33l9-9-9-9V5zm20 29l-8-8-8 8v5h16v-5zm-8-12l8-8V9H16v5l8 8z" /> </IconBase> ); } export default MdHourglassEmpty;
node_modules/@material-ui/core/esm/DialogActions/DialogActions.js
pcclarke/civ-techs
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import '../Button'; // So we don't have any override priority issue. export var styles = { /* Styles applied to the root element. */ root: { display: 'flex', alignItems: 'center', padding: 8, justifyContent: 'flex-end' }, /* Styles applied to the root element if `disableSpacing={false}`. */ spacing: { '& > * + *': { marginLeft: 8 } } }; var DialogActions = React.forwardRef(function DialogActions(props, ref) { var _props$disableSpacing = props.disableSpacing, disableSpacing = _props$disableSpacing === void 0 ? false : _props$disableSpacing, classes = props.classes, className = props.className, other = _objectWithoutProperties(props, ["disableSpacing", "classes", "className"]); return React.createElement("div", _extends({ className: clsx(classes.root, !disableSpacing && classes.spacing, className), ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? DialogActions.propTypes = { /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * If `true`, the actions do not have additional margin. */ disableSpacing: PropTypes.bool } : void 0; export default withStyles(styles, { name: 'MuiDialogActions' })(DialogActions);
packages/reactor-modern-boilerplate/src/index.js
dbuhrman/extjs-reactor
import React from 'react' import ReactDOM from 'react-dom' import { AppContainer } from 'react-hot-loader' import { launch } from '@extjs/reactor'; import App from './App' let viewport; const render = (Component, target) => { ReactDOM.render( <AppContainer> <Component/> </AppContainer>, target ) } launch(target => render(App, viewport = target)); if (module.hot) { module.hot.accept('./App', () => render(App, viewport)); }
react/mortgage/src/components/TableMortgage.js
webmaster444/webmaster444.github.io
import React from 'react'; import { connect } from 'react-redux'; import payments from '../selectors/payments'; import Table from './Table'; export const TableMortgage = (({payments, className})=> { let output=payments.slice(1) .filter(year=>year.balance>0 || year.interestYearly>0) .reduce((acc, year, index) => { return { interestTotal:acc.interestTotal+year.interestYearly, overpaymentTotal:acc.overpaymentTotal+year.overpayment, rows:acc.rows.concat([ [year.partial?year.partial + "m":index+1, Math.round(year.interestYearly||0), Math.round(year.overpayment), Math.round(year.balance)]]) } }, {interestTotal:0, overpaymentTotal:0, rows:[]}); return <Table className={className} headings={["Years", "Interest", "Overpayment", "Balance"]} rows={output.rows} totals={[" ",Math.round(output.interestTotal), Math.round(output.overpaymentTotal)," "]} />; }); export default connect(state=>({ ...payments(state) }))(TableMortgage)
src/components/Menu/MenuList.js
sk-iv/iva-app
import React from 'react'; import PropTypes from 'prop-types'; import { findDOMNode } from 'react-dom'; import keycode from 'keycode'; import contains from 'dom-helpers/query/contains'; import activeElement from 'dom-helpers/activeElement'; import ownerDocument from 'dom-helpers/ownerDocument'; import List from '../List'; class MenuList extends React.Component { state = { currentTabIndex: undefined, }; componentDidMount() { this.resetTabIndex(); } componentWillUnmount() { clearTimeout(this.blurTimer); } setTabIndex(index: number) { this.setState({ currentTabIndex: index }); } list = undefined; selectedItem = undefined; blurTimer = undefined; handleBlur = (event: SyntheticUIEvent<>) => { this.blurTimer = setTimeout(() => { if (this.list) { const list = findDOMNode(this.list); const currentFocus = activeElement(ownerDocument(list)); if (!contains(list, currentFocus)) { this.resetTabIndex(); } } }, 30); if (this.props.onBlur) { this.props.onBlur(event); } }; handleKeyDown = (event: SyntheticUIEvent<>) => { const list = findDOMNode(this.list); const key = keycode(event); const currentFocus = activeElement(ownerDocument(list)); if ( (key === 'up' || key === 'down') && (!currentFocus || (currentFocus && !contains(list, currentFocus))) ) { if (this.selectedItem) { findDOMNode(this.selectedItem).focus(); } else { list.firstChild.focus(); } } else if (key === 'down') { event.preventDefault(); if (currentFocus.nextElementSibling) { currentFocus.nextElementSibling.focus(); } } else if (key === 'up') { event.preventDefault(); if (currentFocus.previousElementSibling) { currentFocus.previousElementSibling.focus(); } } if (this.props.onKeyDown) { this.props.onKeyDown(event, key); } }; handleItemFocus = (event: SyntheticUIEvent<>) => { const list = findDOMNode(this.list); if (list) { for (let i = 0; i < list.children.length; i += 1) { if (list.children[i] === event.currentTarget) { this.setTabIndex(i); break; } } } }; focus() { const { currentTabIndex } = this.state; const list = findDOMNode(this.list); if (!list || !list.children || !list.firstChild) { return; } if (currentTabIndex && currentTabIndex >= 0) { list.children[currentTabIndex].focus(); } else { list.firstChild.focus(); } } resetTabIndex() { const list = findDOMNode(this.list); const currentFocus = activeElement(ownerDocument(list)); const items = [...list.children]; const currentFocusIndex = items.indexOf(currentFocus); if (currentFocusIndex !== -1) { return this.setTabIndex(currentFocusIndex); } if (this.selectedItem) { return this.setTabIndex(items.indexOf(findDOMNode(this.selectedItem))); } return this.setTabIndex(0); } render() { const { children, className, onBlur, onKeyDown, ...other } = this.props; return ( <List data-mui-test="MenuList" role="menu" rootRef={node => { this.list = node; }} className={className} onKeyDown={this.handleKeyDown} onBlur={this.handleBlur} {...other} > {React.Children.map(children, (child, index) => { if (!React.isValidElement(child)) { return null; } return React.cloneElement(child, { tabIndex: index === this.state.currentTabIndex ? 0 : -1, ref: child.props.selected ? node => { this.selectedItem = node; } : undefined, onFocus: this.handleItemFocus, }); })} </List> ); } } MenuList.propTypes = { /** * MenuList contents, normally `MenuItem`s. */ children: PropTypes.node, /** * @ignore */ className: PropTypes.string, /** * @ignore */ onBlur: PropTypes.func, /** * @ignore */ onKeyDown: PropTypes.func, }; export default MenuList;
ext/lib/admin/admin-topics-form/view.js
RosarioCiudad/democracyos
import React from 'react' import { render as ReactRender } from 'react-dom' import closest from 'component-closest' import confirm from 'democracyos-confirmation' import Datepicker from 'democracyos-datepicker' import debug from 'debug' import o from 'component-dom' import t from 't-component' import page from 'page' import moment from 'moment' import tagsInput from 'tags-input' import { dom as render } from 'lib/render/render' import Richtext from 'lib/richtext/richtext' import urlBuilder from 'lib/url-builder' import FormView from 'lib/form-view/form-view' import topicStore from 'lib/stores/topic-store/topic-store' import * as serializer from './body-serializer' import ForumTagsSearch from 'lib/admin/admin-topics-form/tag-autocomplete/component' import linkTemplate from './link.jade' import Attrs from './attrs/component' import template from './template.jade' import templateIdeas from './template-ideas.jade' import user from 'lib/user/user.js' const log = debug('democracyos:admin-topics-form') /** * Creates a password edit view */ let created = false export default class TopicForm extends FormView { constructor (topic, forum, tags) { const locals = { form: { title: null, action: null, method: null, type: null }, topic: topic || { clauses: [] }, tags: tags, moment: moment, forum, urlBuilder } if (topic) { locals.form.type = 'edit' locals.form.action = '/api/v2/topics/' + topic.id locals.form.title = 'admin-topics-form.title.edit' locals.form.method = 'put' topic.body = serializer.toHTML(topic.clauses) .replace(/<a/g, '<a rel="noopener noreferer" target="_blank"') } else { locals.form.type = 'create' locals.form.action = '/api/v2/topics' locals.form.title = 'admin-topics-form.title.create' locals.form.method = 'post' locals.form.forum = forum.id } if (forum.name === 'ideas') { super(templateIdeas, locals) } else { super(template, locals) } this.topic = topic this.tags = tags this.forum = forum this.forumAdminUrl = ':forum/admin'.replace(':forum', forum ? `/${forum.name}` : '') if (tags.length === 0) return this.renderDateTimePickers() if (created) { this.messages([t('admin-topics-form.message.onsuccess')]) created = false } this.pubButton = this.find('a.make-public') this.privButton = this.find('a.make-private') var body = this.find('textarea[name=body]') this.richtext = new Richtext(body) } /** * Turn on event bindings */ switchOn () { this.bind('click', '.add-link', this.bound('onaddlinkclick')) this.bind('click', '.forum-tag', this.bound('onaddforumtagclick')) this.bind('click', '[data-remove-link]', this.bound('onremovelinkclick')) this.bind('click', '.save', this.bound('onsaveclick')) this.bind('click', '.auto-save', this.bound('onsaveclick')) this.bind('click', '.make-public', this.bound('onmakepublicclick')) this.bind('click', '.make-private', this.bound('onmakeprivateclick')) this.bind('click', '.delete-topic', this.bound('ondeletetopicclick')) this.bind('click', '.archivar', this.bound('onclosetopicclick')) this.bind('click', '.abrir', this.bound('onopentopicclick')) this.bind('click', '[data-clear-closing-at]', this.bound('onclearclosingat')) this.bind('change', '.method-input', this.bound('onmethodchange')) this.on('success', this.onsuccess) const actionMethod = this.topic && this.topic.action ? this.topic.action.method : '' const pollOptions = this.find('.poll-options') this.find('.method-input option').forEach(function (option) { if (option.value === actionMethod) option.selected = true }) if (actionMethod === 'poll') pollOptions.removeClass('hide') const tags = this.el[0].querySelectorAll('input[type="tags"]') Array.prototype.forEach.call(tags, tagsInput) if (this.forum.name !== 'presupuesto') { ReactRender(( <ForumTagsSearch tags={this.topic && this.topic.tags && this.topic.tags} initialTags={this.forum.initialTags} forum={this.forum.id} /> ), this.el[0].querySelector('.tags-autocomplete')) } if (this.forum.topicsAttrs.length > 0) { const attrsWrapper = this.el[0].querySelector('[data-attrs]') ReactRender( <Attrs forum={this.forum} topic={this.topic} />, attrsWrapper ) } } /** * Handle `error` event with * logging and display * * @param {String} error * @api private */ onsuccess (res) { log('Topic successfully saved') topicStore.parse(res.body.results.topic) .then((topic) => { if (this.topic) topicStore.unset(this.topic.id) topicStore.set(topic.id, topic) if (!this.forum.privileges.canChangeTopics) { return page(urlBuilder.for('site.topic', { forum: this.forum.name, id: topic.id })) } this.topic = topic created = true document.querySelector('#content').scrollTop = 0 // Forcefully re-render the form page(urlBuilder.for('admin.topics.id', { forum: this.forum.name, id: this.topic.id })) }) .catch((err) => { throw err }) } /** * Renders datepicker and timepicker * elements inside view's `el` * * @return {TopicForm|Element} * @api public */ renderDateTimePickers () { if (this.forum.name !== 'presupuesto') { this.closingAt = this.find('[name=closingAt]', this.el) this.closingAtTime = this.find('[name=closingAtTime]') this.dp = new Datepicker(this.closingAt[0]) return this } } onaddlinkclick (evt) { evt.preventDefault() return this.addLink() } addLink () { const links = o('.topic-links', this.el) const link = render(linkTemplate, { link: {} }) links.append(o(link)) } onremovelinkclick (evt) { const btn = evt.target const link = closest(btn, '[data-link]') link.parentNode.removeChild(link) } onsaveclick (ev) { ev.preventDefault() if (this.dp && this.dp.popover) { this.dp.popover.hide() } if (this.find('.method-input')[0].value === 'poll' && this.find('.poll-options > input')[0].value === '') { this.messages(t('admin-topics-form.message.validation.pollOptions-required'), 'error') return } this.find('form input[type=submit]')[0].click() } postserialize (data = {}) { if (data['links[][text]']) { data.links = data['links[][text]'].map((text, i) => ({ _id: data['links[][_id]'][i] || undefined, url: data['links[][url]'][i], text })) delete data['links[][_id]'] delete data['links[][text]'] delete data['links[][url]'] } if (data.closingAt && data.closingAtTime) { data.closingAt = new Date(`${data.closingAt} ${data.closingAtTime}`) delete data.closingAtTime } /* console.log(data.body)*/ data.clauses = serializer.toArray(data.body) /* console.log(data.clauses)*/ delete data.body if (data['action.options']) { data['action.options'] = data['action.options'].split(',') } if (data.tags) { data.tags = data.tags.split(',') } else { data.tags = [] } return data } onmakepublicclick (ev) { ev.preventDefault() var view = this this.pubButton.addClass('disabled') topicStore.publish(this.topic.id) .then(() => { view.pubButton.removeClass('disabled').addClass('hide') view.privButton.removeClass('hide') }) .catch((err) => { console.log(err) view.pubButton.removeClass('disabled') log('Found error %o', err) }) } onmakeprivateclick (ev) { ev.preventDefault() var view = this this.privButton.addClass('disabled') var id = this.topic.id topicStore.unpublish(id) .then(() => { view.privButton.removeClass('disabled') view.privButton.addClass('hide') view.pubButton.removeClass('hide') }) .catch((err) => { view.pubButton.removeClass('disabled') log('Found error %o', err) }) } ondeletetopicclick (ev) { ev.preventDefault() const _t = (s) => t(`admin-topics-form.delete-topic.confirmation.${s}`) const onconfirmdelete = (ok) => { if (!ok) return topicStore.destroy(this.topic.id) .then(() => { if (this.forum.visibility === 'collaborative') { page(urlBuilder.for('site.forum', { forum: this.forum.name })) } else { page(urlBuilder.for('admin', { forum: this.forum.name })) } }) .catch((err) => { log('Found error %o', err) }) } confirm(_t('title'), _t('body')) .cancel(_t('cancel')) .ok(_t('ok')) .modal() .closable() .effect('slide') .show(onconfirmdelete) } onclearclosingat (ev) { ev.preventDefault() this.closingAt.value('') if (this.dp && this.dp.popover) { this.dp.popover.hide() this.dp = new Datepicker(this.closingAt[0]) } } onmethodchange (e) { const action = e.target.value === 'poll' ? 'removeClass' : 'addClass' this.find('.poll-options')[action]('hide') } onclosetopicclick = (e) => { window.fetch(`/ext/api/${this.forum.name}/${this.topic.id}/status`, { method: 'DELETE', credentials: 'include' }) .then((res) => res.json()) .then((res) => { if (res.status === 200) { window.location.reload() } }) } onopentopicclick = (e) => { window.fetch(`/ext/api/${this.forum.name}/${this.topic.id}/status`, { method: 'POST', credentials: 'include' }) .then((res) => res.json()) .then((res) => { if (res.status === 200) { window.location.reload() } }) } onaddforumtagclick (e) { if (this.find('input[name="tags"]')[0].value.length === 0) { this.find('input[name="tags"]')[0].value = `${e.target.dataset.value}` } else if (!~this.find('input[name="tags"]')[0].value.indexOf(e.target.dataset.value)) { this.find('input[name="tags"]')[0].value += `,${e.target.dataset.value}` } else { return } let span = document.createElement('span') span.setAttribute('data-tag', e.target.dataset.value) span.textContent = e.target.dataset.value span.className = 'tag' this.find('.tags-autocomplete .tags-input').prepend(span) } }
src/js/Main/components/UseCases.js
fr3nchN/proactive
import React from 'react' import links from "./../links" import ContentUseCases from "./../../../content/community/ContentUseCases" const UseCaseCard = ({ useCaseItem }) => { return ( <div className="card"> <img className="card-img-top" src={useCaseItem.image} alt={useCaseItem.name} /> <div className="card-body text-center"> <h4 className="card-title">{useCaseItem.name}</h4> <p className="card-text text-muted">{useCaseItem.description}</p> <a href={useCaseItem.link} className="btn btn-outline-secondary" target="_blank">Download</a> </div> </div> ) }; const UseCases = () => { return ( <div> <div className="row justify-content-md-center"> <div className="col-md-8 text-center"> <h2>Use Cases</h2> <hr /> </div> </div> <div className="card-deck"> { ContentUseCases.map((useCaseItem) => ( <UseCaseCard key={useCaseItem.key} useCaseItem={useCaseItem} /> )) } </div> </div> ) }; export default UseCases;
src/components/Box/Header.js
falmar/react-adm-lte
import React from 'react' import PropTypes from 'prop-types' import classnames from 'classnames' const Header = ({title, border, children}) => { const className = { 'with-border': border } return ( <div className={classnames('box-header', className)}> {title && <h3 className='box-title'>{title}</h3>} {children} </div> ) } Header.propTypes = { title: PropTypes.node, border: PropTypes.bool, children: PropTypes.node } export default Header
components/Index.js
migutw42/base16-viewer
import React from 'react'; import ThemeItem from './ThemeItem'; import Head from './Head' const style = { container: { display: "flex", flex: 1 }, main: { width: "750px" }, side: { flex: 1 } }; export default class Index extends React.Component { constructor (props) { super(props); this.state = { searchWord: '', themes: [] }; } componentDidMount () { if (this.state.themes.length === 0) { this.fetchThemes().then(({themes}) =>{ this.setState({themes}); }) } } fetchThemes () { return (async () => { const res = await fetch('./static/themes.json'); const json = await res.json(); return {themes: json.themes} })(); } updateSearchWord(searchWord) { this.setState({searchWord}); } render () { const { themes, searchWord } = this.state; return ( <div style={style.container}> <Head/> <div style={style.side}></div> <div style={style.main}> <div> <h1>base16-viewer</h1> </div> <div> <input type="text" onInput={(e)=> this.updateSearchWord(e.target.value)}/> </div> <div> {themes.map((theme) => ( <ThemeItem key={theme} theme={theme} visible={theme.includes(searchWord)} /> ))} </div> </div> <div style={style.side}></div> </div> ); } }
Sources/ewsnodejs-server/node_modules/@material-ui/styles/esm/ServerStyleSheets/ServerStyleSheets.js
nihospr01/OpenSpeechPlatform-UCSD
import _extends from "@babel/runtime/helpers/esm/extends"; import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck"; import _createClass from "@babel/runtime/helpers/esm/createClass"; import React from 'react'; import { SheetsRegistry } from 'jss'; import StylesProvider from '../StylesProvider'; import createGenerateClassName from '../createGenerateClassName'; var ServerStyleSheets = /*#__PURE__*/function () { function ServerStyleSheets() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, ServerStyleSheets); this.options = options; } _createClass(ServerStyleSheets, [{ key: "collect", value: function collect(children) { // This is needed in order to deduplicate the injection of CSS in the page. var sheetsManager = new Map(); // This is needed in order to inject the critical CSS. this.sheetsRegistry = new SheetsRegistry(); // A new class name generator var generateClassName = createGenerateClassName(); return /*#__PURE__*/React.createElement(StylesProvider, _extends({ sheetsManager: sheetsManager, serverGenerateClassName: generateClassName, sheetsRegistry: this.sheetsRegistry }, this.options), children); } }, { key: "toString", value: function toString() { return this.sheetsRegistry ? this.sheetsRegistry.toString() : ''; } }, { key: "getStyleElement", value: function getStyleElement(props) { return /*#__PURE__*/React.createElement('style', _extends({ id: 'jss-server-side', key: 'jss-server-side', dangerouslySetInnerHTML: { __html: this.toString() } }, props)); } }]); return ServerStyleSheets; }(); export { ServerStyleSheets as default };
src/App/views/Home/index.js
ryanswapp/react-starter-template
import React from 'react'; import CSSModules from 'react-css-modules'; import style from './style'; class Home extends React.Component { constructor(props) { super(props); this.state = { features: [ 'React, Redux', 'React Router', 'Redux Simple Router', 'Node Sass, Bootstrap Sass' ] }; } render() { const { features } = this.state; return ( <div className="container"> <h1 styleName="h1">React Starter Template</h1> <ul className="list-group"> { features.map((feature, i) => { return <li key={ i } className="list-group-item">{ i + 1 }) { feature }</li>; })} </ul> </div> ); } }; export default CSSModules(Home, style);
src/MorphTransitionNative.js
gorangajic/react-svg-morph
import React from 'react'; import MorphTransition from './MorphTransition'; import { Surface, Transform, Shape, } from 'ReactNativeART'; export default class MorphTransitionNative extends MorphTransition { render() { var width = this.props.width; var height = this.props.height; return ( <Surface width={width} height={height} style={{width: width, height: height}} {...this.props}> {this.state.current.map((item, index) => { var rotate = item.trans.rotate; var transform = new Transform().rotate(rotate[0], rotate[1], rotate[2]); return ( <Shape style={item.style} d={item.path} fill="#000000" {...item.attrs} transform={transform} key={index} /> ); })} </Surface> ); } }
src/SparklinesNormalBand.js
samsface/react-sparklines
import React from 'react'; import DataProcessor from './DataProcessor'; export default class SparklinesNormalBand extends React.Component { static propTypes = { style: React.PropTypes.object }; static defaultProps = { style: { fill: 'red', fillOpacity: .1 } }; render() { const { points, margin, style } = this.props; const ypoints = points.map(p => p.y); const mean = DataProcessor.calculateFromData(ypoints, 'mean'); const stdev = DataProcessor.calculateFromData(ypoints, 'stdev'); return ( <rect x={points[0].x} y={mean - stdev + margin} width={points[points.length - 1].x - points[0].x} height={stdev * 2} style={style} /> ) } }
src/components/icon/components/collapse.js
fmsouza/wcode
import React from 'react'; // Icon taken from: https://github.com/spiffcode/ghedit export const Collapse = (props) => ( <svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='-1 0 16 16' {...props}> <path fill='#C5C5C5' d='M14 1v9h-1V2H5V1h9zM3 3v1h8v8h1V3H3zm7 2v9H1V5h9zM8 7H3v5h5V7z'/> <path fill='#75BEFF' d='M4 9h3v1H4z'/> </svg> );
src/index.js
hieudt/redux-tic-tac-toe
import React from 'react'; import App from './containers/App'; import '../bower_components/bootstrap/dist/css/bootstrap.css'; import '../bower_components/font-awesome/css/font-awesome.css' import '../css/main.css'; React.render(<App />, document.getElementById('root'));
src/resources/EditorResources.js
DelvarWorld/some-game
import React from 'react'; import THREE from 'three'; const gameWidth = 600; const gameHeight = 600; export default [ <meshBasicMaterial key={ 84940 } resourceId="selectionWireframe" color={0x66ff00} wireframe />, <shape resourceId="row" key={ 84941 } > <moveTo x={-gameWidth / 2} y={0} /> <lineTo x={gameHeight / 2} y={0} /> </shape>, <shape resourceId="col" key={ 84942 } > <moveTo x={0} y={-gameWidth / 2} /> <lineTo x={0} y={gameHeight / 2} /> </shape>, <lineBasicMaterial key={ 84943 } resourceId="gridLineMaterial" color={0x222222} linewidth={0.5} />, <meshBasicMaterial key={ 84944 } resourceId="gridFloorMaterial" color={0xffffff} opacity={0.4} transparent />, <meshPhongMaterial key={ 84945 } resourceId="ghostMaterial" color={0xff0000} opacity={0.5} side={ THREE.DoubleSide } transparent />, ];
ui/src/views/deviceprofiles/ListDeviceProfiles.js
jcampanell-cablelabs/lora-app-server
import React, { Component } from 'react'; import { Link } from 'react-router'; import Pagination from "../../components/Pagination"; import DeviceProfileStore from "../../stores/DeviceProfileStore"; import SessionStore from "../../stores/SessionStore"; class DeviceProfileRow extends Component { render() { return( <tr> <td><Link to={`organizations/${this.props.organizationID}/device-profiles/${this.props.deviceProfile.deviceProfileID}`}>{this.props.deviceProfile.name}</Link></td> </tr> ); } } class ListDeviceProfiles extends Component { constructor() { super(); this.state = { pageSize: 20, deviceProfiles: [], isAdmin: false, pageNumber: 1, pages: 1, }; this.updatePage = this.updatePage.bind(this); } componentDidMount() { this.updatePage(this.props); SessionStore.on("change", () => { this.setState({ isAdmin: SessionStore.isAdmin() || SessionStore.isOrganizationAdmin(this.props.params.organizationID), }); }); } updatePage(props) { this.setState({ isAdmin: SessionStore.isAdmin() || SessionStore.isOrganizationAdmin(this.props.params.organizationID), }); const page = (props.location.query.page === undefined) ? 1 : props.location.query.page; DeviceProfileStore.getAllForOrganizationID(props.params.organizationID, this.state.pageSize, (page-1) * this.state.pageSize, (totalCount, deviceProfiles) => { this.setState({ deviceProfiles: deviceProfiles, pageNumber: page, pages: Math.ceil(totalCount / this.state.pageSize), }); window.scrollTo(0, 0); }); } render() { const DeviceProfileRows = this.state.deviceProfiles.map((deviceProfile, i) => <DeviceProfileRow key={deviceProfile.deviceProfileID} deviceProfile={deviceProfile} organizationID={this.props.params.organizationID} />); return( <div className="panel panel-default"> <div className={`panel-heading clearfix ${this.state.isAdmin ? '' : 'hidden'}`}> <div className="btn-group pull-right"> <Link to={`organizations/${this.props.params.organizationID}/device-profiles/create`}><button type="button" className="btn btn-default btn-sm">Create device-profile</button></Link> </div> </div> <div className="panel-body"> <table className="table table-hover"> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> {DeviceProfileRows} </tbody> </table> </div> <Pagination pages={this.state.pages} currentPage={this.state.pageNumber} pathname={`organizations/${this.props.params.organizationID}/device-profiles`} /> </div> ); } } export default ListDeviceProfiles;
src/decorators/withViewport.js
deslee/deslee-react-flux
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from '../../node_modules/react/lib/ExecutionEnvironment'; let EE; let viewport = {width: 1366, height: 768}; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = {width: window.innerWidth, height: window.innerHeight}; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on('resize', this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({viewport: value}); } }; } export default withViewport;
docs/src/pages/layout/grid/CenteredGrid.js
dsslimshaddy/material-ui
// @flow weak import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import Paper from 'material-ui/Paper'; import Grid from 'material-ui/Grid'; const styles = theme => ({ root: { flexGrow: 1, marginTop: 30, }, paper: { padding: 16, textAlign: 'center', color: theme.palette.text.secondary, }, }); function CenteredGrid(props) { const classes = props.classes; return ( <div className={classes.root}> <Grid container spacing={24}> <Grid item xs={12}> <Paper className={classes.paper}>xs=12</Paper> </Grid> <Grid item xs={6}> <Paper className={classes.paper}>xs=6</Paper> </Grid> <Grid item xs={6}> <Paper className={classes.paper}>xs=6</Paper> </Grid> <Grid item xs={3}> <Paper className={classes.paper}>xs=3</Paper> </Grid> <Grid item xs={3}> <Paper className={classes.paper}>xs=3</Paper> </Grid> <Grid item xs={3}> <Paper className={classes.paper}>xs=3</Paper> </Grid> <Grid item xs={3}> <Paper className={classes.paper}>xs=3</Paper> </Grid> </Grid> </div> ); } CenteredGrid.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(CenteredGrid);
app/routes.js
dolfelt/markdeck
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './editor/containers/App'; import MainPanel from './editor/containers/MainPanel'; export default ( <Route path="/" component={App}> <IndexRoute component={MainPanel} /> </Route> );
src/client/assets/javascripts/app/DevTools.js
Sevas727/ReactTest3
import React from 'react'; import { createDevTools } from 'redux-devtools'; // Monitors are separate packages, and you can make a custom one import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; import SliderMonitor from 'redux-slider-monitor'; // createDevTools takes a monitor and produces a DevTools component export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q" changeMonitorKey="ctrl-m"> <LogMonitor theme="nicinabox" /> <SliderMonitor keyboardEnabled /> </DockMonitor> );
liferay-gsearch-workspace/modules/gsearch-react-web/src/main/resources/META-INF/resources/lib/containers/Filters/Filter/ScopeFilter.js
peerkar/liferay-gsearch
import React from 'react' import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { Dropdown } from 'semantic-ui-react' import { RequestParameterNames } from '../../../constants/requestparameters'; import { scopeOptions, defaultScope } from '../../../constants/scope'; import { search } from "../../../store/actions/search"; import { getScope } from '../../../store/reducers/search'; /** * Redux mapping. * * @param {Object} dispatch */ function mapDispatchToProps(dispatch) { const getSearchResults = search.request; return bindActionCreators({ getSearchResults }, dispatch); } /** * Redux mapping. * * @param {Object} state */ function mapStateToProps(state) { return { scope: getScope(state) }; } /** * Scope filter component. */ class ScopeFilter extends React.Component { constructor(props) { super(props); // Bind functions to this instance. this.handleItemSelect = this.handleItemSelect.bind(this); } /** * Handle item selection event. * * @param {Object} event * @param {String} value */ handleItemSelect(event, { value }) { this.props.getSearchResults({ [RequestParameterNames.SCOPE]: value }) } /** * Render */ render() { const { scope } = this.props; return ( <Dropdown compact defaultValue={defaultScope} className='gsearch-filter' onChange={this.handleItemSelect} options={scopeOptions} value={scope} /> ) } } export default connect(mapStateToProps, mapDispatchToProps)(ScopeFilter);
app/containers/LanguageProvider/index.js
romanvieito/ball-simpler
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { makeSelectLocale } from './selectors'; export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ); } } LanguageProvider.propTypes = { locale: PropTypes.string, messages: PropTypes.object, children: PropTypes.element.isRequired, }; const mapStateToProps = createSelector( makeSelectLocale(), (locale) => ({ locale }) ); export default connect(mapStateToProps)(LanguageProvider);
src/components/topic/TopicsApp.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { injectIntl } from 'react-intl'; import AppContainer from '../AppContainer'; import messages from '../../resources/messages'; import PageTitle from '../common/PageTitle'; const TopicsApp = (props) => { const { formatMessage } = props.intl; return ( <div> <PageTitle /> <AppContainer name="topics" title={formatMessage(messages.topicsToolName)} description={formatMessage(messages.topicsToolDescription)} > {props.children} </AppContainer> </div> ); }; TopicsApp.propTypes = { children: PropTypes.node, intl: PropTypes.object.isRequired, }; export default injectIntl(TopicsApp);
src/index.js
mimccio/komi
import React from 'react' import ReactDOM from 'react-dom' import './index.css' import App from './App' import registerServiceWorker from './registerServiceWorker' ReactDOM.render(<App name='hello' />, document.getElementById('root')) registerServiceWorker()
examples/counter/index.js
Lucifier129/redux
import React from 'react'; import Root from './containers/Root'; React.render( <Root />, document.getElementById('root') );
src/app/js/colors/Rect.js
skratchdot/colorify
import React, { Component } from 'react'; import onecolor from 'onecolor'; // 0: color space, 1: property name, 2: number of gradients const values = { h: ['hsl', '_hue', 360], s: ['hsl', '_saturation', 3], l: ['hsl', '_lightness', 3], r: ['rgb', '_red', 2], g: ['rgb', '_green', 2], b: ['rgb', '_blue', 2], a: ['rgb', '_alpha', 2], }; class Rect extends Component { handleRange = (e) => { let newColor; const type = this.props.type; if ( typeof this.props.onColorChange === 'function' && typeof type === 'string' && Object.prototype.hasOwnProperty.call(values, type) ) { newColor = this.props.color[values[type][0]](); newColor[values[type][1]] = parseFloat(e.target.value); newColor = onecolor(newColor); this.props.onColorChange(newColor); } } render() { let value = 0; const type = this.props.type; const style = {}; let info; let background; if ( typeof type === 'string' && Object.prototype.hasOwnProperty.call(values, type) ) { info = values[type]; value = this.props.color[info[0]]()[info[1]]; background = []; if (info[0] === 'hsl') { for (let i = 0; i < info[2]; i++) { const h = type === 'h' ? (i / 359) * 360 : this.props.color.hsl()._hue * 360; const s = type === 's' ? (i / 2) * 100 : this.props.color.hsl()._saturation * 100; const l = type === 'l' ? (i / 2) * 100 : this.props.color.hsl()._lightness * 100; background.push(`hsla(${h},${s}%,${l}%,${this.props.color.alpha()})`); } } else { for (let i = 0; i < info[2]; i++) { const r = Math.round( type === 'r' ? i * 255 : this.props.color.rgb()._red * 255 ); const g = Math.round( type === 'g' ? i * 255 : this.props.color.rgb()._green * 255 ); const b = Math.round( type === 'b' ? i * 255 : this.props.color.rgb()._blue * 255 ); const a = type === 'a' ? i : this.props.color.alpha(); background.push(`rgba(${r},${g},${b},${a})`); } } style.background = `linear-gradient(to right, ${background.join(',')})`; } return ( <div className="color-rect"> <div className="color-rect-alpha"></div> <input type="range" min="0" max="1" step="0.001" value={value} style={style} onChange={this.handleRange} onInput={this.handleRange} /> </div> ); } } export default Rect;
src/components/Button/demo/icon/index.js
lebra/lebra-components
import React, { Component } from 'react'; import { render } from 'react-dom'; import Button from '../../index'; import './index.less'; export default class BaseDemo extends Component { render() { return ( <div> <Button iconType="iconfont icon-add" shape="squared"></Button> <Button iconType="iconfont icon-add">确定</Button> </div> ) } } let root = document.getElementById('app'); render(<BaseDemo />, root);
react/src/components/dashboard/coinTile/coinTile.js
pbca26/EasyDEX-GUI
import React from 'react'; import { connect } from 'react-redux'; import { getCoinTitle, getModeInfo, isKomodoCoin, } from '../../../util/coinHelper'; import CoinTileItem from './coinTileItem'; import translate from '../../../translate/translate'; import CoinTileRender from './coinTile.render'; class CoinTile extends React.Component { constructor() { super(); this.state = { toggledSidebar: false, }; this.renderTiles = this.renderTiles.bind(this); this.toggleSidebar = this.toggleSidebar.bind(this); } toggleSidebar() { this.setState({ toggledSidebar: !this.state.toggledSidebar, }); } renderTiles() { const modes = [ 'native', 'spv', 'eth', ]; const allCoins = this.props.allCoins; let items = []; if (allCoins) { for (let i = 0; i < modes.length; i++) { allCoins[modes[i]].sort(); for (let j = 0; j < allCoins[modes[i]].length; j++) { const _coinMode = getModeInfo(modes[i]); const modecode = _coinMode.code; const modetip = _coinMode.tip; const modecolor = _coinMode.color; const _coinTitle = getCoinTitle(allCoins[modes[i]][j].toUpperCase()); const coinlogo = allCoins[modes[i]][j].toUpperCase(); const coinname = translate(((modes[i] === 'spv' || modes[i] === 'native') && isKomodoCoin(allCoins[modes[i]][j]) ? 'ASSETCHAINS.' : 'CRYPTO.') + allCoins[modes[i]][j].toUpperCase()); const data = { coinlogo, coinname, coin: allCoins[modes[i]][j], mode: modes[i], modecolor, modetip, modecode, }; items.push( <CoinTileItem key={ `coin-tile-${modes[i]}-${allCoins[modes[i]][j]}` } i={ i * (j + 1) } item={ data } /> ); } } } return items; } render() { return CoinTileRender.call(this); } } const mapStateToProps = (state) => { return { allCoins: state.Main.coins, }; }; export default connect(mapStateToProps)(CoinTile);
example/google.js
jukra/react-leaflet-google-sunenergia
import React from 'react'; import { Map, TileLayer, LayersControl } from 'react-leaflet' import {GoogleLayer} from '../src' const { BaseLayer} = LayersControl; const key = 'AIzaSyDEG4lyorD61vnJoAHG0FkQERZ-McElZyg'; const terrain = 'TERRAIN'; const road = 'ROADMAP'; const satellite = 'SATELLITE'; const hydrid = 'HYBRID'; //// Google's map type. Valid values are 'roadmap', 'satellite' or 'terrain'. 'hybrid' is not really supported. export default class GoogleExample extends React.Component { constructor() { super(); } render() { return ( <Map center={[42.09618442380296, -71.5045166015625]} zoom={2} zoomControl={true}> <LayersControl position='topright'> <BaseLayer name='OpenStreetMap.Mapnik'> <TileLayer url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"/> </BaseLayer> <BaseLayer checked name='Google Maps Roads'> <GoogleLayer googlekey={key} maptype={road} /> </BaseLayer> <BaseLayer name='Google Maps Terrain'> <GoogleLayer googlekey={key} maptype={terrain} /> </BaseLayer> <BaseLayer name='Google Maps Satellite'> <GoogleLayer googlekey={key} maptype={satellite} /> </BaseLayer> <BaseLayer name='Google Maps Hydrid'> <GoogleLayer googlekey={key} maptype={hydrid} libraries={['geometry', 'places']} /> </BaseLayer> <BaseLayer name='Google Maps with Libraries'> <GoogleLayer googlekey={key} maptype={hydrid} libraries={['geometry', 'places']} /> </BaseLayer> </LayersControl> </Map> ) } }
src/main.js
sheridp2/triviapp
import React from 'react'; import ReactDOM from 'react-dom'; import './style.scss'; import App from './component/app'; ReactDOM.render(<App />, document.getElementById('root'));
examples/huge-apps/components/App.js
kelsadita/react-router
import React from 'react'; import Dashboard from './Dashboard'; import GlobalNav from './GlobalNav'; class App extends React.Component { render() { var courses = COURSES; return ( <div> <GlobalNav /> <div style={{ padding: 20 }}> {this.props.children || <Dashboard courses={courses} />} </div> </div> ); } } export default App;
examples/universal/client/index.js
wescravens/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import configureStore from '../common/store/configureStore'; import App from '../common/containers/App'; const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const rootElement = document.getElementById('app'); React.render( <Provider store={store}> {() => <App/>} </Provider>, rootElement );
examples/huge-apps/components/App.js
clloyd/react-router
/*globals COURSES:true */ import React from 'react' import Dashboard from './Dashboard' import GlobalNav from './GlobalNav' class App extends React.Component { render() { return ( <div> <GlobalNav /> <div style={{ padding: 20 }}> {this.props.children || <Dashboard courses={COURSES} />} </div> </div> ) } } export default App
src/routes/home/Home.js
0xcdc/rfb-client-app
import useStyles from 'isomorphic-style-loader/useStyles'; import React from 'react'; import PropTypes from 'prop-types'; import s from './Home.css'; import SearchBar from '../../components/SearchBar'; export default function Home({ clients }) { useStyles(s); return <SearchBar clients={clients} />; } Home.propTypes = { clients: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.number.isRequired, name: PropTypes.string.isRequired, householdId: PropTypes.number.isRequired, householdSize: PropTypes.number.isRequired, cardColor: PropTypes.string.isRequired, lastVisit: PropTypes.string, note: PropTypes.string, }), ).isRequired, };
src/index.js
guilherme-toti/react-highlight-overlay
import React from 'react' class HighlightOverlay extends React.Component { constructor(props) { super(props) this.state = { width: 0, height: 0 } } componentDidMount() { this.updateWindowSize() window.onresize = () => this.updateWindowSize() } updateWindowSize = () => { const { width, height } = this.getBodySize() this.setState({ width: width, height: height }) } componentDidUpdate = () => { this.updateCanvas() } getBodySize = () => { return document.body.getBoundingClientRect() } updateCanvas = () => { let context = this.refs.canvas.getContext('2d') context.save() this.drawBackground(context) context.globalCompositeOperation = 'destination-out' for (let index = 0; index < this.props.targets.length; index++) { this.drawHighlight(context, this.props.targets[index]) } context.restore() } drawBackground = (context) => { const { width, height } = this.getBodySize() context.clearRect(0, 0, width, height) context.beginPath() context.rect(0, 0, width, height) context.fillStyle = this.props.backgroundColor context.fill() } drawHighlight = (context, target) => { const targetObject = document.querySelector(target) if (!targetObject) { setTimeout(() => { this.drawHighlight(context, target) }, 200) return } const { top, left, width, height } = targetObject.getBoundingClientRect() context.beginPath() context.rect(left, top, width, height) context.fillStyle = 'white' context.fill() } render = () => { return ( <canvas ref="canvas" width={ this.state.width } height={ this.state.height } style={{ top: 0, left: 0, position: 'absolute', zIndex: this.props.zIndex }} /> ) } } HighlightOverlay.propTypes = { targets: React.PropTypes.array, zIndex: React.PropTypes.number, backgroundColor: React.PropTypes.string } HighlightOverlay.defaultProps = { targets: [], zIndex: 1400, backgroundColor: 'rgba(0, 0, 0, 0.6)' } module.exports = HighlightOverlay
src/ListComposite/index.js
DuckyTeam/ducky-components
import Icon from '../Icon'; import React from 'react'; import PropTypes from 'prop-types'; import Typography from '../Typography'; import classNames from 'classnames'; import styles from './styles.css'; function ListComposite(props) { const title = ( props.challenge ? props.challengeName : 'Hashtag' ); const supplementInfo = ( props.challenge ? ' deltagere' : ' poster' ); return ( <div className={classNames(styles.wrapper, {[props.className]: props.className})}> <Icon className={styles.icon} icon={props.challenge ? 'icon-trophy' : 'icon-local_offer'} size={"standard"} /> <div className={styles.composite}> <Typography className={styles.typo} type="bodyTextTitle" > {title} </Typography> <Typography className={styles.typo} type="caption2Normal" > {props.info} {supplementInfo} </Typography> </div> </div> ); } ListComposite.propTypes = { challenge: PropTypes.bool, challengeName: PropTypes.string, className: PropTypes.string, info: PropTypes.number }; export default ListComposite;
modules/pages/client/components/Foundation.component.js
Trustroots/trustroots
// External dependencies import { Trans, useTranslation } from 'react-i18next'; import React from 'react'; // Internal dependencies` import { userType } from '@/modules/users/client/users.prop-types'; import Board from '@/modules/core/client/components/Board.js'; import ManifestoText from './ManifestoText.component.js'; export default function Foundation({ user }) { const { t } = useTranslation('pages'); return ( <> <Board names="nordiclights"> <div className="container"> <div className="row"> <div className="col-xs-12 text-center"> <br /> <br /> <i className="icon-3x icon-heart-o"></i> <br /> <br /> <h2>{t('Trustroots Foundation')}</h2> </div> </div> </div> </Board> <section className="container container-spacer"> <div className="row"> <div className="col-xs-12 col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8"> <p className="lead"> {t(`Trustroots is owned and operated by Trustroots Foundation, a non-profit Limited by Guarantee (LBG) under section 60 exemption, registered in the United Kingdom in March 2015.`)} </p> <ul className="list-inline"> <li> <a href="https://beta.companieshouse.gov.uk/company/09489825"> {t('Details')} </a> </li> <li> <a href="https://ideas.trustroots.org/wordpress/wp-content/uploads/2015/03/Trustroots-Articles-2015.pdf"> {t('Foundation’s Articles')} </a>{' '} <small className="text-muted">(pdf)</small> </li> <li> <a href="/faq/foundation">{t('FAQ')}</a> </li> <li> <a href="https://ideas.trustroots.org/2015/03/10/announcing-trustroots-foundation/"> {t('Announcement')} </a>{' '} <small className="text-muted"> ({t('{{date, LL}}', { date: new Date(2015, 2, 10) })}) </small> </li> <li> <a href="/support">{t('Contact us')}</a> </li> <li> <a href="/volunteering">{t('Volunteering')}</a> </li> </ul> </div> </div> {/* /.row */} </section> {/* /.container */} {/* Board */} <section className="container container-spacer"> <hr /> <div className="row"> <div className="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3 text-center"> <h2 id="board">{t('Board')}</h2> <p> <Trans t={t} ns="pages"> We are a group of hospitality exchange enthusiasts with backgrounds in some notable projects. The same people who also brought you <a href="https://hitchwiki.org/">Hitchwiki</a>,{' '} <a href="https://trashwiki.org/">Trashwiki</a>,{' '} <a href="https://nomadwihki.org/">Nomadwiki</a> &amp; more. </Trans> </p> <p> {t( 'All current board members are also members of the founding team. We will have non-founding members in the board at some point.', )} </p> <br /> <br /> </div> </div> <div className="row"> <div className="col-xs-12 col-sm-4"> {/* Mikael */} <div className="media"> <a className="pull-left" href="https://mikaelkorpela.fi/"> <img className="media-object img-circle" src="//gravatar.com/avatar/d0229f23745d3c266f81c6b0cd014a38?s=200" width="100" alt="Mikael" /> </a> <div className="media-body"> <h4 className="media-heading">Mikael</h4> <p className="text-color-links"> <Trans t={t} ns="pages"> Working on big freegan/travel projects such as{' '} <a href="https://hitchwiki.org/">Hitchwiki</a>,{' '} <a href="http://hitchgathering.org/"> Hitchgathering festival </a> , <a href="https://trashwiki.org/">Trashwiki</a> and{' '} <a href="https://nomadwiki.org/">Nomadwiki</a> since 2008. In the past has volunteered for BeWelcome (2013). Active open source contributor and visionary free/gift-economics activist. A developer at{' '} <a href="https://automattic.com/">Automattic</a>. </Trans> </p> <p> <ul className="list-inline"> <li> <a href="https://www.mikaelkorpela.fi/"> mikaelkorpela.fi </a> </li> <li> <a href="/profile/mikael">{t('Trustroots profile')}</a> </li> </ul> </p> </div> </div> <br /> <br /> </div> <div className="col-xs-12 col-sm-4"> {/* Natalia */} <div className="media"> <img className="media-object img-circle pull-left" src="/img/team-natalia.jpg" width="100" alt="Natalia" /> <div className="media-body"> <h4 className="media-heading">Natalia</h4> <p className="text-color-links"> {t( 'Coming from a multinational business background, Natalia is an enthusiastic of the share and gift economy. Veteran globetrotter and volunteer for different NGOs from hospex as Couchsurfing to nonprofit lobbying orgs.', )} </p> <p> <ul className="list-inline"> <li> <a href="https://www.linkedin.com/in/natalia-s%C3%A1enz-alban%C3%A9s-38469227/"> LinkedIn </a> </li> <li> <a href="/profile/natalia_sevilla"> {t('Trustroots profile')} </a> </li> </ul> </p> </div> </div> </div> </div> <hr /> <div className="row"> <div className="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3 text-center"> <h2>{t('Past board members')}</h2> <p> {t( 'Callum, Carlos and Kasper were also part of the founding team.', )} </p> <br /> <br /> </div> </div> <div className="row"> <div className="col-xs-12 col-sm-4 col-sm-offset-2"> {/* Callum */} <div className="media"> <a className="pull-left" href="https://www.callum-macdonald.com/"> <img className="media-object img-circle" src="//gravatar.com/avatar/1e2eebc68bae7e891391688ad1c331d1?s=100" width="100" alt="" /> </a> <div className="media-body"> <h4 className="media-heading">Callum</h4> <p className="text-color-links"> {t( 'Long term nomad and technology expert. Volunteered for BeWelcome BoD in 2013 and for CouchSurfing in 2007.', )} </p> <p> <ul className="list-inline"> <li> <a href="https://www.callum-macdonald.com/"> callum-macdonald.com </a> </li> <li> <a href="/profile/chmac">{t('Trustroots profile')}</a> </li> </ul> </p> </div> </div> </div> <div className="col-xs-12 col-sm-4"> {/* Carlos */} <div className="media"> <img className="media-object img-circle pull-left" src="/img/team-carlos.jpg" width="100" alt="Carlos" /> <div className="media-body"> <h4 className="media-heading">Carlos</h4> <p className="text-color-links"> {t( 'Love to travel, passionate and enthusiastic about share economy and hospitality exchange as human development tools. Volunteered CouchSurfing from 2008 to 2010 as well as other NGOs.', )} </p> <p> <ul className="list-inline"> <li> <a href="https://www.linkedin.com/in/carlosmcardenas/"> LinkedIn </a> </li> <li> <a href="/profile/carlos">{t('Trustroots profile')}</a> </li> </ul> </p> </div> </div> </div> <div className="col-xs-12 col-sm-4"> {/* Kasper */} <div className="media"> <a className="pull-left" href="https://guaka.org/"> <img className="media-object img-circle" src="/img/team-kasper.png" width="100" alt="Kasper" /> </a> <div className="media-body"> <h4 className="media-heading">Kasper</h4> <p className="text-color-links"> <Trans t={t} ns="pages"> Founded multiple popular and trusted websites such as{' '} <a href="https://hitchwiki.org/">Hitchwiki</a>,{' '} <a href="https://trashwiki.org/">Trashwiki</a>,{' '} <a href="https://nomadwiki.org/">Nomadwiki</a>,{' '} <a href="https://couchwiki.org/">Couchwiki</a> and{' '} <a href="https://deletionpedia.org/">Deletionpedia</a>.{' '} Volunteered for CouchSurfing as a tech team coordinator in 2006 and 2007 and for{' '} <a href="https://www.bewelcome.org/">BeWelcome</a> since 2007. Loves paradoxes, makes money with{' '} <a href="https://moneyless.org/">moneyless.org</a>. </Trans> </p> <p> <ul className="list-inline"> <li> <a href="https://guaka.org/">guaka.org</a> </li> <li> <a href="/profile/guaka">{t('Trustroots profile')}</a> </li> </ul> </p> </div> </div> </div> </div> <hr /> </section> <section className="vision-footer"> <div className="container"> <div className="row" id="mission-vision-values"> <div className="col-xs-12 text-center hidden-xs"> <h2>{t('Vision, Mission & Values')}</h2> <br /> <br /> </div> <div className="col-sm-4 text-center"> <h3 id="vision">{t('Vision')}</h3> <p className="lead"> <em>“{t('A world that encourages trust and adventure.')}”</em> </p> </div> <div className="col-sm-4 text-center"> <h3 id="mission">{t('Mission')}</h3> <p className="lead"> {t(`Trustroots seeks to be a platform for sharing and getting people together. We aim to connect likeminded people together. We encourage trust, adventure and intercultural connections.`)} </p> </div> <div className="col-sm-4 text-center"> <h3 id="values">{t('Values')}</h3> <ul className="list-unstyled lead"> <li>{t('Trust')}</li> <li>{t('Adventure')}</li> <li>{t('Transparency')}</li> <li>{t('Freedom')}</li> </ul> </div> </div> {/* /.row */} </div> {/* /.container */} </section> {/* Manifesto */} <Board className="board-primary board-inset" names="jungleroad" id="manifesto" > <div className="container"> <div className="row"> <div className="col-md-offset-3 col-md-6 text-center lead font-brand-light"> <ManifestoText></ManifestoText> {!user && ( <p> <br /> <br /> <a href="/signup" className="btn btn-lg btn-action btn-inverse" > {t('Join Trustroots')} </a> </p> )} </div> </div> </div> </Board> </> ); } Foundation.propTypes = { user: userType, };
packages/material-ui-icons/src/Lock.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z" /></g> , 'Lock');
components/Layout/Navigation.js
gadflying/profileSite
/** * 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'; import Link from '../Link'; import s from './Header.css'; class Navigation extends React.Component { componentDidMount() { window.componentHandler.upgradeElement(this.root); } componentWillUnmount() { window.componentHandler.downgradeElements(this.root); } render() { return ( <nav className="mdl-navigation" ref={node => (this.root = node)}> <Link className="mdl-navigation__link ${s.substitle}" to="/">Home</Link> <Link className="mdl-navigation__link ${s.substitle}" to="/about">Works</Link> <Link className="mdl-navigation__link ${s.substitle}" to="/about">Blogs</Link> <Link className="mdl-navigation__link ${s.substitle}" to="/about">Contact</Link> </nav> ); } } export default Navigation;
docs/src/HomePage.js
blue68/react-bootstrap
import React from 'react'; import NavMain from './NavMain'; import PageFooter from './PageFooter'; import Grid from '../../src/Grid'; import Alert from '../../src/Alert'; import Glyphicon from '../../src/Glyphicon'; import Label from '../../src/Label'; export default class HomePage extends React.Component { render() { return ( <div> <NavMain activePage="home" /> <main className="bs-docs-masthead" id="content" role="main"> <div className="container"> <span className="bs-docs-booticon bs-docs-booticon-lg bs-docs-booticon-outline"></span> <p className="lead">The most popular front-end framework, rebuilt for React.</p> </div> </main> <Grid> <Alert bsStyle="warning"> <p><Glyphicon glyph="bullhorn" /> We are actively working to reach a 1.0.0 release, and we would love your help to get there.</p> <p><Glyphicon glyph="check" /> Check out the <a href="https://github.com/react-bootstrap/react-bootstrap/wiki#100-roadmap">1.0.0 Roadmap</a> and <a href="https://github.com/react-bootstrap/react-bootstrap/blob/master/CONTRIBUTING.md">Contributing Guidelines</a> to see where you can help out.</p> <p><Glyphicon glyph="sunglasses" /> A great place to start is any <a target="_blank" href="https://github.com/react-bootstrap/react-bootstrap/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22">issues</a> with a <Label bsStyle="success">help-wanted</Label> label.</p> <p><Glyphicon glyph="ok" /> We are open to pull requests that address bugs, improve documentation, enhance accessibility,</p> <p>add test coverage, or bring us closer to feature parity with <a target="_blank" href="http://getbootstrap.com/">Bootstrap</a>.</p> <p><Glyphicon glyph="user" /> We actively seek to invite frequent pull request authors to join the organization. <Glyphicon glyph="thumbs-up" /></p> </Alert> <Alert bsStyle="danger"> <p><Glyphicon glyph="warning-sign" /> The project is under active development, and APIs will change. </p> <p><Glyphicon glyph="bullhorn" /> Prior to the 1.0.0 release, breaking changes should result in a Minor version bump.</p> </Alert> <Alert bsStyle="info"> <p><Glyphicon glyph="bullhorn" /> If you want to try / play with <b>React-0.14</b> betas, we cut releases from the <b>react-14</b> branch. They're on the <b>react-pre</b> tag.</p> <p><kbd>$ npm install react-bootstrap@react-pre</kbd></p> </Alert> </Grid> <PageFooter /> </div> ); } }
src/Label.js
rapilabs/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const Label = React.createClass({ mixins: [BootstrapMixin], getDefaultProps() { return { bsClass: 'label', bsStyle: 'default' }; }, render() { let classes = this.getBsClassSet(); return ( <span {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </span> ); } }); export default Label;
client/components/Flass/Upload/QuestionInsertion/Quiz/QuizWrapper/QuizWrapperComponent.js
Nexters/flass
import React from 'react'; import PropTypes from 'prop-types'; import './QuizWrapperComponentStyles.scss'; const propTypes = { children: PropTypes.element.isRequired }; const defaultProps = {}; const QuizWrapperComponent = ({ children }) => ( <div className="quiz-wrapper"> { children } </div> ); QuizWrapperComponent.propTypes = propTypes; QuizWrapperComponent.defaultProps = defaultProps; export default QuizWrapperComponent;
examples-native/crna-kitchen-sink/storybook/stories/Button/index.ios.js
storybooks/react-storybook
import React from 'react'; import PropTypes from 'prop-types'; import { TouchableHighlight } from 'react-native'; export default function Button({ onPress, children }) { return <TouchableHighlight onPress={onPress}>{children}</TouchableHighlight>; } Button.defaultProps = { children: null, onPress: () => {}, }; Button.propTypes = { children: PropTypes.node, onPress: PropTypes.func, };
src/svg-icons/maps/local-phone.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalPhone = (props) => ( <SvgIcon {...props}> <path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/> </SvgIcon> ); MapsLocalPhone = pure(MapsLocalPhone); MapsLocalPhone.displayName = 'MapsLocalPhone'; MapsLocalPhone.muiName = 'SvgIcon'; export default MapsLocalPhone;
test/templates/Check.snap.js
sullenor/teatime-test-utils
import Check from 'teatime-components/component/Check'; import React from 'react'; export default () => ( <Check id='checks-id' label='checks label' name='check-control'/> );
fields/types/Field.js
dryna/keystone-twoje-urodziny
import classnames from 'classnames'; import evalDependsOn from '../utils/evalDependsOn.js'; import React from 'react'; import { findDOMNode } from 'react-dom'; import { FormField, FormInput, FormNote } from '../../admin/client/App/elemental'; import blacklist from 'blacklist'; import CollapsedFieldLabel from '../components/CollapsedFieldLabel'; function isObject (arg) { return Object.prototype.toString.call(arg) === '[object Object]'; } function validateSpec (spec) { if (!spec) spec = {}; if (!isObject(spec.supports)) { spec.supports = {}; } if (!spec.focusTargetRef) { spec.focusTargetRef = 'focusTarget'; } return spec; } var Base = module.exports.Base = { getInitialState () { return {}; }, getDefaultProps () { return { adminPath: Keystone.adminPath, inputProps: {}, labelProps: {}, valueProps: {}, size: 'full', }; }, getInputName (path) { // This correctly creates the path for field inputs, and supports the // inputNamePrefix prop that is required for nested fields to work return this.props.inputNamePrefix ? `${this.props.inputNamePrefix}[${path}]` : path; }, valueChanged (event) { this.props.onChange({ path: this.props.path, value: event.target.value, }); }, shouldCollapse () { return this.props.collapse && !this.props.value; }, shouldRenderField () { if (this.props.mode === 'create') return true; return !this.props.noedit; }, focus () { if (!this.refs[this.spec.focusTargetRef]) return; findDOMNode(this.refs[this.spec.focusTargetRef]).focus(); }, renderNote () { if (!this.props.note) return null; return <FormNote html={this.props.note} />; }, renderField () { const { autoFocus, value, inputProps } = this.props; return ( <FormInput {...{ ...inputProps, autoFocus, autoComplete: 'off', name: this.getInputName(this.props.path), onChange: this.valueChanged, ref: 'focusTarget', value, }} /> ); }, renderValue () { return <FormInput noedit>{this.props.value}</FormInput>; }, renderUI () { var wrapperClassName = classnames( 'field-type-' + this.props.type, this.props.className, { 'field-monospace': this.props.monospace } ); return ( <FormField htmlFor={this.props.path} label={this.props.label} className={wrapperClassName} cropLabel> <div className={'FormField__inner field-size-' + this.props.size}> {this.shouldRenderField() ? this.renderField() : this.renderValue()} </div> {this.renderNote()} </FormField> ); }, }; var Mixins = module.exports.Mixins = { Collapse: { componentWillMount () { this.setState({ isCollapsed: this.shouldCollapse(), }); }, componentDidUpdate (prevProps, prevState) { if (prevState.isCollapsed && !this.state.isCollapsed) { this.focus(); } }, uncollapse () { this.setState({ isCollapsed: false, }); }, renderCollapse () { if (!this.shouldRenderField()) return null; return ( <FormField> <CollapsedFieldLabel onClick={this.uncollapse}>+ Add {this.props.label.toLowerCase()}</CollapsedFieldLabel> </FormField> ); }, }, }; module.exports.create = function (spec) { spec = validateSpec(spec); var field = { spec: spec, displayName: spec.displayName, mixins: [Mixins.Collapse], statics: { getDefaultValue: function (field) { return field.defaultValue || ''; }, }, render () { if (!evalDependsOn(this.props.dependsOn, this.props.values)) { return null; } if (this.state.isCollapsed) { return this.renderCollapse(); } return this.renderUI(); }, }; if (spec.statics) { Object.assign(field.statics, spec.statics); } var excludeBaseMethods = {}; if (spec.mixins) { spec.mixins.forEach(function (mixin) { Object.keys(mixin).forEach(function (name) { if (Base[name]) { excludeBaseMethods[name] = true; } }); }); } Object.assign(field, blacklist(Base, excludeBaseMethods)); Object.assign(field, blacklist(spec, 'mixins', 'statics')); if (Array.isArray(spec.mixins)) { field.mixins = field.mixins.concat(spec.mixins); } return React.createClass(field); };
node_modules/react-bootstrap/es/Radio.js
FoxMessenger/nyt-react
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 warning from 'warning'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { inline: PropTypes.bool, disabled: PropTypes.bool, /** * Only valid if `inline` is not set. */ validationState: PropTypes.oneOf(['success', 'warning', 'error', null]), /** * Attaches a ref to the `<input>` element. Only functions can be used here. * * ```js * <Radio inputRef={ref => { this.input = ref; }} /> * ``` */ inputRef: PropTypes.func }; var defaultProps = { inline: false, disabled: false }; var Radio = function (_React$Component) { _inherits(Radio, _React$Component); function Radio() { _classCallCheck(this, Radio); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Radio.prototype.render = function render() { var _props = this.props, inline = _props.inline, disabled = _props.disabled, validationState = _props.validationState, inputRef = _props.inputRef, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['inline', 'disabled', 'validationState', 'inputRef', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var input = React.createElement('input', _extends({}, elementProps, { ref: inputRef, type: 'radio', disabled: disabled })); if (inline) { var _classes2; var _classes = (_classes2 = {}, _classes2[prefix(bsProps, 'inline')] = true, _classes2.disabled = disabled, _classes2); // Use a warning here instead of in propTypes to get better-looking // generated documentation. process.env.NODE_ENV !== 'production' ? warning(!validationState, '`validationState` is ignored on `<Radio inline>`. To display ' + 'validation state on an inline radio, set `validationState` on a ' + 'parent `<FormGroup>` or other element instead.') : void 0; return React.createElement( 'label', { className: classNames(className, _classes), style: style }, input, children ); } var classes = _extends({}, getClassSet(bsProps), { disabled: disabled }); if (validationState) { classes['has-' + validationState] = true; } return React.createElement( 'div', { className: classNames(className, classes), style: style }, React.createElement( 'label', null, input, children ) ); }; return Radio; }(React.Component); Radio.propTypes = propTypes; Radio.defaultProps = defaultProps; export default bsClass('radio', Radio);
blog/src/Menu/SubMenu.js
Robert2333/kilakila-react
import React from 'react' const PropTypes=require('prop-types'); class SubMenu extends React.Component{ getItem(){ const {children} = this.props; const item = React.Children.map(children, (child,id) => { if (!child) { alert('没有子元素') return; } else { const props = { subId:this.props.subId, id:this.props.subId.toString()+id.toString(), } return React.cloneElement(child,props) } }) return item; } render(){ const {subId,title} = this.props; return( <div> <h4 onClick={()=>this.context.onSelect(subId.toString())}>{title}</h4> <ul>{this.getItem()}</ul> </div> ) } } SubMenu.contextTypes={ onSelect:PropTypes.func, } export default SubMenu;
examples/src/app.js
javier-garcia-anfix/react-select
/* eslint react/prop-types: 0 */ import React from 'react'; import Select from 'react-select'; import CustomRenderField from './components/CustomRenderField'; import MultiSelectField from './components/MultiSelectField'; import RemoteSelectField from './components/RemoteSelectField'; import SelectedValuesField from './components/SelectedValuesField'; import StatesField from './components/StatesField'; import UsersField from './components/UsersField'; import ValuesAsNumbersField from './components/ValuesAsNumbersField'; import DisabledUpsellOptions from './components/DisabledUpsellOptions'; var FLAVOURS = [ { label: 'Chocolate', value: 'chocolate' }, { label: 'Vanilla', value: 'vanilla' }, { label: 'Strawberry', value: 'strawberry' }, { label: 'Cookies and Cream', value: 'cookiescream' }, { label: 'Peppermint', value: 'peppermint' } ]; var FLAVOURS_WITH_DISABLED_OPTION = FLAVOURS.slice(0); FLAVOURS_WITH_DISABLED_OPTION.unshift({ label: 'Caramel (You don\'t like it, apparently)', value: 'caramel', disabled: true }); function logChange() { console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments))); } React.render( <div> <StatesField label="States" searchable /> <UsersField label="Users (custom options/value)" hint="This example uses Gravatar to render user's image besides the value and the options" /> <ValuesAsNumbersField label="Values as numbers" /> <MultiSelectField label="Multiselect"/> <SelectedValuesField label="Clickable labels (labels as links)" options={FLAVOURS} hint="Open the console to see click behaviour (data/event)" /> <SelectedValuesField label="Disabled option" options={FLAVOURS_WITH_DISABLED_OPTION} hint="You savage! Caramel is the best..." /> <DisabledUpsellOptions label="Disable option with an upsell link"/> <SelectedValuesField label="Option Creation (tags mode)" options={FLAVOURS} allowCreate hint="Enter a value that's not in the list, then hit enter" /> <CustomRenderField label="Custom render options/values" /> <CustomRenderField label="Custom render options/values (multi)" multi delimiter="," /> <RemoteSelectField label="Remote Options" hint='Type anything in the remote example to asynchronously load options. Valid alternative results are "A", "AA", and "AB"' /> </div>, document.getElementById('example') );
src/resources/assets/react-app/components/AuthHome.js
darrenmerrett/ruf
import React, { Component } from 'react'; class AuthHome extends Component { render() { return ( <div> You are logged in! </div> ) } } export default AuthHome;
stories/NumberInput.js
felixgirault/rea11y
import React from 'react'; import {storiesOf, action} from '@kadira/storybook'; import {StatefulNumberInput, NumberInputControls} from '../src'; /** * */ storiesOf('NumberInput', module) .addWithInfo( 'default', ` Keyboard interactions when the focus is inside the input: * \`↑\` increments the value * \`↓\` decrements the value * \`Page up\` increments the value by a larger amount * \`Page down\` decrements the value by a larger amount * \`Home\` sets the value to the minimum * \`End\` sets the value to the maximum `, () => ( <StatefulNumberInput onChange={action('onChange')} /> ), { inline: true, source: false, propTables: false } ) .addWithInfo( 'controlable', ` In addition to the keyboards interactions, buttons can be used to increment or decrement the value. `, () => ( <StatefulNumberInput onChange={action('onChange')}> <NumberInputControls /> </StatefulNumberInput> ), { inline: true, source: false, propTables: false } );
client/components/nota/SocialShare.js
EstebanFuentealba/biobiochile-mobile-spa
import React from 'react'; export default class SocialShare extends React.Component{ render() { return (<div> <ul className="barra-social"> <li className="s-fb"> <a href={`https://www.facebook.com/sharer.php?u=${this.props.nota.post_URL}`} className="fa fa-facebook"></a> </li> <li className="s-tw"> <a href={`https://twitter.com/intent/tweet?original_referer=${this.props.nota.post_URL}&text=${this.props.nota.post_title}&url=${this.props.nota.post_URL}`} data-lang="es" className="fa fa-twitter"></a> </li> <li className="s-gp"> <a href={`https://plus.google.com/share?url=${this.props.nota.post_URL}`} className="fa fa-google-plus"></a> </li> <li className="s-lin"> <a href={`https://www.linkedin.com/shareArticle?source=BioBioChile%22+rel%3D%22nofollow&amp;title=${this.props.nota.post_title}&summary=&mini=true&url=${this.props.nota.post_URL}`} className="fa fa-linkedin"></a> </li> <li id="s-wp" className="s-wp"> <a href={`whatsapp://send?text=${this.props.nota.post_title} ${this.props.nota.post_URL}`}></a> </li> </ul> <ul className="data-social"> <li id="s-fb" className="data-fb">0</li> <li id="s-tw" className="data-tw">0</li> <li id="s-gp" className="data-gp">0</li> <li id="s-lin" className="data-lin">0</li> <li className="data-wp">Enviar</li> </ul> </div>) } }
src/components/bookmark-slider.js
bokuweb/tomato_pasta
import React, { Component } from 'react'; import Slider from 'material-ui/lib/slider'; export default class BookmarkSlider extends Component { constructor(props) { super(props); } onSliderChange(e, value) { this.props.changeBookmarkThreshold(~~value, e.clientX); } render() { let x = this.props.bookmarkFilterX - 24; x = (x > 210)? 210 : x; x = (x < 10)? 10 : x; return ( <div className="bookmarkslider"> <div className="bookmarkslider__count" style={{left:x}}> <i className="bookmarkslider__icon icon-hatena" /> {this.props.bookmarkFilter} </div> <Slider name="bookmarkslider" defaultValue={this.props.defaultValue} onChange={this.onSliderChange.bind(this)} onDragStop={this.props.onSliderChanged} max={this.props.max} min={this.props.min} /> </div> ); } }
src/popup/components/Logo/index.js
fluany/fluany
/** * @fileOverview The logo component * @name index.js<Logo> * @license GNU General Public License v3.0 */ import React from 'react' const Logo = () => ( <div className='logo-content'> <svg className='octopus-logo'> <use xlinkHref='#octopus' /> </svg> <h1 className='logo-title'> <span className='flu'>flu</span> <span className='any'>any</span> </h1> </div> ) export default Logo
app/components/CentralStatement.js
freele/glossary
import React from 'react'; import classNames from 'classnames'; import {Decorator as Cerebral} from 'cerebral-react'; @Cerebral({ statement: ['centralStatementRef'] }, {}) class CentralStatement extends React.Component { componentDidMount() { this.props.signals.centralStatementUpdated(); this.props.signals.pageInited(); // $.get(this.props.source, function(result) { // var lastGist = result[0]; // if (this.isMounted()) { // this.setState({ // username: lastGist.owner.login, // lastGistUrl: lastGist.html_url // }); // } // }.bind(this)); } onStatementClick(word) { // console.log('Click info', word); this.props.signals.centralStatementUpdated({search: word}); } renderWord(word, index) { return ( <span key={index}> <span className="statement-word" onClick={() => this.onStatementClick(word)}> {word} </span> <span> {' '} </span> </span> ); } render() { return ( <div className="statement"> <label> {this.props.statement ? this.props.statement.text.split(' ').map(this.renderWord.bind(this)) : ''} </label> </div> ); } } export default CentralStatement;
frontend/src/components/Crud.js
purocean/yii2-template
import React from 'react'; import { Table } from 'antd'; import CrudActions from '../actions/CrudActions'; import CrudStore from '../stores/CrudStore'; class Component extends React.Component { constructor(props){ super(props); this.onChange = this.onChange.bind(this); this.state = CrudStore.getState(); this.rowSelection = { onChange: (selectedRowKeys, selectedRows) => { CrudActions.rowSelectionChange(selectedRowKeys, selectedRows); }, onSelect: (record, selected, selectedRows) => { CrudActions.rowSelectionSelect(record, selected, selectedRows); }, onSelectAll: (selected, selectedRows, changeRows) => { CrudActions.rowSelectionSelectAll(selected, selectedRows, changeRows); }, }; } componentDidMount() { CrudStore.listen(this.onChange); } componentWillUnmount() { CrudStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } handleTableChange(pagination, filters, sorter) { CrudActions.fetch(false, { page: pagination.current, sortField: sorter.field, sortOrder: sorter.order, ...filters }); } render() { return ( <div> {this.props.panel} {this.props.saveModal} <Table bordered rowKey={record => record.id} size={this.props.tableSize} rowSelection={typeof this.props.rowSelection === 'undefined' ? this.rowSelection : this.props.rowSelection} columns={this.props.tableColumns} dataSource={this.state.list} loading={this.state.status === 'fetching'} pagination={this.state.pagination} onChange={(pagination, filters, sorter) => this.handleTableChange(pagination, filters, sorter)} /> </div> ); } } Component.defaultProps = { tableSize: 'middle', }; export default Component;
examples/test/components.js
steos/reactcards
import React from 'react' import { assert } from 'chai' import { shallow } from 'enzyme' import { Foo, Bar } from '../components' export function testBarComponent() { const wrapper = shallow(<Bar/>) assert.equal(wrapper.text(), 'a bar. drink up!') } export function testFooComponent() { const wrapper = shallow(<Foo message="testing"/>) assert.equal(wrapper.text(), "Foo says 'testing'") }
examples/src/components/CustomOption.js
RassaLibre/react-select
import React from 'react'; import Gravatar from 'react-gravatar'; var Option = React.createClass({ propTypes: { addLabelText: React.PropTypes.string, className: React.PropTypes.string, mouseDown: React.PropTypes.func, mouseEnter: React.PropTypes.func, mouseLeave: React.PropTypes.func, option: React.PropTypes.object.isRequired, renderFunc: React.PropTypes.func }, render () { var obj = this.props.option; var size = 15; var gravatarStyle = { borderRadius: 3, display: 'inline-block', marginRight: 10, position: 'relative', top: -2, verticalAlign: 'middle', }; return ( <div className={this.props.className} onMouseEnter={this.props.mouseEnter} onMouseLeave={this.props.mouseLeave} onMouseDown={this.props.mouseDown} onClick={this.props.mouseDown}> <Gravatar email={obj.email} size={size} style={gravatarStyle} /> {obj.value} </div> ); } }); module.exports = Option;
src/containers/App.js
SuperCoac/basic-redux-boilerplate
import React from 'react'; import CounterContainer from './CounterContainer'; function App() { return ( <div> <h1>Counter</h1> <CounterContainer /> </div> ); } export default App;
web-ui/src/login/about/welcome.js
pixelated/pixelated-user-agent
/* * Copyright (c) 2017 ThoughtWorks, Inc. * * Pixelated 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. * * Pixelated 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 Pixelated. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react'; import { translate } from 'react-i18next'; import './welcome.scss'; export const Welcome = ({ t }) => ( <div className='welcome'> <img className='welcome-logo' src='/public/images/welcome.svg' alt={t('login.welcome-image-alt')} /> <div> <h3>{t('login.welcome-message')}</h3> </div> </div> ); Welcome.propTypes = { t: React.PropTypes.func.isRequired }; export default translate('', { wait: true })(Welcome);
src/routes/index.js
pl12133/pl12133.github.io
/* eslint-disable no-unused-vars*/ import React from 'react'; /* eslint-enable no-unused-vars*/ import { Router, Route, IndexRoute } from 'react-router'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import App from './App/'; import Home from './Home/'; const Routes = () => ( <Router history={createBrowserHistory()}> <Route path="/" component={App}> <IndexRoute component={Home} /> </Route> </Router> ); export default Routes;
src/main.js
QuVideo/viva-react-template
import React from 'react' import ReactDOM from 'react-dom' import { Button } from 'antd' import app from './app.less' import title from './title.less' import antShowcase from './ant-showcase.less' const Title = ({ content }) => { return <h1 className={ title.normal }>{ content }</h1> } const AntShowcase = () => { return ( <div className={ antShowcase.normal }> <Button type="primary">Primary</Button> </div> ) } const App = () => { return ( <div className={ app.normal }> <Title content="Welcome to React world." /> <AntShowcase /> </div> ) } ReactDOM.render(<App />, document.getElementById('root')) if (module.hot) { module.hot.accept() }
tests/react_children/tuple.js
jamesgpearce/flow
// @flow import React from 'react'; class Tuple extends React.Component<{children: [boolean, string, number]}, void> {} class TupleOne extends React.Component<{children: [boolean]}, void> {} <Tuple />; // Error: `children` is required. <Tuple>{true}{'foo'}{42}</Tuple>; // OK: All the tuple items. <Tuple>{true}foo{42}</Tuple>; // OK: Mixing text with expressions. <Tuple>{true}{'foo'}{42}{null}</Tuple>; // Error: One to many. <Tuple> {true}foo{42}</Tuple>; // Error: Spaces add items. <Tuple>{true}foo{42} </Tuple>; // Error: Spaces add items. <Tuple>{[true, 'foo', 42]}</Tuple>; // OK: All the tuple items. <Tuple>{[true, 'foo', 42]}{[true, 'foo', 42]}</Tuple>; // Error: There may only // be one tuple. <Tuple>{[true, 'foo', 42, null]}</Tuple>; // Error: One to many // OK: All the tuple items on multiple liens. <Tuple> {true} {'foo'} {42} </Tuple>; // OK: All the tuple items mixing text and expressions. <Tuple> {true} foo {42} </Tuple>; <TupleOne>{true}</TupleOne>; // Error: A single expression is not an array. <TupleOne>{[true]}</TupleOne>; // OK: This is ok.
app/react/demo/src/App.js
enjoylife/storybook
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;
src/components/Button.react.js
Acehaidrey/addrbook
'use strict'; require('./css/Button.less'); import React from 'react'; import {Link} from 'react-router'; /** * Styled button component. */ export default class Button extends React.Component { constructor(props) { super(props); } render() { return ( <div> <h5> This is my button component. </h5> <button> <Link to={this.props.linkName}>{this.props.buttonName}</Link> </button> </div> ); } }
actor-apps/app-web/src/app/components/modals/Preferences.react.js
liruqi/actor-platform-v0.9
import _ from 'lodash'; import React from 'react'; import Modal from 'react-modal'; import ReactMixin from 'react-mixin'; import { IntlMixin, FormattedMessage } from 'react-intl'; import { Styles, FlatButton, RadioButtonGroup, RadioButton, DropDownMenu } from 'material-ui'; import { KeyCodes } from 'constants/ActorAppConstants'; import ActorTheme from 'constants/ActorTheme'; import PreferencesActionCreators from 'actions/PreferencesActionCreators'; import PreferencesStore from 'stores/PreferencesStore'; const appElement = document.getElementById('actor-web-app'); Modal.setAppElement(appElement); const ThemeManager = new Styles.ThemeManager(); const menuItems = [ { payload: '1', text: 'English', value: 'en'}, { payload: '2', text: 'Russian', value: 'ru'} ]; const getStateFromStores = () => { const language = PreferencesStore.language; return { isOpen: PreferencesStore.isModalOpen, preferences: PreferencesStore.preferences, language: language, selectedLanguage: _.findIndex(menuItems, {value: language}) }; }; @ReactMixin.decorate(IntlMixin) class PreferencesModal extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); this.state = getStateFromStores(); ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ button: { minWidth: 60 } }); PreferencesStore.addChangeListener(this.onChange); document.addEventListener('keydown', this.onKeyDown, false); } componentWillUnmount() { PreferencesStore.removeChangeListener(this.onChange); document.removeEventListener('keydown', this.onKeyDown, false); } onChange = () => { this.setState(getStateFromStores()); }; onClose = () => { PreferencesActionCreators.hide(); }; onDone = () => { PreferencesActionCreators.save({ language: this.state.language, sendByEnter: this.refs.sendByEnter.getSelectedValue() }); this.onClose(); }; onKeyDown = event => { if (event.keyCode === KeyCodes.ESC) { event.preventDefault(); this.onClose(); } }; onLanguageChange = (event, selectedIndex, menuItem) => { this.setState({ language: menuItem.value, selectedLanguage: _.findIndex(menuItems, {value: menuItem.value}) }); }; render() { const preferences = this.state.preferences; if (this.state.isOpen === true) { return ( <Modal className="modal-new modal-new--preferences" closeTimeoutMS={150} isOpen={this.state.isOpen} style={{width: 760}}> <div className="modal-new__header"> <i className="modal-new__header__icon material-icons">settings</i> <h3 className="modal-new__header__title"> <FormattedMessage message={this.getIntlMessage('preferencesModalTitle')}/> </h3> <div className="pull-right"> <FlatButton hoverColor="rgba(81,145,219,.17)" label="Done" labelStyle={{padding: '0 8px'}} onClick={this.onDone} secondary={true} style={{marginTop: -6}}/> </div> </div> <div className="modal-new__body"> <div className="preferences"> <aside className="preferences__tabs"> <a className="preferences__tabs__tab preferences__tabs__tab--active">General</a> <a className="preferences__tabs__tab hide">Notifications</a> <a className="preferences__tabs__tab hide">Sidebar colors</a> <a className="preferences__tabs__tab hide">Security</a> <a className="preferences__tabs__tab hide">Other Options</a> </aside> <div className="preferences__body"> <div className="preferences__list"> <div className="preferences__list__item preferences__list__item--general"> <ul> <li> <i className="icon material-icons">keyboard</i> <RadioButtonGroup defaultSelected={preferences.sendByEnter} name="send" ref="sendByEnter"> <RadioButton label="Enter – send message, Shift + Enter – new line" style={{marginBottom: 12}} value="true"/> <RadioButton label="Cmd + Enter – send message, Enter – new line" value="false"/> </RadioButtonGroup> </li> <li className="language hide"> <i className="icon material-icons">menu</i> Language: <DropDownMenu labelStyle={{color: '#5191db'}} menuItemStyle={{height: '40px', lineHeight: '40px'}} menuItems={menuItems} onChange={this.onLanguageChange} selectedIndex={this.state.selectedLanguage} style={{verticalAlign: 'top', height: 52}} underlineStyle={{display: 'none'}}/> </li> </ul> </div> <div className="preferences__list__item preferences__list__item--notifications hide"> <ul> <li> <i className="icon material-icons">notifications</i> <RadioButtonGroup defaultSelected="all" name="notifications"> <RadioButton label="Notifications for activity of any kind" style={{marginBottom: 12}} value="all"/> <RadioButton label="Notifications for Highlight Words and direct messages" style={{marginBottom: 12}} value="quiet"/> <RadioButton label="Never send me notifications" style={{marginBottom: 12}} value="disable"/> </RadioButtonGroup> <p className="hint"> You can override your desktop notification preference on a case-by-case basis for channels and groups from the channel or group menu. </p> </li> </ul> </div> </div> </div> </div> </div> </Modal> ); } else { return null; } } } export default PreferencesModal;
src/containers/Root.js
dont-fear-the-repo/fear-the-repo
import React from 'react'; import { Provider } from 'react-redux'; import routes from '../routes'; import { ReduxRouter } from 'redux-router'; import DevTools from './DevTools'; import { createDevToolsWindow } from '../utils'; import HTML5Backend from 'react-dnd-html5-backend'; import { DragDropContext } from 'react-dnd'; @DragDropContext(HTML5Backend) export default class Root extends React.Component { static propTypes = { store: React.PropTypes.object.isRequired, debug: React.PropTypes.bool, debugExternal: React.PropTypes.bool } static defaultProps = { debug: false, debugExternal: false } renderDevTools() { if (!this.props.debug) { return null; } return this.props.debugExternal ? createDevToolsWindow(this.props.store) : <DevTools />; } render() { return ( <Provider store={this.props.store}> <div> <ReduxRouter> {routes} </ReduxRouter> {this.renderDevTools()} </div> </Provider> ); } }
src/components/Embedded/intellijoe.js
pritchardtw/ReactPersonalSite
import React, { Component } from 'react'; import Project from '../project'; export default class IntelliJoe extends Component { render() { const images = [ "../../static/images/embedded/intellijoe/blockdiagram.png" ]; return( <Project title="Intelli Joe!" description="I participated in a Milwaukee Hackathon with my co-workers. In addition to myself, we had another Software Engineer, an Electrical Engineer, and a Mechanical Engineer. We won the “Nerdiest Project”. I picked out all the hardware for the project and coded some Python scripts used to toggle the Raspberry Pi GPIO. The goal was to create an IoT coffee pot. We wanted to be able to turn the pot on before leaving for the office, so by the time we arrived we would have hot coffee waiting for us. A secondary feature is that we could also turn the pot off from home in case we forgot to at the end of the day. During the 8 hour hackathon we achieved the ability to turn the pot on and off via a cell phone. This proof of concept proved out our digital datapath infrastructure. At that point we were only limited by whatever sensors we wanted to harness to the coffee pot. Some value add features we wanted were -Temperature Sensor - to gauge hotness -Force Sensor - to gauge fullness -Optical Sensor - to gauge fullness should the force sensor not work so well (because the coffee pot weighs the same whether the waters in the pot or the reservoir.) -Switch - to gauge if the pot is in the coffee maker or currently gone." images={images} /> ); } }
src/svg-icons/device/signal-wifi-0-bar.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalWifi0Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z"/> </SvgIcon> ); DeviceSignalWifi0Bar = pure(DeviceSignalWifi0Bar); DeviceSignalWifi0Bar.displayName = 'DeviceSignalWifi0Bar'; export default DeviceSignalWifi0Bar;
app/components/Component1/StaticMap.js
joaquinPega/ReactTutorial
import React from 'react'; import { StyleSheet, View, Text, Dimensions, ScrollView, } from 'react-native'; import MapView from 'react-native-maps'; const { width, height } = Dimensions.get('window'); const ASPECT_RATIO = width / height; const LATITUDE = 37.78825; const LONGITUDE = -122.4324; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; class StaticMap extends React.Component { constructor(props) { super(props); this.state = { region: { latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }, }; } render() { return ( <View style={styles.container}> <ScrollView style={StyleSheet.absoluteFill} contentContainerStyle={styles.scrollview} > <Text>Clicking</Text> <Text>and</Text> <Text>dragging</Text> <Text>the</Text> <Text>map</Text> <Text>will</Text> <Text>cause</Text> <Text>the</Text> <MapView provider={this.props.provider} style={styles.map} scrollEnabled={false} zoomEnabled={false} pitchEnabled={false} rotateEnabled={false} initialRegion={this.state.region} > <MapView.Marker title="This is a title" description="This is a description" coordinate={this.state.region} /> </MapView> <Text>parent</Text> <Text>ScrollView</Text> <Text>to</Text> <Text>scroll.</Text> <Text>When</Text> <Text>using</Text> <Text>a Google</Text> <Text>Map</Text> <Text>this only</Text> <Text>works</Text> <Text>if you</Text> <Text>disable:</Text> <Text>scroll,</Text> <Text>zoom,</Text> <Text>pitch,</Text> <Text>rotate.</Text> <Text>...</Text> <Text>It</Text> <Text>would</Text> <Text>be</Text> <Text>nice</Text> <Text>to</Text> <Text>have</Text> <Text>an</Text> <Text>option</Text> <Text>that</Text> <Text>still</Text> <Text>allows</Text> <Text>zooming.</Text> </ScrollView> </View> ); } } StaticMap.propTypes = { provider: MapView.ProviderPropType, }; const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'flex-end', alignItems: 'center', }, scrollview: { alignItems: 'center', paddingVertical: 40, }, map: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, }, }); module.exports = StaticMap;
stories/base/switch.story.js
WellerQu/rongcapital-ui
import React from 'react'; import { storiesOf } from '@storybook/react'; import { Switch } from '../../src/base'; storiesOf('base.Switch', module) .add('initialize by default', () => ( <Switch /> )) .add('initialize switch defaults isOpen true', () => ( <Switch width={80} height={20} isOpen={true} /> )) .add('initialize switch defaults disabled true', () => ( <Switch width={80} height={20} disabled={true} /> ));
app/javascript/mastodon/features/report/components/status_check_box.js
unarist/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Toggle from 'react-toggle'; import noop from 'lodash/noop'; import StatusContent from '../../../components/status_content'; import { MediaGallery, Video } from '../../ui/util/async-components'; import Bundle from '../../ui/components/bundle'; export default class StatusCheckBox extends React.PureComponent { static propTypes = { status: ImmutablePropTypes.map.isRequired, checked: PropTypes.bool, onToggle: PropTypes.func.isRequired, disabled: PropTypes.bool, }; render () { const { status, checked, onToggle, disabled } = this.props; let media = null; if (status.get('reblog')) { return null; } if (status.get('media_attachments').size > 0) { if (status.get('media_attachments').some(item => item.get('type') === 'unknown')) { } else if (status.getIn(['media_attachments', 0, 'type']) === 'video') { const video = status.getIn(['media_attachments', 0]); media = ( <Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} > {Component => ( <Component preview={video.get('preview_url')} src={video.get('url')} width={239} height={110} inline sensitive={status.get('sensitive')} onOpenVideo={noop} /> )} </Bundle> ); } else { media = ( <Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery} > {Component => <Component media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={noop} />} </Bundle> ); } } return ( <div className='status-check-box'> <div className='status-check-box__status'> <StatusContent status={status} /> {media} </div> <div className='status-check-box-toggle'> <Toggle checked={checked} onChange={onToggle} disabled={disabled} /> </div> </div> ); } }
src/svg-icons/navigation/menu.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationMenu = (props) => ( <SvgIcon {...props}> <path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/> </SvgIcon> ); NavigationMenu = pure(NavigationMenu); NavigationMenu.displayName = 'NavigationMenu'; NavigationMenu.muiName = 'SvgIcon'; export default NavigationMenu;