path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
tests/react_custom_funs/clone_element.js
MichaelDeBoey/flow
// @flow import React from 'react'; import type {Element} from 'react'; declare var any: any; class A extends React.Component<{foo: number}, void> {} class B extends React.Component<{foo: number, bar: number}, void> {} class C extends React.Component<{children: number}, void> {} class D extends React.Component<{children: Array<number>}, void> {} class E extends React.Component<{foo: number, bar: number}, void> { static defaultProps = {bar: 42}; } declare var a: Element<Class<A>>; declare var b: Element<Class<B>>; declare var c: Element<Class<C>>; declare var d: Element<Class<D>>; declare var e: Element<Class<E>>; React.cloneElement(); // Error: Needs a minimum of two arguments. React.cloneElement('nope'); // Error: Not a valid element type. React.cloneElement({ type: any }); // Error: Not a valid element type. React.cloneElement(a); // OK: `a` is an element. (React.cloneElement(a).type: Class<A>); // OK: `a` has a type of `A`. (React.cloneElement(a).type: Class<B>); // Error: `a` has a type of `A`. (React.cloneElement(a).props.foo: number); // OK (React.cloneElement(a).props.bar: empty); // Error: `bar` does not exist. (React.cloneElement(a).props.foo: string); // Error: `foo` is number. (React.cloneElement(b).props.foo: number); // OK (React.cloneElement(b).props.bar: number); // OK (React.cloneElement(b).props.foo: string); // Error: `foo` is number. React.cloneElement(a, {}); // OK React.cloneElement(a, undefined); // OK React.cloneElement(a, null); // OK React.cloneElement(a, {foo: 1}); // OK React.cloneElement(a, {foo: 1, bar: 2}); // OK React.cloneElement(a, {foo: '1'}); // Error: `foo` is a number. React.cloneElement(b, {}); // OK React.cloneElement(b, undefined); // OK React.cloneElement(b, null); // OK React.cloneElement(b, {foo: 1}); // OK React.cloneElement(b, {foo: 1, bar: 2}); // OK React.cloneElement(b, {foo: '1'}); // Error: `foo` is a number. React.cloneElement(c, {}); // OK React.cloneElement(c, undefined); // OK React.cloneElement(c, null); // OK React.cloneElement(c, {children: 42}); // OK React.cloneElement(c, {children: '42'}); // Error: `children` is a number. React.cloneElement(c, {}, 42); // OK React.cloneElement(c, undefined, 42); // OK React.cloneElement(c, null, 42); // OK React.cloneElement(c, {}, 1, 2, 3); // Error: `children` is not an array. React.cloneElement(c, undefined, 1, 2, 3); // Error: `children` is not an array. React.cloneElement(c, null, 1, 2, 3); // Error: `children` is not an array. React.cloneElement(c, {}, ...[]); // OK React.cloneElement(d, {}); // OK React.cloneElement(d, {children: 42}); // Error: `children` is an array. React.cloneElement(d, {children: [1, 2, 3]}); // OK React.cloneElement(d, {}, 42); // Error: `children` is an array. React.cloneElement(d, undefined, 42); // Error: `children` is an array. React.cloneElement(d, null, 42); // Error: `children` is an array. React.cloneElement(d, {}, 1, 2, 3); // OK React.cloneElement(d, undefined, 1, 2, 3); // OK React.cloneElement(d, null, 1, 2, 3); // OK React.cloneElement(e, {}); // OK React.cloneElement(e, {foo: 1}); // OK React.cloneElement(e, {foo: 1, bar: 2}); // OK React.cloneElement(e, {foo: undefined, bar: 2}); // Error: undefined ~> number React.cloneElement(e, {foo: 1, bar: undefined}); // OK: `bar` has a default.
app/javascript/mastodon/components/domain.js
primenumber/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import IconButton from './icon_button'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unblock domain {domain}' }, }); export default @injectIntl class Account extends ImmutablePureComponent { static propTypes = { domain: PropTypes.string, onUnblockDomain: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleDomainUnblock = () => { this.props.onUnblockDomain(this.props.domain); } render () { const { domain, intl } = this.props; return ( <div className='domain'> <div className='domain__wrapper'> <span className='domain__domain-name'> <strong>{domain}</strong> </span> <div className='domain__buttons'> <IconButton active icon='unlock' title={intl.formatMessage(messages.unblockDomain, { domain })} onClick={this.handleDomainUnblock} /> </div> </div> </div> ); } }
src/svg-icons/hardware/keyboard-arrow-left.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardArrowLeft = (props) => ( <SvgIcon {...props}> <path d="M15.41 16.09l-4.58-4.59 4.58-4.59L14 5.5l-6 6 6 6z"/> </SvgIcon> ); HardwareKeyboardArrowLeft = pure(HardwareKeyboardArrowLeft); HardwareKeyboardArrowLeft.displayName = 'HardwareKeyboardArrowLeft'; HardwareKeyboardArrowLeft.muiName = 'SvgIcon'; export default HardwareKeyboardArrowLeft;
src/frontend/index.js
resummed/resummed
import React from 'react'; import { compose } from 'recompose'; import { Provider, connect } from 'react-redux'; import { Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import configureRoutes from './configureRoutes'; import 'frontend/static/favicon.ico'; const withStore = Component => ({ ...props, store }) => ( <Provider store={store}> <Component {...props} /> </Provider> ); const renderApp = ({ store }) => ( <Router history={syncHistoryWithStore(browserHistory, store)} routes={configureRoutes()} /> ); const App = compose( withStore, )(renderApp); export default App;
fields/explorer/field.js
matthieugayon/keystone
import Domify from 'react-domify'; import React from 'react'; import Markdown from 'react-markdown'; const Row = (props) => { const styles = { display: 'flex', flexWrap: 'wrap', marginLeft: -10, marginRight: -10, ...props.style, }; return ( <div {...props} className={props.className || 'Row'} style={styles} /> ); }; const Col = (props) => { const styles = { flex: props.width ? null : '1 1 0', minHeight: 1, paddingLeft: 10, paddingRight: 10, width: props.width || '100%', ...props.style, }; return ( <div {...props} className={props.className || 'Col'} style={styles} /> ); }; const ExplorerFieldType = React.createClass({ getInitialState () { return { readmeIsVisible: !!this.props.readme, filter: this.props.FilterComponent.getDefaultValue(), value: this.props.value, }; }, componentWillReceiveProps (newProps) { if (this.props.params.type === newProps.params.type) return; this.setState({ filter: newProps.FilterComponent.getDefaultValue(), readmeIsVisible: newProps.readme ? this.state.readmeIsVisible : false, value: newProps.value, }); }, onFieldChange (e) { var logValue = typeof e.value === 'string' ? `"${e.value}"` : e.value; console.log(`${this.props.params.type} field value changed:`, logValue); this.setState({ value: e.value, }); }, onFilterChange (value) { console.log(`${this.props.params.type} filter value changed:`, value); this.setState({ filter: value, }); }, render () { const { FieldComponent, FilterComponent, readme, spec, toggleSidebar } = this.props; const { readmeIsVisible } = this.state; return ( <div className="fx-page"> <div className="fx-page__header"> <div className="fx-page__header__title"> <button className="fx-page__header__button fx-page__header__button--sidebar mega-octicon octicon-three-bars" onClick={toggleSidebar} type="button" /> {spec.label} </div> {!!readme && ( <button className="fx-page__header__button fx-page__header__button--readme mega-octicon octicon-file-text" onClick={() => this.setState({ readmeIsVisible: !readmeIsVisible })} title={readmeIsVisible ? 'Hide Readme' : 'Show Readme'} type="button" /> )} </div> <div className="fx-page__content"> <Row> <Col> <div className="fx-page__content__inner"> <div className="fx-page__field"> <Row> <Col width={readmeIsVisible ? 300 : null} style={{ minWidth: 300, maxWidth: 640 }}> <FieldComponent {...spec} onChange={this.onFieldChange} value={this.state.value} /> </Col> <Col> <div style={{ marginLeft: 30, marginTop: 26 }}> <Domify className="Domify" value={{ value: this.state.value }} /> </div> </Col> </Row> </div> <div className="fx-page__filter"> <div className="fx-page__filter__title">Filter</div> <Row> <Col width={300}> <FilterComponent field={spec} filter={this.state.filter} onChange={this.onFilterChange} /> </Col> <Col> <div style={{ marginLeft: 30 }}> <Domify className="Domify" value={this.state.filter} /> </div> </Col> </Row> </div> </div> </Col> {!!readmeIsVisible && ( <Col width={380}> <Markdown className="Markdown" source={readme} /> </Col> )} </Row> </div> </div> ); }, }); module.exports = ExplorerFieldType;
src/svg-icons/av/queue-music.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvQueueMusic = (props) => ( <SvgIcon {...props}> <path d="M15 6H3v2h12V6zm0 4H3v2h12v-2zM3 16h8v-2H3v2zM17 6v8.18c-.31-.11-.65-.18-1-.18-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3V8h3V6h-5z"/> </SvgIcon> ); AvQueueMusic = pure(AvQueueMusic); AvQueueMusic.displayName = 'AvQueueMusic'; AvQueueMusic.muiName = 'SvgIcon'; export default AvQueueMusic;
src/parser/ui/Panel.js
anom0ly/WoWAnalyzer
import { Panel as InterfacePanel, ErrorBoundary } from 'interface'; import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY'; import PropTypes from 'prop-types'; import React from 'react'; const Panel = ({ category = STATISTIC_CATEGORY.PANELS, position, ...others }) => ( <ErrorBoundary> <InterfacePanel {...others} /> </ErrorBoundary> ); Panel.propTypes = { children: PropTypes.node.isRequired, // eslint-disable-next-line react/no-unused-prop-types category: PropTypes.oneOf(Object.values(STATISTIC_CATEGORY)), // eslint-disable-next-line react/no-unused-prop-types position: PropTypes.number, }; Panel.defaultProps = { category: STATISTIC_CATEGORY.PANELS, }; export default Panel;
src/components/__tests__/PageDropdownTest.js
joellanciaux/Griddle
import 'jsdom-global/register'; import React from 'react'; import test from 'ava'; import { shallow, mount } from 'enzyme'; import PageDropdown from '../PageDropdown'; // TODO: This whole test is pretty bad. I couldn't get the matches element working with option for some reason test('renders with style', (t) => { const style = { backgroundColor: '#EDEDED' }; const wrapper = shallow(<PageDropdown style={style} />); t.is(wrapper.node.type, 'select'); t.is(wrapper.node.props.style, style); }); test('renders with className', (t) => { const wrapper = shallow(<PageDropdown className="className" />); t.is(wrapper.node.type, 'select'); t.is(wrapper.node.props.className, 'className'); }); test('renders with option element at page 0 if no pages provided', (t) => { const wrapper = shallow(<PageDropdown />); const option = wrapper.childAt(0); t.is(option.html(), '<option value="0">0</option>'); }); test('renders with as many option elements as max pages', (t) => { const wrapper = shallow(<PageDropdown maxPages={10} />); t.is(wrapper.children().length, 10); }); test('renders at selected page', (t) => { // using mount because attempting to get selectedIndex later on const wrapper = mount(<PageDropdown currentPage={3} maxPages={10} />); const select = wrapper.find('select').node; t.is(select.selectedIndex, 2); }); test('fires set page event', (t) => { let changed = false; const onChange = () => { changed = true; }; const wrapper = mount(<PageDropdown currentPage={0} maxPages={10} setPage={onChange} />); wrapper.simulate('change', { target: { value: 3 } }); t.true(changed); });
5-use-firebase/src/pages/Login.js
pirosikick/react-hands-on-20171023
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import * as firebase from 'firebase'; /** * ログインページ */ class Login extends Component { static propTypes = { history: PropTypes.shape({ replace: PropTypes.func.isRequired, }).isRequired, }; state = { error: false, }; componentDidMount() { const user = firebase.auth().currentUser; if (user) { // ログイン済みの場合はリダイレクト this.props.history.replace('/'); } } handleClick = () => { // Google認証のダイアログを開く const provider = new firebase.auth.GoogleAuthProvider(); firebase .auth() .signInWithPopup(provider) .then((/* result */) => { // 認証完了 // result.userからログイン情報を取得可能 this.props.history.replace('/'); }) .catch(err => { // 認証エラー console.log('failed to log in', err); this.setState({ error: true }); }); }; render() { const { error } = this.state; return ( <div> {error ? <p>ログインエラー</p> : ''} <button onClick={this.handleClick}>Googleアカウントでログイン</button> </div> ); } } export default Login;
src/Game/UI/Panel/Component/Close.js
digijin/space-station-sim
//@flow import React from 'react' type Props = { close:Function } export default class Close extends React.Component{ props:Props render(){ return <div className='close' onClick={this.props.close}>X</div> } }
writeExampleWebpack2/src/js/contains/AddTodo.js
fengnovo/webpack-react
import React from 'react' import { connect } from 'react-redux' import { ADD } from '../actions' let AddTodo = ({dispatch}) => { //来自props的,参数要加花括号 let input return <div> <form onSubmit={e=>{ e.preventDefault() if(!input.value.trim()){ return } dispatch(ADD(input.value)) input.value = '' }}> <input ref={node=>{input=node}}/> <button type="submit">添加</button> </form> </div> } AddTodo = connect()(AddTodo); export default AddTodo
static/src/containers/PieGraph.js
eltrufas/cosmico
import React from 'react'; import connectToDataPoints from '../connectToDataPoints'; import {Chart} from 'react-google-charts'; const unsusedColors = [ '#2196F3', '#F44336', '#FF9800', '#4CAF50' ] const PieGraph = ({ sensorsObj, totals, sensors, key }) => { const rows = sensors .map((sensorId, idx) => [ sensorsObj[sensorId] ? sensorsObj[sensorId].name : 'Cargando', totals[sensorId] ? totals[sensorId] : 0 ]); return ( <div className={"full-height"}> <Chart chartType="PieChart" data={[['Sensor', 'Frecuencia']].concat(rows)} options={{ colors: unsusedColors, animation:{ duration: 2000, easing: 'inAndOut', }, }} graph_id={key} width="100%" height="100%" legend_toggle /> </div> ); } export default connectToDataPoints(PieGraph);
packages/web/src/components/result/addons/Results.js
appbaseio/reactivesearch
import React from 'react'; import { getClassName } from '@appbaseio/reactivecore/lib/utils/helper'; import types from '@appbaseio/reactivecore/lib/utils/types'; import ImpressionTracker from './ImpressionTracker'; const Results = ({ filteredResults, hasCustomRender, listClass, innerClass, renderItem, triggerClickAnalytics, base, analytics, getComponent, }) => { const resultElement = () => (hasCustomRender ? ( getComponent() ) : ( <div className={`${listClass} ${getClassName(innerClass, 'list')}`}> {filteredResults.map((item, index) => renderItem(item, () => { triggerClickAnalytics(base + index); }), )} </div> )); // If analytics is set to true then render with impression tracker if (analytics) { return <ImpressionTracker hits={filteredResults}>{resultElement()}</ImpressionTracker>; } return resultElement(); }; Results.propTypes = { hasCustomRender: types.boolRequired, innerClass: types.style, renderItem: types.func, base: types.number, getComponent: types.func, listClass: types.string, filteredResults: types.hits, triggerClickAnalytics: types.func, analytics: types.bool, }; export default Results;
ui/src/Mining.js
halilozercan/halocoin
import React, { Component } from 'react'; import Balance from './widgets/balance.js'; import Address from './widgets/address.js'; import Send from './widgets/send.js'; import Miner from './widgets/miner.js'; import Power from './widgets/power.js'; import Stake from './widgets/stake.js'; import JobListing from './widgets/job_listing.js'; class Mining extends Component { render() { return ( <div className="container-fluid" style={{marginTop:16, marginBottom:64}}> <div className="row" style={{marginBottom:16}}> <div className="col-lg-6 col-md-6 col-sm-6"> <Miner notify={this.props.notify} /> </div> <div className="col-lg-6 col-md-6 col-sm-6"> <Power socket={this.props.socket}/> </div> </div> <div className="row"> <div className="col-lg-12 col-md-12 col-sm-12"> <Stake wallet={this.props.default_wallet} notify={this.props.notify}/> </div> </div> <div className="row"> <JobListing notify={this.props.notify}/> </div> </div> ); } } export default Mining;
src/js/OrderCompleted.js
merlox/dapp-transactions
import React from 'react' import Header from './Header' import {Link} from 'react-router-dom' import './../stylus/index.styl' import './../stylus/ordersentpage.styl' import LINKS from './utils.js' class OrderSentPage extends React.Component { constructor(props) { super(props) } render(){ return ( <div style={{height: '100%'}}> <div className="order-sent-container"> <img src={LINKS.baseUrl + "img/order-sent/check-last.png"} /> <h1>Transaction Accepted and Funds to be Released</h1> <div className="order-sent-buttons-container"> <Link to={LINKS.home} onClick={() => this.props.showRetailers()} className="order-sent-back">Back to Login</Link> </div> </div> </div> ) } } export default OrderSentPage
src/LeaderboardSeparator1/index.js
christianalfoni/ducky-components
import React from 'react'; import PropTypes from 'prop-types'; import Icon from '../Icon'; import Spacer from '../Spacer'; import styles from './styles.css'; function LeaderboardSeparator1() { return ( <div className={styles.wrapper}> <Spacer size="double" /> <div className={styles.iconWrapper}> <Icon className={styles.icon} icon="icon-dots-vertical" /> </div> </div> ); } export default LeaderboardSeparator1;
client/my-sites/drafts/controller.js
tinkertinker/wp-calypso
/** * External Dependencies */ import React from 'react'; import i18n from 'i18n-calypso'; /** * Internal Dependencies */ import sitesFactory from 'lib/sites-list'; import route from 'lib/route'; import { setDocumentHeadTitle as setTitle } from 'state/document-head/actions'; import { renderWithReduxStore } from 'lib/react-helpers'; const sites = sitesFactory(); module.exports = { drafts: function( context ) { var Drafts = require( 'my-sites/drafts/main' ), siteID = route.getSiteFragment( context.path ); // FIXME: Auto-converted from the Flux setTitle action. Please use <DocumentHead> instead. context.store.dispatch( setTitle( i18n.translate( 'Drafts', { textOnly: true } ) ) ); renderWithReduxStore( React.createElement( Drafts, { siteID: siteID, sites: sites, trackScrollPage: function() {} } ), document.getElementById( 'primary' ), context.store ); } };
assets/jqwidgets/jqwidgets-react/react_jqxlineargauge.js
juannelisalde/holter
/* jQWidgets v4.5.4 (2017-June) Copyright (c) 2011-2017 jQWidgets. License: http://jqwidgets.com/license/ */ import React from 'react'; const JQXLite = window.JQXLite; export default class JqxLinearGauge extends React.Component { componentDidMount() { let options = this.manageAttributes(); this.createComponent(options); }; manageAttributes() { let properties = ['animationDuration','background','colorScheme','disabled','easing','height','int64','labels','min','max','orientation','pointer','rangesOffset','rangeSize','ranges','showRanges','scaleStyle','scaleLength','ticksOffset','ticksPosition','ticksMinor','ticksMajor','value','width','disable','enable']; let options = {}; for(let item in this.props) { if(item === 'settings') { for(let itemTwo in this.props[item]) { options[itemTwo] = this.props[item][itemTwo]; } } else { if(properties.indexOf(item) !== -1) { options[item] = this.props[item]; } } } return options; }; createComponent(options) { if(!this.style) { for (let style in this.props.style) { JQXLite(this.componentSelector).css(style, this.props.style[style]); } } if(this.props.className !== undefined) { let classes = this.props.className.split(' '); for (let i = 0; i < classes.length; i++ ) { JQXLite(this.componentSelector).addClass(classes[i]); } } if(!this.template) { JQXLite(this.componentSelector).html(this.props.template); } JQXLite(this.componentSelector).jqxLinearGauge(options); }; setOptions(options) { JQXLite(this.componentSelector).jqxLinearGauge('setOptions', options); }; getOptions() { if(arguments.length === 0) { throw Error('At least one argument expected in getOptions()!'); } let resultToReturn = {}; for(let i = 0; i < arguments.length; i++) { resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxLinearGauge(arguments[i]); } return resultToReturn; }; on(name,callbackFn) { JQXLite(this.componentSelector).on(name,callbackFn); }; off(name) { JQXLite(this.componentSelector).off(name); }; animationDuration(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('animationDuration', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('animationDuration'); } }; background(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('background', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('background'); } }; colorScheme(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('colorScheme', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('colorScheme'); } }; disabled(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('disabled', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('disabled'); } }; easing(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('easing', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('easing'); } }; height(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('height', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('height'); } }; int64(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('int64', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('int64'); } }; labels(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('labels', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('labels'); } }; min(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('min', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('min'); } }; max(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('max', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('max'); } }; orientation(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('orientation', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('orientation'); } }; pointer(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('pointer', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('pointer'); } }; rangesOffset(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('rangesOffset', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('rangesOffset'); } }; rangeSize(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('rangeSize', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('rangeSize'); } }; ranges(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('ranges', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('ranges'); } }; showRanges(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('showRanges', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('showRanges'); } }; scaleStyle(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('scaleStyle', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('scaleStyle'); } }; scaleLength(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('scaleLength', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('scaleLength'); } }; ticksOffset(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('ticksOffset', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('ticksOffset'); } }; ticksPosition(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('ticksPosition', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('ticksPosition'); } }; ticksMinor(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('ticksMinor', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('ticksMinor'); } }; ticksMajor(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('ticksMajor', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('ticksMajor'); } }; value(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('value', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('value'); } }; width(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('width', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('width'); } }; disable(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('disable', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('disable'); } }; enable(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('enable', arg) } else { return JQXLite(this.componentSelector).jqxLinearGauge('enable'); } }; val(value) { if (value !== undefined) { JQXLite(this.componentSelector).jqxLinearGauge('val', value) } else { return JQXLite(this.componentSelector).jqxLinearGauge('val'); } }; render() { let id = 'jqxLinearGauge' + JQXLite.generateID(); this.componentSelector = '#' + id; return ( <div id={id}>{this.props.value}{this.props.children}</div> ) }; };
demo/client/AppWithStateless.js
gadicc/meteor-react-hotloader
import React, { Component } from 'react'; import Stateless from './Stateless'; export class AppWithStateless extends Component { render() { return ( <div>Stateless: <Stateless prop1={14} prop2={"z"} /> </div> ); } }
packages/mineral-ui-icons/src/IconRoomService.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconRoomService(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M2 17h20v2H2zm11.84-9.21A2.006 2.006 0 0 0 12 5a2.006 2.006 0 0 0-1.84 2.79C6.25 8.6 3.27 11.93 3 16h18c-.27-4.07-3.25-7.4-7.16-8.21z"/> </g> </Icon> ); } IconRoomService.displayName = 'IconRoomService'; IconRoomService.category = 'places';
app/components/About.js
RoadToGlobal/ClientDistro
import React from 'react'; const About = () => <div> Just a crummy page to showcase react-router! </div>; export default About;
src/svg-icons/device/battery-50.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery50 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V13h10V5.33z"/><path d="M7 13v7.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13H7z"/> </SvgIcon> ); DeviceBattery50 = pure(DeviceBattery50); DeviceBattery50.displayName = 'DeviceBattery50'; DeviceBattery50.muiName = 'SvgIcon'; export default DeviceBattery50;
packages/material-ui-icons/src/DeveloperBoard.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let DeveloperBoard = props => <SvgIcon {...props}> <path d="M22 9V7h-2V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-2h2v-2h-2v-2h2v-2h-2V9h2zm-4 10H4V5h14v14zM6 13h5v4H6zm6-6h4v3h-4zM6 7h5v5H6zm6 4h4v6h-4z" /> </SvgIcon>; DeveloperBoard = pure(DeveloperBoard); DeveloperBoard.muiName = 'SvgIcon'; export default DeveloperBoard;
node_modules/react-bootstrap/es/InputGroup.js
cmccandless/SolRFrontEnd
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 InputGroupAddon from './InputGroupAddon'; import InputGroupButton from './InputGroupButton'; import { bsClass, bsSizes, getClassSet, splitBsProps } from './utils/bootstrapUtils'; import { Size } from './utils/StyleConfig'; var InputGroup = function (_React$Component) { _inherits(InputGroup, _React$Component); function InputGroup() { _classCallCheck(this, InputGroup); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } InputGroup.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('span', _extends({}, elementProps, { className: classNames(className, classes) })); }; return InputGroup; }(React.Component); InputGroup.Addon = InputGroupAddon; InputGroup.Button = InputGroupButton; export default bsClass('input-group', bsSizes([Size.LARGE, Size.SMALL], InputGroup));
js/app.js
paulbevis/teamcity-build-monitor
import App from './containers/App'; import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( <App/>, document.getElementById('root') );
client/src/app/routes/settings/containers/Students/StudentControl.js
zraees/sms-project
import React from 'react' import axios from 'axios' import classNames from 'classnames' import {getLangKey, instanceAxios} from '../../../../components/utils/functions' import Msg from '../../../../components/i18n/Msg' class StudentControl extends React.Component { constructor(props){ super(props); this.state = { student: {}, key: getLangKey() } this.getStudent = this.getStudent.bind(this); } componentDidMount() { console.log('componentDidMount --> StudentControl'); this.getStudent(this.props); } getStudent(props){ var shiftId, classId, sectionId, batchId, studentId; //let key = getLangKey(); shiftId = props.shiftId ? props.shiftId : 0; classId = props.classId ? props.classId : 0; sectionId = props.sectionId ? props.sectionId : 0; batchId = props.batchId ? props.batchId : 0; studentId = props.studentId ? props.studentId : 0; //console.log('sdasd'); instanceAxios.get('/api/GetStudentControlData/' + this.state.key + '/' + shiftId + '/' + classId + '/' + sectionId + '/' + batchId + '/' + studentId) .then(res => { //console.log('sdas asd d', res.data); const student = res.data; this.setState({ student }); }); } shouldComponentUpdate(nextProps, nextState) { //const { batchId, sectionId, classId, shiftId, studentId } = this.props; //const { nbatchId, nsectionId, nclassId, nshiftId, nstudentId } = nextProps; // console.log('shouldComponentUpdate --> StudentControl',this.props.studentId != nextProps.nstudentId, studentId, nstudentId, nextState.student); // console.log('nextProps.studentId ', nextProps.studentId, nextProps); if (this.props.studentId != nextProps.studentId && nextProps.studentId) { //let key = getLangKey(); this.setState({ student: [] }); this.getStudent(nextProps); } return this.props.studentId != nextProps.nstudentId; } // render() { const { student } = this.state; return ( <div> <div className="well well-sm bg-color-teal txt-color-white text-center"><h5>StudentText</h5></div> <div className="well"> <div className="table-responsive"> <table className="table table-bordered table-striped"> <thead> <tr> <th><Msg phrase="CodeText" /></th> <th colSpan="2"><Msg phrase="FullNameText" /></th> <th>{student.StudentRollNo?<Msg phrase="RollNoText" />:""}</th> </tr> </thead> <tbody> <tr> <td>{student.StudentCode}</td> <td colSpan="2">{student.StudentName}</td> <td>{student.StudentRollNo}</td> </tr> <tr> <th><Msg phrase="BatchText" /></th> <th><Msg phrase="ShiftText" /></th> <th><Msg phrase="ClassText" /></th> <th><Msg phrase="SectionText" /></th> </tr> <tr> <td>{student.BatchName}</td> <td>{student.ShiftName}</td> <td>{student.ClassName}</td> <td>{student.SectionName}</td> </tr> </tbody> </table> </div> </div> </div> ) } } export default StudentControl
src/smart/workflow/EditableWorkflow.js
jeckhummer/wf-constructor
import React from 'react'; import {connect} from 'react-redux'; import {getWorkflowMatrix} from "../../selectors/workflow"; import {EditableWorkflowBlock} from "./EditableWorkflowBlock"; import {getSortedPhasesIds} from "../../selectors/phases"; import {getWorkflowTeamIds} from "../../selectors/teams"; import {WorkflowGrid} from "../../dumb/WorkflowGrid"; const mapStateToProps = (state) => { const sortedPhaseIds = getSortedPhasesIds(state); const sortedTeamIds = getWorkflowTeamIds(state); const workflow = getWorkflowMatrix(state); const matrix = workflow.map((row, teamIndex) => row.map((items, phaseIndex) => <EditableWorkflowBlock items={items} phaseId={sortedPhaseIds[phaseIndex]} teamId={sortedTeamIds[teamIndex]} /> ) ); return {matrix}; }; export const EditableWorkflow = connect(mapStateToProps)(WorkflowGrid);
src/routes/codes/List.js
yunqiangwu/kmadmin
import React from 'react' import PropTypes from 'prop-types' import { Table, Modal } from 'antd' import classnames from 'classnames' import { DropOption } from 'components' import { Link } from 'dva/router' import AnimTableBody from '../../components/DataTable/AnimTableBody' import styles from './List.less' const confirm = Modal.confirm const List = ({ onDeleteItem, onEditItem, isMotion, location, ...tableProps }) => { const handleMenuClick = (record, e) => { if (e.key === '1') { onEditItem(record) } else if (e.key === '2') { confirm({ title: 'Are you sure delete this record?', onOk () { onDeleteItem(record.lookupType) }, }) } } const columns = [ { title: '代码', dataIndex: 'lookupType', key: 'lookupType', render: (text, record) => <Link to={`/codes/values/${record.lookupType}`}>{text}</Link>, }, { title: '名称', dataIndex: 'name', key: 'name', }, { title: '描述', dataIndex: 'description', key: 'description', }, { title: '操作', key: 'operation', render: (text, record) => { return <DropOption onMenuClick={e => handleMenuClick(record, e)} menuOptions={[{ key: '1', name: '编辑' }, { key: '2', name: '删除' }]} /> }, }, ] const getBodyWrapperProps = { page: location.query.page, current: tableProps.pagination.current, } const getBodyWrapper = (body) => { return isMotion ? <AnimTableBody {...getBodyWrapperProps} body={body} /> : body } return ( <div> <Table {...tableProps} className={classnames({ [styles.table]: true, [styles.motion]: isMotion })} bordered onRowDoubleClick={(item) => { onEditItem(item) }} scroll={{ x: 1024 }} columns={columns} simple rowKey={record => record.lookupType} getBodyWrapper={getBodyWrapper} /> </div> ) } List.propTypes = { onDeleteItem: PropTypes.func, onEditItem: PropTypes.func, isMotion: PropTypes.bool, location: PropTypes.object, } export default List
src/SparklinesReferenceLine.js
borisyankov/react-sparklines
import PropTypes from 'prop-types'; import React from 'react'; import * as dataProcessing from './dataProcessing'; export default class SparklinesReferenceLine extends React.Component { static propTypes = { type: PropTypes.oneOf(['max', 'min', 'mean', 'avg', 'median', 'custom']), value: PropTypes.number, style: PropTypes.object }; static defaultProps = { type: 'mean', style: { stroke: 'red', strokeOpacity: .75, strokeDasharray: '2, 2' } }; render() { const { points, margin, type, style, value } = this.props; const ypoints = points.map(p => p.y); const y = type == 'custom' ? value : dataProcessing[type](ypoints); return ( <line x1={points[0].x} y1={y + margin} x2={points[points.length - 1].x} y2={y + margin} style={style} /> ) } }
app/src/index.js
oramics/synth-kit
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
src/main/resources/public/js/components/tabs.js
SICTIAM/ozwillo-portal
import React from 'react'; import PropTypes from 'prop-types'; class Tabs extends React.Component { static propTypes = { //Warning: Attributes of fields headers and tabs must be sames //ex headers { tab1: () => "toto", tab2: () => <h1>Toto 2</h1> } headers: PropTypes.object.isRequired, //ex tabs { tab1: () => "content", tab2: () => <section>content</section> } tabs: PropTypes.object.isRequired, //Name of attribute associate with the tab tabToDisplay: PropTypes.string }; render() { const tabToDisplay = this.props.tabToDisplay; const tabName = Object.keys(this.props.tabs).find(attr => { return attr === tabToDisplay; }); const Component = this.props.tabs[tabName]; return <section className={`tabs flex-col ${this.props.className || ''}`}> <header className="tabs-headers"> <ul className="headers-list undecorated-list flex-row"> { Object.keys(this.props.headers).map((tabName) => { const Component = this.props.headers[tabName]; return <li key={tabName} data-tab={tabName} className={`header ${(tabName === tabToDisplay && 'active') || ''}`}> <Component/> </li> }) } </ul> </header> <article className="tab-content"> {tabName && <Component/>} </article> </section> } } export default Tabs;
src/client/react/admin/views/ResponsesView/ResponseCheck.js
bwyap/ptc-amazing-g-race
import React from 'react'; import PropTypes from 'prop-types'; import autobind from 'core-decorators/es/autobind'; import DateFormat from 'dateformat'; import { graphql } from 'react-apollo'; import { withRouter } from 'react-router-dom'; import { Intent, Button, Collapse, Switch } from '@blueprintjs/core'; import { checkResponse } from '../../../../graphql/response'; import FormInput from '../../../../../../lib/react/components/forms/FormInput'; import NotificationToaster from '../../../components/NotificationToaster'; @graphql(checkResponse('ok'), { name: 'MutationCheckResponse' }) @withRouter @autobind class ResponseCheck extends React.Component { static propTypes = { response: PropTypes.shape({ _id: PropTypes.string.isRequired, responseValid: PropTypes.bool.isRequired, checked: PropTypes.bool.isRequired, retry: PropTypes.bool.isRequired, pointsAwarded: PropTypes.number.isRequired, comment: PropTypes.string.isRequired }).isRequired, refetchResponse: PropTypes.func.isRequired } state = { showCheckResponse: false, checkResponseLoading: false, checkResponseError: null, responseValid: this.props.response.responseValid, retry: this.props.response.retry, pointsAwarded: this.props.response.pointsAwarded, comment: this.props.response.comment } toggle(state) { return () => { this.setState((prevState) => { return { [state]: !prevState[state] }; }); } } onPointsAwardedChange(e) { this.setState({ pointsAwarded: e.target.value }); } onCommentChange(e) { this.setState({ comment: e.target.value }); } async submitCheckResponse() { try { this.setState({ checkResponseError: null, checkResponseLoading: true }); await this.props.MutationCheckResponse({ variables: { responseId: this.props.response._id, responseValid: this.state.responseValid, retry: this.state.retry, pointsAwarded: this.state.pointsAwarded, comment: this.state.comment } }); await this.props.refetchResponse(); // this.setState({ checkResponseLoading: false, showCheckResponse: false }); this.props.history.push('/admin/dashboard/responses'); } catch (err) { this.setState({ checkResponseLoading: false, checkResponseError: err.toString() }); if (!this.state.showCheckResponse) { NotificationToaster.show({ intent: Intent.DANGER, message: `Unable to modify response state: ${err.toString()}` }); } } } render() { let warning; if (this.props.response.checked) { warning = ( <div className='pt-callout pt-intent-warning pt-icon-warning-sign' style={{marginBottom:'1rem'}}> <h5>Response checked</h5> <div> This response has already been checked. Avoid modifying a checked response unless it is absolutely necessary. Team point correction will be applied upon saving the modification. </div> </div> ); } else { warning = ( <div className='pt-callout pt-intent-primary pt-icon-info-sign' style={{marginBottom:'1rem'}}> <h5>Modifying the response status</h5> <div> Modifying this response and saving it will apply the point change to the team and cause your verdict to be reflected on the user's dashboard. Please check your action is correct before proceeding. </div> </div> ); } return ( <div> <Button className='pt-fill' iconName={this.state.showCheckResponse?'chevron-down':'chevron-right'} text='Modify response status' onClick={this.toggle('showCheckResponse')}/> <Collapse isOpen={this.state.showCheckResponse}> <div style={{marginTop:'1rem',padding:'1rem',background:'#f5f5f5',borderRadius:'0.3rem'}}> { this.state.checkResponseError ? <div className='pt-callout pt-intent-danger pt-icon-error' style={{margin:'0.5rem 0'}}> <h5>Error</h5> {this.state.checkResponseError} </div> : null } {warning} <Switch checked={this.state.responseValid} label='Response valid' onChange={this.toggle('responseValid')} className='pt-large' disabled={this.state.checkResponseLoading}/> <Switch checked={this.state.retry} label='Retry' onChange={this.toggle('retry')} className='pt-large' disabled={this.state.checkResponseLoading}/> <div class='pt-form-group pt-inline' style={{marginBottom:'0.3rem'}}> <label class='pt-label' for='points'> Points Awarded </label> <div class='pt-form-content'> <div class='pt-input-group' style={{maxWidth:'5rem'}}> <input id='points' class='pt-input' type='text' value={this.state.pointsAwarded} onChange={this.onPointsAwardedChange} disabled={this.state.checkResponseLoading}/> </div> </div> </div> <FormInput id='comment' value={this.state.comment} onChange={this.onCommentChange} disabled={this.state.checkResponseLoading} label='Comment' helperText='Teams will see this comment on their response'/> <Button intent={Intent.DANGER} className='pt-fill' text='Save' onClick={this.submitCheckResponse} loading={this.state.checkResponseLoading}/> </div> </Collapse> </div> ); } } export default ResponseCheck;
client/scripts/components/content-clients.js
rubeniskov/web-palomasafe
import React from 'react'; export default class ContentClients extends React.Component { constructor(props) { super(props); } render() { return ( <section id="clients" className="e-block-null e-block-darkest" data-stellar-background-ratio="0.5"> <div className="container"> <div className="row partners"> <div className="col-xs-1"><img src="assets/custom/images/partners_01.png" className="img-responsive" alt="x"/></div> <div className="col-xs-1"><img src="assets/custom/images/partners_02.png" className="img-responsive" alt="x"/></div> <div className="col-xs-1"><img src="assets/custom/images/partners_03.png" className="img-responsive" alt="x"/></div> <div className="col-xs-1"><img src="assets/custom/images/partners_04.png" className="img-responsive" alt="x"/></div> <div className="col-xs-1"><img src="assets/custom/images/partners_05.png" className="img-responsive" alt="x"/></div> <div className="col-xs-1"><img src="assets/custom/images/partners_06.png" className="img-responsive" alt="x"/></div> <div className="col-xs-1"><img src="assets/custom/images/partners_07.png" className="img-responsive" alt="x"/></div> <div className="col-xs-1"><img src="assets/custom/images/partners_08.png" className="img-responsive" alt="x"/></div> <div className="col-xs-1"><img src="assets/custom/images/partners_09.png" className="img-responsive" alt="x"/></div> <div className="col-xs-1"><img src="assets/custom/images/partners_10.png" className="img-responsive" alt="x"/></div> <div className="col-xs-1"><img src="assets/custom/images/partners_11.png" className="img-responsive" alt="x"/></div> <div className="col-xs-1"><img src="assets/custom/images/partners_12.png" className="img-responsive" alt="x"/></div> </div> </div> </section> ); } }
src/components/form/LoginForm.js
jhameenaho/weather-demo
import React from 'react' import { Form, Field } from 'react-final-form' import './LoginForm.css' const LoginForm = props => { const onSubmit = values => { props.onSubmit(values) } return ( <Form onSubmit={onSubmit} render={({ handleSubmit }) => ( <form onSubmit={handleSubmit} className="Login-wrapper"> <Field name="username" placeholder="Username" component="input" type="text" className="Login-input" /> <Field name="password" placeholder="Password" component="input" type="password" className="Login-input" /> <button type="submit" className="Login-button">Login</button> </form> )} /> ) } export default LoginForm;
actor-apps/app-web/src/app/components/modals/MyProfile.react.js
yangchenghu/actor-platform
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ import React, { Component } from 'react'; import { Container } from 'flux/utils'; import Modal from 'react-modal'; import ActorClient from 'utils/ActorClient'; import { KeyCodes } from 'constants/ActorAppConstants'; import MyProfileActions from 'actions/MyProfileActionCreators'; import CropAvatarActionCreators from 'actions/CropAvatarActionCreators'; import MyProfileStore from 'stores/MyProfileStore'; import CropAvatarStore from 'stores/CropAvatarStore'; import AvatarItem from 'components/common/AvatarItem.react'; import CropAvatarModal from './CropAvatar.react.js'; import { Styles, TextField } from 'material-ui'; import ActorTheme from 'constants/ActorTheme'; const ThemeManager = new Styles.ThemeManager(); class MyProfile extends Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } static getStores = () => [MyProfileStore, CropAvatarStore]; static calculateState() { return { profile: MyProfileStore.getProfile(), name: MyProfileStore.getName(), nick: MyProfileStore.getNick(), about: MyProfileStore.getAbout(), isOpen: MyProfileStore.isModalOpen(), isCropModalOpen: CropAvatarStore.isOpen() }; } componentWillMount() { ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ textField: { textColor: 'rgba(0,0,0,.87)', focusColor: '#68a3e7', backgroundColor: 'transparent', borderColor: '#68a3e7', disabledTextColor: 'rgba(0,0,0,.4)' } }); } componentWillUpdate(nextProps, nextState) { if ((nextState.isOpen && !this.state.isOpen) || (this.state.isOpen && !nextState.isCropModalOpen)) { document.addEventListener('keydown', this.onKeyDown, false); } else if ((!nextState.isOpen && this.state.isOpen) || (this.state.isOpen && nextState.isCropModalOpen)) { document.removeEventListener('keydown', this.onKeyDown, false); } } onClose = () => MyProfileActions.hide(); onKeyDown = event => { if (event.keyCode === KeyCodes.ESC) { event.preventDefault(); this.onClose(); } }; onNameChange = event => this.setState({name: event.target.value}); onNicknameChange = event => this.setState({nick: event.target.value}); onAboutChange = event => this.setState({about: event.target.value}); onSave = () => { const { nick, name, about } = this.state; MyProfileActions.saveName(name); MyProfileActions.saveNickname(nick); MyProfileActions.editMyAbout(about); this.onClose(); }; onProfilePictureInputChange = () => { const imageInput = React.findDOMNode(this.refs.imageInput); const imageForm = React.findDOMNode(this.refs.imageForm); const file = imageInput.files[0]; let reader = new FileReader(); reader.onload = (event) => { CropAvatarActionCreators.show(event.target.result); imageForm.reset(); }; reader.readAsDataURL(file); }; onChangeAvatarClick = () => { const imageInput = React.findDOMNode(this.refs.imageInput); imageInput.click() }; onProfilePictureRemove = () => MyProfileActions.removeMyAvatar(); changeMyAvatar = (croppedImage) => MyProfileActions.changeMyAvatar(croppedImage); render() { const { isOpen, isCropModalOpen, profile, nick, name, about } = this.state; const cropAvatar = isCropModalOpen ? <CropAvatarModal onCropFinish={this.changeMyAvatar}/> : null; if (profile !== null && isOpen) { return ( <Modal className="modal-new modal-new--profile" closeTimeoutMS={150} isOpen={isOpen} style={{width: 440}}> <header className="modal-new__header"> <a className="modal-new__header__icon material-icons">person</a> <h4 className="modal-new__header__title">Profile</h4> <div className="pull-right"> <button className="button button--lightblue" onClick={this.onSave}>Done</button> </div> </header> <div className="modal-new__body row"> <div className="col-xs"> <div className="name"> <TextField className="login__form__input" floatingLabelText="Full name" fullWidth onChange={this.onNameChange} type="text" value={name}/> </div> <div className="nick"> <TextField className="login__form__input" floatingLabelText="Nickname" fullWidth onChange={this.onNicknameChange} type="text" value={nick}/> </div> <div className="phone"> <TextField className="login__form__input" disabled floatingLabelText="Phone number" fullWidth type="tel" value={(profile.phones[0] || {}).number}/> </div> <div className="about"> <label htmlFor="about">About</label> <textarea className="textarea" id="about" onChange={this.onAboutChange} placeholder="Few words about you" value={about}/> </div> </div> <div className="profile-picture text-center"> <div className="profile-picture__changer"> <AvatarItem image={profile.bigAvatar} placeholder={profile.placeholder} size="big" title={profile.name}/> <a onClick={this.onChangeAvatarClick}> <span>Change</span> <span>avatar</span> </a> </div> <div className="profile-picture__controls"> <a onClick={this.onProfilePictureRemove}>Remove</a> </div> <form className="hide" ref="imageForm"> <input onChange={this.onProfilePictureInputChange} ref="imageInput" type="file"/> </form> </div> </div> {cropAvatar} </Modal> ); } else { return null; } } } export default Container.create(MyProfile, {pure: false});
src/Card/CardText.js
kradio3/react-mdc-web
import PropTypes from 'prop-types'; import React from 'react'; import classnames from 'classnames'; const propTypes = { className: PropTypes.string, children: PropTypes.node, }; const CardText = ({ className, children }) => ( <section className={classnames('mdc-card__supporting-text', className)} > {children} </section> ); CardText.propTypes = propTypes; export default CardText;
blueocean-material-icons/src/js/components/svg-icons/communication/call.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const CommunicationCall = (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> ); CommunicationCall.displayName = 'CommunicationCall'; CommunicationCall.muiName = 'SvgIcon'; export default CommunicationCall;
src/components/explorer/ExplorerApp.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 ExplorerApp = (props) => { const { formatMessage } = props.intl; return ( <div> <PageTitle /> <AppContainer name="explorer" title={formatMessage(messages.explorerToolName)} description={formatMessage(messages.explorerToolDescription)} > {props.children} </AppContainer> </div> ); }; ExplorerApp.propTypes = { children: PropTypes.node, intl: PropTypes.object.isRequired, }; export default injectIntl(ExplorerApp);
src/shared/visualization/BarChart.js
cityofasheville/simplicity2
import React from 'react'; import PropTypes from 'prop-types'; import { color } from 'd3-color'; import { ResponsiveOrdinalFrame } from 'semiotic'; import HorizontalLegend from './HorizontalLegend'; import Tooltip from './Tooltip'; import { formatDataForStackedBar, budgetBarAnnotationRule } from './visUtilities'; /* * TODOS * size margins based on where labels are even going (y or x), how long they are, remsize */ const getLongDesc = (data, dataKeys, mainAxisKey, valueFormatter) => { // need to fix this function to be generic and work for any barchart data sent in. let formattedData = []; if (data.length > 0 && data[0].label === undefined) { // hacky temporary fix so homelessness barcharts still work formattedData = data; } else { for (let item of data) { let yearAlreadyPresent = false; for (let f of formattedData) { if (f.display_year === item.display_year) { f[item.label] = item.value; yearAlreadyPresent = true; break; } } if (!yearAlreadyPresent) { formattedData.push({ display_year: item.display_year, [item.label]: item.value }); } } } return ( <div> {formattedData.map((value, index) => ( <div key={[value[mainAxisKey], index].join('_')}> <p>{value[mainAxisKey]}<br /> {dataKeys.map(key => ( <span key={[value[mainAxisKey], key].join('_')}> {key || '[data error]'}: {valueFormatter !== null ? valueFormatter(value[key]) : value[key]} <br /> </span> ))} </p> </div> ))} </div> ); }; class BarChart extends React.Component { constructor(props) { super(props); this.state = { altText: this.props.altText || this.props.chartTitle, showingLongDesc: this.showLongDesc, }; this.toggleLongDesc = this.toggleLongDesc.bind(this); } toggleLongDesc(event) { if (event.key === 'Enter' || event.type === 'click') { this.setState({ showingLongDesc: !this.state.showingLongDesc, }); } } render() { const formattedData = this.props.dataFormatter( this.props.data, this.props.dataKeys, this.props.mainAxisDataKey, this.props.colorScheme, ); return ( <div> <div className="visualization-title">{this.props.chartTitle}</div> <br /> <p> {this.props.chartText.isArray && this.props.chartText.map((textChunk, index) => (<span key={index}>{textChunk}</span>)) } {!this.props.chartText.isArray && this.props.chartText } </p> <div aria-label={this.state.altText} tabIndex={0} className="row visualization-container" > <div style={{height: 350}}> <div style={{height: this.props.height}}> <ResponsiveOrdinalFrame responsiveWidth responsiveHeight annotations={this.props.annotations} data={formattedData} hoverAnnotation margin={{ top: 10, right: 10, bottom: 45, left: 60, }} oAccessor={this.props.mainAxisDataKey} oLabel={(d) => { let textAnchor = 'middle'; let transform = 'translate(0,0)'; if (this.props.rotateXLabels && this.props.layout === 'vertical') { textAnchor = 'end'; transform = 'translate(8,0)'; } else if (this.props.layout === 'horizontal') { textAnchor = 'end'; } if (this.props.rotateXLabels) { transform += 'rotate(-45)'; } return ( <text textAnchor={textAnchor} transform={transform} > {this.props.xAxisTickFormatter(d)} </text> ); }} oPadding={8} projection={this.props.layout} rAccessor="value" rExtent={this.props.domain} type="bar" axis={[ { orient: 'left', tickFormat: d => this.props.yAxisTickFormatter(d), ticks: 8, }, ]} style={d => ( this.state.hover === d[this.props.mainAxisDataKey] ? // For the currently hovered bar, return a brighter fill and add a stroke { fill: color(d.color).brighter(0.6).toString(), stroke: color(d.color).toString(), strokeWidth: 2, } : { fill: d.color }) } tooltipContent={(d) => { const dPieces = d.pieces || [d.data]; const tooltipTitle = d.column ? d.column.name : d.data[this.props.mainAxisDataKey]; const textLines = dPieces.map(piece => ({ text: `${piece.label}: ${this.props.tooltipYValFormatter(piece.value)}`, color: piece.color, }) ); if (this.props.layout !== 'horizontal') { textLines.reverse(); } return (<Tooltip textLines={textLines} title={tooltipTitle} />); }} svgAnnotationRules={(d) => { if (d.d.budgetAnnotation === true) { // todo: separate this out? return budgetBarAnnotationRule(d, this.props.layout); } if (d.d.type === 'line' && d.screenCoordinates[0]) { return ( <g key={d.d.label}> <text x={d.screenCoordinates[0]} y={-5} textAnchor="middle" > {d.d.label} </text> <line stroke="black" strokeWidth={3} x1={d.screenCoordinates[0]} x2={d.screenCoordinates[0]} y1={0} y2={d.adjustedSize[1]} /> </g> ); } return null; }} customHoverBehavior={(d) => { if (d && d.pieces) { this.setState({ hover: d.pieces[0].data[this.props.mainAxisDataKey] }); } else { this.setState({ hover: null }); } }} /> </div> </div> </div> <div className="row"> <div className="col-xs-10 col-xs-offset-1"> <HorizontalLegend formattedData={formattedData} legendLabelFormatter={this.props.legendLabelFormatter} /> </div> </div> {!this.props.hideSummary && // TODO: improve keyboard functionality-- a sighted user who relies on the keyboard can't use the button to see the summary very easily // see also area chart (and maybe make this into a component) <div className="row"> <div className="col-xs-10 col-xs-offset-1"> <br /> <div className="text-center inText" role="button" tabIndex="0" onClick={this.toggleLongDesc} onKeyUp={this.toggleLongDesc} > {this.state.showingLongDesc ? 'Hide' : 'Show'} {this.props.chartTitle} bar chart summary </div> <div hidden={!this.state.showingLongDesc}> {getLongDesc(this.props.data, this.props.dataKeys, this.props.mainAxisDataKey, this.props.tooltipYValFormatter)} </div> </div> </div> } </div> ); } } BarChart.propTypes = { altText: PropTypes.string, annotations: PropTypes.arrayOf(PropTypes.object), chartText: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), chartTitle: PropTypes.string, colorScheme: PropTypes.string, data: PropTypes.array, // eslint-disable-line dataFormatter: PropTypes.func, dataKeys: PropTypes.arrayOf(PropTypes.string), domain: PropTypes.arrayOf(PropTypes.number), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), hideSummary: PropTypes.bool, layout: PropTypes.string, legendLabelFormatter: PropTypes.func, mainAxisDataKey: PropTypes.string, rotateXLabels: PropTypes.bool, tooltipYValFormatter: PropTypes.func, xAxisLabel: PropTypes.string, xAxisTickFormatter: PropTypes.func, yAxisTickFormatter: PropTypes.func, }; BarChart.defaultProps = { altText: null, annotations: [], chartText: '', chartTitle: '', colorScheme: 'new_bright_colors', data: [], dataFormatter: formatDataForStackedBar, dataKeys: [], domain: [], height: '100%', hideSummary: false, layout: 'vertical', legendLabelFormatter: val => val, mainAxisDataKey: null, rotateXLabels: false, tooltipYValFormatter: val => val, xAxisLabel: null, xAxisTickFormatter: val => val, yAxisTickFormatter: val => val, }; export default BarChart;
node_modules/react-router/es6/Link.js
rageboom/React_Study
'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; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React, { Component } from 'react'; 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; 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; } /** * 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 = (function (_Component) { _inherits(Link, _Component); function Link() { _classCallCheck(this, Link); _Component.apply(this, arguments); } Link.prototype.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 state = _props.state; var to = _props.to; var query = _props.query; var hash = _props.hash; if (hash) to += hash; this.context.history.pushState(state, to, query); } }; Link.prototype.render = function render() { var _this = this; 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']); // Manually override onClick. props.onClick = function (e) { return _this.handleClick(e); }; // Ignore if rendered outside the context of history, simplifies unit testing. var history = this.context.history; if (history) { props.href = history.createHref(to, query); if (hash) props.href += hash; if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) { if (history.isActive(to, query, onlyActiveOnIndex)) { if (activeClassName) props.className += props.className === '' ? activeClassName : ' ' + activeClassName; if (activeStyle) props.style = _extends({}, props.style, activeStyle); } } } return React.createElement('a', props); }; return Link; })(Component); Link.contextTypes = { history: object }; Link.propTypes = { to: string.isRequired, query: object, hash: string, state: object, activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, onClick: func }; Link.defaultProps = { onlyActiveOnIndex: false, className: '', style: {} }; export default Link;
docs/client/components/pages/InlineToolbar/index.js
dagopert/draft-js-plugins
import React, { Component } from 'react'; // eslint-disable-next-line import/no-unresolved import simpleExampleCode from '!!../../../loaders/prism-loader?language=javascript!./SimpleInlineToolbarEditor'; // eslint-disable-next-line import/no-unresolved import simpleExampleEditorStylesCode from '!!../../../loaders/prism-loader?language=css!./SimpleInlineToolbarEditor/editorStyles.css'; // eslint-disable-next-line import/no-unresolved import customExampleCode from '!!../../../loaders/prism-loader?language=javascript!./CustomInlineToolbarEditor'; // eslint-disable-next-line import/no-unresolved import customExampleEditorStylesCode from '!!../../../loaders/prism-loader?language=css!./CustomInlineToolbarEditor/editorStyles.css'; // eslint-disable-next-line import/no-unresolved import themedExampleCode from '!!../../../loaders/prism-loader?language=javascript!./ThemedInlineToolbarEditor'; // eslint-disable-next-line import/no-unresolved import themedExampleEditorStylesCode from '!!../../../loaders/prism-loader?language=css!./ThemedInlineToolbarEditor/editorStyles.css'; // eslint-disable-next-line import/no-unresolved import gettingStarted from '!!../../../loaders/prism-loader?language=javascript!./gettingStarted'; // eslint-disable-next-line import/no-unresolved import webpackConfig from '!!../../../loaders/prism-loader?language=javascript!./webpackConfig'; // eslint-disable-next-line import/no-unresolved import webpackImport from '!!../../../loaders/prism-loader?language=javascript!./webpackImport'; import Container from '../../shared/Container'; import AlternateContainer from '../../shared/AlternateContainer'; import Heading from '../../shared/Heading'; import styles from './styles.css'; import Code from '../../shared/Code'; import InlineCode from '../../shared/InlineCode'; import SimpleInlineToolbarEditor from './SimpleInlineToolbarEditor'; import CustomInlineToolbarEditor from './CustomInlineToolbarEditor'; import ThemedInlineToolbarEditor from './ThemedInlineToolbarEditor'; import SocialBar from '../../shared/SocialBar'; import NavBar from '../../shared/NavBar'; import Separator from '../../shared/Separator'; import ExternalLink from '../../shared/Link'; export default class App extends Component { render() { return ( <div> <NavBar /> <Separator /> <Container> <Heading level={2}>InlineToolbar</Heading> <Heading level={3}>Supported Environment</Heading> <ul className={styles.list}> <li className={styles.listEntry}> Desktop: Yes </li> <li className={styles.listEntry}> Mobile: No </li> <li className={styles.listEntry}> Screen-reader: No </li> </ul> </Container> <AlternateContainer> <Heading level={2}>Getting Started</Heading> <Code code="npm install draft-js-plugins-editor@beta --save" /> <Code code="npm install draft-js-inline-toolbar-plugin@beta --save" /> <Code code={gettingStarted} name="gettingStarted.js" /> <Heading level={3}>Importing the default styles</Heading> <p> The plugin ships with a default styling available at this location in the installed package: &nbsp; <InlineCode code={'node_modules/draft-js-inline-toolbar-plugin/lib/plugin.css'} /> </p> <Heading level={4}>Webpack Usage</Heading> <ul className={styles.list}> <li className={styles.listEntry}> 1. Install Webpack loaders: &nbsp; <InlineCode code={'npm i style-loader css-loader --save-dev'} /> </li> <li className={styles.listEntry}> 2. Add the below section to Webpack config (if your config already has a loaders array, simply add the below loader object to your existing list. <Code code={webpackConfig} className={styles.guideCodeBlock} /> </li> <li className={styles.listEntry}> 3. Add the below import line to your component to tell Webpack to inject the style to your component. <Code code={webpackImport} className={styles.guideCodeBlock} /> </li> <li className={styles.listEntry}> 4. Restart Webpack. </li> </ul> <Heading level={4}>Browserify Usage</Heading> <p> Please help, by submiting a Pull Request to the <ExternalLink href="https://github.com/draft-js-plugins/draft-js-plugins/blob/master/docs/client/components/pages/InlineToolbar/index.js">documentation</ExternalLink>. </p> </AlternateContainer> <Container> <Heading level={2}>Simple Inline Toolbar Example</Heading> <SimpleInlineToolbarEditor /> <Code code={simpleExampleCode} name="SimpleInlineToolbarEditor.js" /> <Code code={simpleExampleEditorStylesCode} name="editorStyles.css" /> </Container> <Container> <Heading level={2}>Custom Inline Toolbar Example</Heading> <CustomInlineToolbarEditor /> <Code code={customExampleCode} name="CustomInlineToolbarEditor.js" /> <Code code={customExampleEditorStylesCode} name="editorStyles.css" /> </Container> <Container> <Heading level={2}>Themed Inline Toolbar Example</Heading> <ThemedInlineToolbarEditor /> <Code code={themedExampleCode} name="ThemedInlineToolbarEditor.js" /> <Code code={themedExampleEditorStylesCode} name="editorStyles.css" /> </Container> <SocialBar /> </div> ); } }
src/main.js
daimagine/gh-milestone
import React from 'react' import ReactDOM from 'react-dom' import { useRouterHistory } from 'react-router' import { createHistory } from 'history' import makeRoutes from './routes' import Root from './containers/Root' import configureStore from './redux/configureStore' import { addLocaleData } from 'react-intl' import en from 'react-intl/lib/locale-data/en' import de from 'react-intl/lib/locale-data/de' import it from 'react-intl/lib/locale-data/it' import es from 'react-intl/lib/locale-data/es' import fr from 'react-intl/lib/locale-data/fr' const historyConfig = { basename: __BASENAME__ } const history = useRouterHistory(createHistory)(historyConfig) const initialState = window.__INITIAL_STATE__ const store = configureStore({ initialState, history }) const routes = makeRoutes(store) addLocaleData(en) addLocaleData(de) addLocaleData(it) addLocaleData(es) addLocaleData(fr) // All modern browsers, expect `Safari`, have implemented // the `ECMAScript Internationalization API`. // For that we need to patch in on runtime. if (!global.Intl) { require.ensure(['intl'], require => { require('intl') start() }, 'IntlBundle') } else start() function start () { // Render the React application to the DOM ReactDOM.render( <Root history={history} routes={routes} store={store} />, document.getElementById('root') ) } // Render the React application to the DOM ReactDOM.render( <Root history={history} routes={routes} store={store} />, document.getElementById('root') )
frontend-new/src/js/components/common/header/hamburger/index.js
leapfrogtechnology/vyaguta-resource
import React, { Component } from 'react'; import App from '../../../../../custom-ui/app'; class Hamburger extends Component { toggleSidebar(){ App.sidebar('toggle-sidebar'); } render() { return( <ul className='nav navbar-nav-custom'> <li><a href='javascript:void(0)' id='burgerMenu' onClick={this.toggleSidebar.bind(this)}> <i className='fa fa-bars fa-fw'></i> </a></li> </ul> ); } } export default Hamburger;
src/svg-icons/editor/functions.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFunctions = (props) => ( <SvgIcon {...props}> <path d="M18 4H6v2l6.5 6L6 18v2h12v-3h-7l5-5-5-5h7z"/> </SvgIcon> ); EditorFunctions = pure(EditorFunctions); EditorFunctions.displayName = 'EditorFunctions'; EditorFunctions.muiName = 'SvgIcon'; export default EditorFunctions;
src/client.js
erikras/react-redux-universal-hot-example
/** * THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER. */ import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import io from 'socket.io-client'; import {Provider} from 'react-redux'; import { Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { ReduxAsyncConnect } from 'redux-async-connect'; import useScroll from 'scroll-behavior/lib/useStandardScroll'; import getRoutes from './routes'; const client = new ApiClient(); const _browserHistory = useScroll(() => browserHistory)(); const dest = document.getElementById('content'); const store = createStore(_browserHistory, client, window.__data); const history = syncHistoryWithStore(_browserHistory, store); function initSocket() { const socket = io('', {path: '/ws'}); socket.on('news', (data) => { console.log(data); socket.emit('my other event', { my: 'data from client' }); }); socket.on('msg', (data) => { console.log(data); }); return socket; } global.socket = initSocket(); const component = ( <Router render={(props) => <ReduxAsyncConnect {...props} helpers={{client}} filter={item => !item.deferred} /> } history={history}> {getRoutes(store)} </Router> ); ReactDOM.render( <Provider store={store} key="provider"> {component} </Provider>, dest ); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) { console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); } } if (__DEVTOOLS__ && !window.devToolsExtension) { const DevTools = require('./containers/DevTools/DevTools'); ReactDOM.render( <Provider store={store} key="provider"> <div> {component} <DevTools /> </div> </Provider>, dest ); }
src/containers/DevToolsWindow.js
VinSpee/react-redux-postcss-boilerplate
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; export default createDevTools( <LogMonitor /> );
app/routes/Profile/Profile.js
blovato/sca-mobile
import React from 'react'; import { Text, View, Image } from 'react-native'; import Button from '../../components/Button'; import Avatar from '../../components/Avatar'; import images from '../../config/images'; import { capitalize } from '../../lib/string'; import styles from './styles'; const Profile = (props) => { const { user, signOut } = props; let email; if (user) { email = user.emails[0].address; } return ( <View style={styles.container}> <Image style={styles.header} source={images.profileHeader} /> <View style={styles.body}> <Avatar email={email} /> <Text>{capitalize(email)}</Text> <Button text="Sign Out" onPress={signOut} /> </View> </View> ); }; Profile.propTypes = { user: React.PropTypes.object, signOut: React.PropTypes.func, }; export default Profile;
docs/client/components/pages/Playground/index.js
koaninc/draft-js-plugins
import React, { Component } from 'react'; import Container from '../../shared/Container'; import Heading from '../../shared/Heading'; import PlaygroundEditor from './PlaygroundEditor'; import NavBar from '../../shared/NavBar'; import Separator from '../../shared/Separator'; export default class App extends Component { render() { return ( <div> <NavBar /> <Separator /> <Container> <Heading level={2}>Development Playground</Heading> </Container> <Container> <PlaygroundEditor /> </Container> </div> ); } }
src/js/Components/Home.js
RoyalSix/myBiolaApp
import React, { Component } from 'react'; import { View, Text, Image, ScrollView, KeyboardAvoidingView } from 'react-native'; import BoardContainer from '../Containers/BoardContainer' import { biola_picture } from 'assets'; export default class HomeContainer extends Component { render() { return ( <KeyboardAvoidingView behavior={'position'} style={{flex:1}}> <ScrollView contentContainerStyle={{minHeight:height, marginTop:20}} > <View style={{ borderWidth: 1, borderColor: 'white', height: 182, marginHorizontal: 15 }} > <Image resizeMode={'contain'} style={{ height: 180, alignSelf: 'center', }} source={biola_picture} /> </View> <BoardContainer /> </ScrollView> </KeyboardAvoidingView> ) } }
blueocean-material-icons/src/js/components/svg-icons/image/switch-video.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageSwitchVideo = (props) => ( <SvgIcon {...props}> <path d="M18 9.5V6c0-.55-.45-1-1-1H3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-3.5l4 4v-13l-4 4zm-5 6V13H7v2.5L3.5 12 7 8.5V11h6V8.5l3.5 3.5-3.5 3.5z"/> </SvgIcon> ); ImageSwitchVideo.displayName = 'ImageSwitchVideo'; ImageSwitchVideo.muiName = 'SvgIcon'; export default ImageSwitchVideo;
app/components/ShowUserApplications/index.js
theClubhouse-Augusta/JobWeasel-FrontEnd
/** * * ShowUserApplications * */ import React from 'react'; import {Link} from 'react-router-dom'; import './style.css'; import './styleM.css'; export default class ShowUserApplications extends React.PureComponent { constructor(props) { super(props); this.state = { applications: [], notification: "" }; } componentWillMount() { this.getApplications(this.props.userId); } getApplications = (id) => { let url = "http://localhost:8000/api/getUserApplications/" + id; let _this = this; fetch(url, {method: 'GET'}).then( function(response) { return response.json(); } ).then( function(json) { if (!json.error) { _this.setState({ applications: json.applications }); } console.log(url); console.log(json.applications); } ); } getNotification = (json) => { if (json.success) { this.setState({notification: json.success}); } if (json.error) { this.setState({notification: json.error}); } } handleAcceptOffer = (app) => { let url = "http://localhost:8000/api/acceptOffer"; let _this = this; let data = new FormData; data.append('application_id', app.id); data.append('employee_accepts', 1); let token = sessionStorage.getItem("token"); let auth = {"Authorization": "Bearer " + token}; fetch(url, {method: 'POST', body: data, headers: auth}) .then(function(response) {return response.json();}) .then(function(json) { console.log(url); console.log(json); _this.getNotification(json); _this.getApplications(_this.props.userId); } ); } renderApplication = (app, index) => { let url = "/JobDetails/" + app.job_id; let message = ""; let accept = ""; if (app.applicant_reviewed === 0) { message = "Pending Employer Review"; } else { if (app.employer_approves === 1) { message = "Application Approved!"; accept = <input type="button" value="Accept Offer" className="acceptOffer button" onClick={() => this.handleAcceptOffer(app)} />; } if (app.employer_approves === 0) {message = "Application Denied";} } if (app.employee_accepts === 1) { message = "You have accepted this job offer!"; accept = ""; } return ( <div className="jobApplications panel" key={index}> <div className="jobApplications label">Job:</div> <div className="jobApplications panel"> <Link to={url}>{app.name}</Link> </div> <div className="jobApplications">{message}</div> {accept} </div> ); } renderNotification = (text) => { return ( <div className="jsonNotification"> {text} </div> ); } render() { let notification = ""; if (this.state.notification !== "") { notification = this.renderNotification(this.state.notification); } return ( <div className="jobApplications"> {notification} {this.state.applications.map( (app, index) => (this.renderApplication(app, index)) )} </div> ); } } ShowUserApplications.contextTypes = { router: React.PropTypes.object };
client/app/admin/index.js
prilutskiy/hackathon
import React from 'react'; import { Router, Route, IndexRoute, Redirect, browserHistory } from 'react-router'; import NotFound from './../shared/NotFound'; import Application from './Application'; import Home from './Home'; import Profile from '../shared/Profile'; import Lab from './Lab'; const adminRoutes = ( <Router history={browserHistory}> <Route path="/" component={Application}> <IndexRoute component={Home} /> <Route path="/labs/:labId" component={Lab} /> <Route path="/profile" component={Profile} /> <Route path="*" component={NotFound} /> </Route> </Router> ); export default adminRoutes;
src/FormaticTestUtils.js
zapier/formatic
import React from 'react'; import { mount } from 'enzyme'; import Formatic from './formatic'; // Render some Formatic fields to HTML so we can do a snapshot test of them. // Pass in a callback so you can do assertions on the components as well. export const renderFieldsToHtml = (fields, handleComponent = () => {}) => { const config = Formatic.createConfig(); const value = config.createRootValue({ fields, }); const component = mount( <Formatic config={config} fields={fields} onChange={() => {}} value={value} /> ); handleComponent(component); const html = component.html(); component.unmount(); return html; };
src/components/App.js
shoegazer/shuffly-now
import React from 'react' import HeaderIcons from './HeaderIcons' import Settings from './Settings' import Help from './Help' import Weather from './Weather' import Now from './Now' import Popup from './Popup' import Alert from './Alert' import Background from './Background' import Graph from './Graph' import '../styles/app.css' import '../styles/tooltip.css' export default class extends React.Component { render() { return pug` #app Background #mask #body Now Help HeaderIcons Settings Weather Popup Alert Graph `; } }
stories/examples/BadgePills.js
reactstrap/reactstrap
import React from 'react'; import { Badge } from 'reactstrap'; const Example = (props) => { return ( <div> <Badge color="primary" pill>Primary</Badge> <Badge color="secondary" pill>Secondary</Badge> <Badge color="success" pill>Success</Badge> <Badge color="danger" pill>Danger</Badge> <Badge color="warning" pill>Warning</Badge> <Badge color="info" pill>Info</Badge> <Badge color="light" pill>Light</Badge> <Badge color="dark" pill>Dark</Badge> </div> ); } export default Example;
src/svg-icons/editor/format-quote.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatQuote = (props) => ( <SvgIcon {...props}> <path d="M6 17h3l2-4V7H5v6h3zm8 0h3l2-4V7h-6v6h3z"/> </SvgIcon> ); EditorFormatQuote = pure(EditorFormatQuote); EditorFormatQuote.displayName = 'EditorFormatQuote'; EditorFormatQuote.muiName = 'SvgIcon'; export default EditorFormatQuote;
paraviewweb/src/React/CollapsibleControls/PlotlyChartControl/index.js
CordyChen/VisMechan
import React from 'react'; import CollapsibleWidget from '../../Widgets/CollapsibleWidget'; import DropDownWidget from '../../Widgets/DropDownWidget'; import Histogram from './Histogram'; import Histogram2D from './Histogram2D'; import Scatter3D from './Scatter3D'; import PieChart from './PieChart'; const types = { Histogram, Histogram2D, Scatter3D, PieChart, }; export default React.createClass({ displayName: 'PlotlyChartControl', propTypes: { model: React.PropTypes.object.isRequired, }, updateChartType(chartType) { this.props.model.updateState({ chartType, }); this.forceUpdate(); }, updateChartData(data) { this.props.model.updateState(data); this.forceUpdate(); }, render() { const arrays = this.props.model.getArrays(); const chartState = this.props.model.getState(); return ( <CollapsibleWidget title="Chart" activeSubTitle subtitle={ <DropDownWidget field={chartState.chartType} fields={Object.keys(types)} onChange={this.updateChartType} /> } > {React.createElement(types[chartState.chartType], { chartState, arrays, onChange: this.updateChartData })} </CollapsibleWidget> ); }, });
node_modules/react-icons/md/mic-off.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const MdMicOff = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m7.1 5l27.9 27.9-2.1 2.1-7-7c-1.2 0.8-2.8 1.3-4.3 1.5v5.5h-3.2v-5.5c-5.5-0.8-10-5.4-10-11.1h2.8c0 5 4.2 8.4 8.8 8.4 1.3 0 2.7-0.3 3.8-0.9l-2.7-2.7c-0.3 0.1-0.7 0.2-1.1 0.2-2.7 0-5-2.3-5-5v-1.3l-10-10z m17.9 13.6l-10-9.9v-0.3c0-2.8 2.3-5 5-5s5 2.2 5 5v10.2z m6.6-0.2c0 1.9-0.5 3.8-1.4 5.4l-2.1-2.1c0.5-1 0.7-2.1 0.7-3.3h2.8z"/></g> </Icon> ) export default MdMicOff
information/blendle-frontend-react-source/app/components/PortalDialog.js
BramscoChill/BlendleParser
import React from 'react'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; import portalMixin from 'components/mixins/PortalMixin'; import classNames from 'classnames'; export default createReactClass({ displayName: 'PortalDialog', propTypes: { children: PropTypes.element.isRequired, onClick: PropTypes.func.isRequired, className: PropTypes.string, }, mixins: [portalMixin('dialog-portal')], _onClick(e) { if (!e.target.classList.contains('dialog-overlay')) { return; } this.props.onClick(e); }, render() { return null; }, renderLayer() { const detect = window.BrowserDetect; const noOverflow = detect.browser === 'Android Browser' && detect.version < '4.4'; const overlayClasses = classNames({ [this.props.className]: this.props.className, 'dialog-overlay': true, 'no-overflow': noOverflow, }); return ( <div className={overlayClasses} onClick={this._onClick}> {this.props.children} </div> ); }, }); // WEBPACK FOOTER // // ./src/js/app/components/PortalDialog.js
source/components/DatasetSelector.js
PitchInteractiveInc/tilegrams
import React from 'react' import geographyResource from '../resources/GeographyResource' const CUSTOM_LABEL = 'Custom CSV' export default class DatasetSelector extends React.Component { constructor(props) { super(props) this.state = { selectedIndex: 0, csvInputValue: '', } this._onCsvChange = this._onCsvChange.bind(this) this._submitCustomCsv = this._submitCustomCsv.bind(this) } /** * When new labels are passed, for example when a user selects a new geo, * reset selected index to match the loaded dataset */ componentWillReceiveProps(nextProps) { if (JSON.stringify(nextProps.labels) !== JSON.stringify(this.props.labels)) { this.setState({selectedIndex: 0}) } } _onSelect(event) { const selectedIndex = event.target.value this.setState({selectedIndex, csvInputValue: ''}) if (!this._isCustomSelection(selectedIndex)) { this.props.onDatasetSelected(selectedIndex) } else { this.props.onResizeNeeded() } } _onCsvChange(event) { const csvInputValue = event.target.value this.setState({csvInputValue}) } _submitCustomCsv() { if (this.state.csvInputValue) { this.props.onCustomDataset(this.state.csvInputValue) } } /** Return true if user has selected 'Custom' option */ _displayCsvInput() { return this._isCustomSelection() } /** Return true if index is the 'Custom' option */ _isCustomSelection(index) { return parseInt(index || this.state.selectedIndex, 10) === this.props.labels.length } _renderMenu() { const labels = this.props.labels.concat([CUSTOM_LABEL]) const datasets = labels.map((label, index) => { return <option key={label} value={index}>{label}</option> }) return ( <select id='dataset-selector' className='dataset-select' onChange={(event) => this._onSelect(event)} > {datasets} </select> ) } /** Builds custom csv from geos to help users input good data */ _generateSampleCsv() { const geos = geographyResource.getMapResource(this.props.geography).getUniqueFeatureIds() const geoHash = geographyResource.getGeoCodeHash(this.props.geography) const sampleCsv = geos.reduce((a, b) => `${a}${b},1,${geoHash[b].name}\n`, '') return ( <div className='code'> {sampleCsv} </div> ) } _renderCsvInput() { let submitClass = 'submit-custom' if (this.state.csvInputValue) { submitClass += ' active' } return ( <div className='csv-input'> <div className='instruction'> {`Csv should be formatted with no headers and geo id as the first column and value as second. The third column is ignored. Sample CSV:`} {this._generateSampleCsv()} Paste custom CSV below: </div> <textarea ref={(ref) => { this.csvInput = ref }} rows={5} onChange={this._onCsvChange} value={this.state.csvInputValue || ''} /> <div className={submitClass} onClick={this._submitCustomCsv}>Submit</div> </div> ) } render() { let csvInput if (this._displayCsvInput()) { csvInput = this._renderCsvInput() } return ( <fieldset> {this._renderMenu()} {csvInput} </fieldset> ) } } DatasetSelector.propTypes = { labels: React.PropTypes.array, onDatasetSelected: React.PropTypes.func, onCustomDataset: React.PropTypes.func, onResizeNeeded: React.PropTypes.func, geography: React.PropTypes.string, } DatasetSelector.defaultProps = { labels: [], onDatasetSelected: () => {}, onCustomDataset: () => {}, onResizeNeeded: () => {}, }
src/routes/discover/index.js
transitlinks/web-app
import { getLog } from '../../core/log'; const log = getLog('routes/discover'); import React from 'react'; import ErrorPage from '../../components/common/ErrorPage'; import Discover from './Discover'; import { createParamString } from '../../core/utils'; import { getActiveTripQuery, getDiscoverQuery } from '../../data/queries/queries'; export default { path: '/discover', async action({ params, context }) { const { graphqlRequest } = context.store.helpers; //${getDiscoverQuery({ ...params, offset: 0, limit: 6 })} try { const { data } = await graphqlRequest( `query {, transportTypes { slug }, ${getActiveTripQuery()} }` ); log.info('event=received-discoveries-data', data); return <Discover discover={data.discover} transportTypes={data.transportTypes} activeTrip={data.activeTrip} />; } catch (error) { log.info('error=route-discover', error); return <ErrorPage errors={error.errors} /> } } };
packages/zensroom/lib/components/bookings/BookingsNewForm.js
SachaG/Zensroom
/* Form for inserting a new booking, wrapped with withNew HoC. http://docs.vulcanjs.org/mutations.html#Higher-Order-Components */ import React, { Component } from 'react'; import { Components, registerComponent, withCurrentUser, getFragment, getSetting, withMessages, withNew, addCallback } from 'meteor/vulcan:core'; import { withRouter } from 'react-router'; import compose from 'recompose/compose'; import DateTimePicker from 'react-datetime'; import Button from 'react-bootstrap/lib/Button'; import gql from 'graphql-tag'; import moment from 'moment'; import { intlShape, FormattedMessage } from 'meteor/vulcan:i18n'; import { Form, Input } from 'formsy-react-components'; import Bookings from '../../modules/bookings/collection'; import withUnavailableDates from '../../containers/withUnavailableDatesContainer'; class BookingsNewForm extends Component { constructor() { super(); this.success = this.success.bind(this); this.submitForm = this.submitForm.bind(this); this.updateFromDate = this.updateFromDate.bind(this); this.updateToDate = this.updateToDate.bind(this); this.updateGuests = this.updateGuests.bind(this); this.isAvailable = this.isAvailable.bind(this); this.createNewBooking = this.createNewBooking.bind(this); this.state = { from: null, to: null, numberOfGuests: 1, disabled: false } } updateFromDate(date) { this.setState({ from: date }); if (date > this.state.to) { this.setState({ to: date.clone().add('days', 1) }) } } updateToDate(date) { this.setState({ to: date }); } updateGuests(name, value) { this.setState({ numberOfGuests: parseInt(value || 1) }); } /* Helper to tell if a date is available */ isAvailable(mDate) { const unavailableDates = this.props.unavailableDates && this.props.unavailableDates.map(date => moment(new Date(date)).startOf('day').toString()); return !_.contains(unavailableDates, mDate.toString()) } /* Form submit handler */ submitForm(data) { // disable form to prevent multiple submissions this.setState({ disabled: true }); // if fields are missing, show message and abort submission if (!this.state.from || !this.state.to || !this.state.numberOfGuests) { alert(this.context.intl.formatMessage({id: 'bookings.please_fill_in_all_fields'})); this.setState({ disabled: false }); return; } // create alias for this.createNewBooking const createNewBooking = this.createNewBooking; // create callback function and set it to only run once function createNewBookingCallback() { createNewBooking(data); return {}; } createNewBookingCallback.runOnce = true; if (this.props.currentUser) { // user is logged in this.createNewBooking(data); } else { // user is not logged in // add postlogin callback, go to sign-up page, show message addCallback('users.postlogin', createNewBookingCallback); this.props.router.push('/sign-up'); this.props.flash(this.context.intl.formatMessage({id: 'users.please_sign_up_log_in'}), 'error'); } } /* Trigger new booking mutation and then call this.success() */ createNewBooking(data) { console.log('// createNewBooking') console.log(data) this.props.newMutation({document: { startAt: this.state.from.toDate(), endAt: this.state.to.toDate(), numberOfGuests: this.state.numberOfGuests, roomId: this.props.room._id }}).then(result => this.success(result.data.BookingsNew)); } /* Success callback */ success(booking) { this.props.router.push({pathname: `/booking/${booking._id}`}); this.props.flash(this.context.intl.formatMessage({id: 'bookings.created'}), 'success'); } /* Render */ render() { const numberOfNights = this.state.from && this.state.to ? this.state.to.diff(this.state.from, 'days') : 0; const totalPrice = this.props.room.pricePerNight * this.state.numberOfGuests * numberOfNights; return ( <Form onSubmit={this.submitForm}> <div className="bookings-form"> <h3>Total Price: {getSetting('defaultCurrency', '$')}{totalPrice}</h3> <div className="bookings-form-field"> <label className="control-label"><FormattedMessage id="bookings.from" /></label> <DateTimePicker onChange={newDate => this.updateFromDate(newDate)} format={"x"} isValidDate={(currentDate, selectedDate) => { const yesterday = moment().subtract( 1, 'day' ); return currentDate.isAfter(yesterday) && this.isAvailable(currentDate); }} timeFormat={false} value={this.state.from} /> </div> <div className="bookings-form-field"> <label className="control-label"><FormattedMessage id="bookings.to" /></label> <DateTimePicker onChange={newDate => this.updateToDate(newDate)} format={"x"} isValidDate={(currentDate, selectedDate) => { const yesterday = moment().subtract( 1, 'day' ); return currentDate.isAfter(yesterday) && currentDate.isAfter(moment(this.state.from)) && this.isAvailable(currentDate); }} timeFormat={false} value={this.state.to} /> </div> <div className="bookings-form-field"> <label className="control-label"><FormattedMessage id="bookings.number_of_guests" /></label> <Input layout="elementOnly" onChange={this.updateGuests} value={this.state.numberOfGuests} name="numberOfGuests" type="number"/> </div> <Button disabled={this.state.disabled} className="bookings-form-submit" type="submit" bsStyle="primary"><FormattedMessage id="bookings.book" /></Button> </div> </Form> ) } } BookingsNewForm.contextTypes = { intl: intlShape }; const options = { collection: Bookings, fragment: gql` fragment BookingFragment on Booking { __typename _id createdAt userId roomId startAt endAt paidAt } ` } registerComponent('BookingsNewForm', BookingsNewForm, [withNew, options], withRouter, withMessages, withCurrentUser, withUnavailableDates); // export default compose( // withNew(options), // withRouter, // withMessages, // withCurrentUser, // withUnavailableDates, // )(BookingsNewForm)
app/routes/Match/NoSets.js
arnef/ligatool-hamburg
import React from 'react'; import { View, Linking, Alert, Platform } from 'react-native'; import { connect } from 'react-redux'; import moment from 'moment'; import { Text, TeamLogo, Card, ListItem, Image, Separator, } from '../../components'; import S from '../../lib/strings'; import styles from './styles'; import * as NavigationActions from '../../redux/modules/navigation'; import Routes from '../../config/routes'; import { DATETIME_DB, DATETIME_FORMAT, ASSOC } from '../../config/settings'; import { setFixtureStatusInPlay } from '../../redux/modules/fixtures'; import { getColor } from '../../redux/modules/user'; function NoSets(props) { function onOpenVenue() { const address = `${props.venue.street}, ${props.venue.zipCode} ${ props.venue.city }`; const uri = Platform.OS === 'ios' ? 'http://maps.apple.com/?address=' : 'geo:53.5586526,9.6476386?q='; Linking.openURL(uri + encodeURI(address)).catch(() => Alert.alert(S.MAPS_APP_NOT_FOUND), ); } function insertResult() { props.insertResult(props.match.id); } function openDateChange() { props.navigate(Routes.MATCH_DATE, { id: props.match.id }); } function renderPlayer() { const { player } = props; const length = player.home ? Math.max(player.home.length, player.away.length) : 0; const childs = []; for (let i = 0; i < length; i++) { const playerHome = i < player.home.length ? player.home[i] : null; const playerAway = i < player.away.length ? player.away[i] : null; childs.push( <View style={styles.playerRow} key={`player-${i}`}> <View style={styles.player}> {playerHome && ( <Card // onPress={() => { // props.navigate(Routes.PLAYER, playerHome); // }} > <View style={styles.playerContainer}> <Image url={playerHome.image} size={90} /> <Text style={styles.playerText}>{`${playerHome.name} ${ playerHome.surname }`}</Text> </View> </Card> )} </View> <View style={styles.player}> {playerAway && ( <Card // onPress={() => { // props.navigate(Routes.PLAYER, playerAway); // }} > <View style={styles.playerContainer}> <Image url={playerAway.image} size={90} /> <Text style={styles.playerText}>{`${playerAway.name} ${ playerAway.surname }`}</Text> </View> </Card> )} </View> </View>, ); } return childs; } const date = moment(props.match.date, DATETIME_DB); return ( <View style={styles.container}> <View style={styles.row}> <View style={styles.teamInfo}> <TeamLogo team={props.match.homeTeamLogo} size={90} /> </View> {!props.firstFixture && ( <Text style={styles.teamVs} bold secondary> vs </Text> )} {props.firstFixture && ( <View style={styles.firstMatch}> <Text small secondary bold> {S.FIRST_MATCH} </Text> <View style={styles.firstMatchResult}> <Text style={styles.textFirstMatchResult}> {`${props.firstFixture.setPointsAwayTeam}:${ props.firstFixture.setPointsHomeTeam }`} </Text> <Text style={styles.textFirstMatchResult}> {`(${props.firstFixture.goalsAwayTeam}:${ props.firstFixture.goalsHomeTeam })`} </Text> </View> <Text small secondary bold> {' '} </Text> </View> )} <View style={styles.teamInfo}> <TeamLogo team={props.match.awayTeamLogo} size={90} /> </View> </View> <ListItem.Group> <ListItem.Header title={`${ props.match.status == 'POSTPONED' ? S.SO_FAR : '' }${date.format(DATETIME_FORMAT)}`} /> {props.venue && !!props.venue.name && ( <ListItem onPress={onOpenVenue}> <View style={styles.option}> <Text>{`${props.venue.name}`}</Text> <Text>{`${props.venue.street}, ${props.venue.zipCode} ${ props.venue.city }`}</Text> </View> <ListItem.Icon right color={props.color} name="pin" /> </ListItem> )} {props.isAdmin && <Separator />} {props.isAdmin && ASSOC.indexOf('tfvhh') !== -1 && ( <ListItem onPress={openDateChange}> <Text style={styles.option}>{S.CHANGE_MATCH_DATETIME}</Text> <ListItem.Icon right color={props.color} name="calendar" /> </ListItem> )} {props.isAdmin && ASSOC.indexOf('tfvhh') !== -1 && <Separator />} {props.isAdmin && ( <ListItem onPress={insertResult} disabled={date.diff(moment(), 'days') > 0} > <Text style={styles.option}>{S.INSERT_SCORE}</Text> <ListItem.Icon right color={props.color} name="create" /> </ListItem> )} </ListItem.Group> {renderPlayer()} </View> ); } export default connect( state => ({ color: getColor(state), }), (dispatch, props) => ({ insertResult: () => dispatch(setFixtureStatusInPlay(props.match.id)), navigate: (routeName, params) => dispatch(NavigationActions.navigate({ routeName, params })), }), )(NoSets);
src/routes/fullscreen/components/Fullscreen.js
ahthamrin/kbri-admin2
import React from 'react'; import QueueAnim from 'rc-queue-anim'; const Fullscreen = () => ( <section className="container-fluid"> <QueueAnim type="bottom" className="ui-animate"> <div key="1"> <div className="article-title">Blank</div> </div> </QueueAnim> </section> ); module.exports = Fullscreen;
webapp/src/App.js
Freshmilkymilk/ardacraft.me
import React from 'react'; import {Header} from "./Margins/Header"; import {Footer} from "./Margins/Footer"; import {BrowserRouter as Router, Route, Switch} from "react-router-dom"; import './App.css'; import Home from "./Pages/Home"; import Modpack from "./Pages/Modpack"; import About from "./Pages/About"; import Map from "./Pages/Map"; import FAQ from "./Pages/FAQ"; import Privacy from "./Pages/Privacy"; import Rules from "./Pages/Rules"; export default function App() { return ( <Router> <div> <Header/> <Switch> <Route exact path="/modpack" component={Modpack}/> <Route exact path="/map" component={Map}/> <Route exact path="/about" component={About}/> <Route exact path="/faq" component={FAQ}/> <Route exact path="/privacy" component={Privacy}/> <Route exact path="/rules" component={Rules}/> <Route exact path="/" component={Home}/> </Switch> <Footer/> </div> </Router> ); }
app/components/keyboard.js
BAMason/HI
import React from 'react'; export default class Keyboard extends React.Component { constructor(props) { super(props); const alpha = [`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`, `O`, `P`, `Q`, `R`, `S`, `T`, `U`, `V`, `W`, `X`, `Y`, `Z`]; this.keys = alpha.map((ltr) => <div className="key" key={ltr} onClick={this.props.onClick}>{ltr}</div>); } render() { return <div className="keyboard">{this.keys}</div>; } }
src/parser/hunter/survival/modules/talents/VipersVenom.js
fyruna/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import ItemDamageDone from 'interface/others/ItemDamageDone'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; import StatTracker from 'parser/shared/modules/StatTracker'; import TalentStatisticBox from 'interface/others/TalentStatisticBox'; import GlobalCooldown from 'parser/shared/modules/GlobalCooldown'; import { RAPTOR_MONGOOSE_VARIANTS, VIPERS_VENOM_DAMAGE_MODIFIER } from 'parser/hunter/survival/constants'; /** * Raptor Strike (or Mongoose Bite) has a chance to make your next * Serpent Sting cost no Focus and deal an additional 250% initial damage. * * Example log: https://www.warcraftlogs.com/reports/pNJbYdLrMW2ynKGa#fight=3&type=damage-done&source=16&translate=true */ class VipersVenom extends Analyzer { static dependencies = { statTracker: StatTracker, globalCooldown: GlobalCooldown, }; buffedSerpentSting = false; bonusDamage = 0; procs = 0; lastProcTimestamp = 0; accumulatedTimeFromBuffToCast = 0; currentGCD = 0; wastedProcs = 0; badRaptorsOrMBs = 0; spellKnown = null; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.VIPERS_VENOM_TALENT.id); if (this.active) { this.spellKnown = this.selectedCombatant.hasTalent(SPELLS.MONGOOSE_BITE_TALENT.id) ? SPELLS.MONGOOSE_BITE_TALENT : SPELLS.RAPTOR_STRIKE; } } on_byPlayer_cast(event) { const spellId = event.ability.guid; if ((!RAPTOR_MONGOOSE_VARIANTS.includes(spellId) && spellId !== SPELLS.SERPENT_STING_SV.id) || !this.selectedCombatant.hasBuff(SPELLS.VIPERS_VENOM_BUFF.id)) { return; } if (spellId === SPELLS.SERPENT_STING_SV.id) { this.buffedSerpentSting = true; this.currentGCD = this.globalCooldown.getGlobalCooldownDuration(spellId); this.accumulatedTimeFromBuffToCast += event.timestamp - this.lastProcTimestamp - this.currentGCD; return; } if (RAPTOR_MONGOOSE_VARIANTS.includes(spellId)) { this.badRaptorsOrMBs++; } } on_byPlayer_damage(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.SERPENT_STING_SV.id || !this.buffedSerpentSting) { return; } this.bonusDamage += calculateEffectiveDamage(event, VIPERS_VENOM_DAMAGE_MODIFIER); this.buffedSerpentSting = false; } on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.VIPERS_VENOM_BUFF.id) { return; } this.procs++; this.lastProcTimestamp = event.timestamp; } on_byPlayer_refreshbuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.VIPERS_VENOM_BUFF.id) { return; } this.wastedProcs++; } get averageTimeBetweenBuffAndUsage() { return (this.accumulatedTimeFromBuffToCast / this.procs / 1000).toFixed(2); } get raptorWithBuffThresholds() { return { actual: this.badRaptorsOrMBs, isGreaterThan: { minor: 1, average: 2, major: 3, }, style: 'number', }; } get wastedProcsThresholds() { return { actual: this.wastedProcs, isGreaterThan: { minor: 0, average: 2, major: 4, }, style: 'number', }; } suggestions(when) { when(this.raptorWithBuffThresholds).addSuggestion((suggest, actual, recommended) => { return suggest(<>Remember to cast <SpellLink id={SPELLS.SERPENT_STING_SV.id} /> after proccing <SpellLink id={SPELLS.VIPERS_VENOM_TALENT.id} /> before you cast <SpellLink id={this.spellKnown.id} /> again.</>) .icon(SPELLS.VIPERS_VENOM_TALENT.icon) .actual(`${actual} raptor casts with Viper's Venom buff active`) .recommended(`<${recommended} casts is recommended`); }); when(this.wastedProcsThresholds).addSuggestion((suggest, actual, recommended) => { return suggest(<>Remember to utilise all your <SpellLink id={SPELLS.VIPERS_VENOM_TALENT.id} /> procs, and to not cast <SpellLink id={this.spellKnown.id} /> before you've spent the <SpellLink id={SPELLS.VIPERS_VENOM_TALENT.id} /> buff.</>) .icon(SPELLS.VIPERS_VENOM_TALENT.icon) .actual(`${actual} wasted procs of Viper's Venom`) .recommended(`<${recommended} is recommended`); }); } statistic() { return ( <TalentStatisticBox talent={SPELLS.VIPERS_VENOM_TALENT.id} value={( <> {this.procs} / {this.wastedProcs + this.procs} procs used<br /> <ItemDamageDone amount={this.bonusDamage} /> </> )} tooltip={( <> <ul> <li>Average time between gaining Viper's Venom buff and using it was <b>{this.averageTimeBetweenBuffAndUsage}</b> seconds. <ul> <li>Note: This accounts for the GCD after the {this.spellKnown.name} proccing Viper's Venom. </li> {this.wastedProcs > 0 && <li>You wasted {this.wastedProcs} procs by gaining a new proc, whilst your current proc was still active.</li>} </ul> </li> </ul> </> )} /> ); } } export default VipersVenom;
docs/src/sections/BadgeSection.js
lzcmaro/react-ratchet
import React from 'react'; import Samples from '../Samples' import ReactPlayground from '../ReactPlayground' export default function BadgeSection() { return ( <div> <ReactPlayground id="badges" title='Badges' desc='标记' codeText={Samples.Badge} /> </div> ); };
pkg/interface/groups/src/js/components/lib/icons/sigil.js
ngzax/urbit
import React, { Component } from 'react'; import { sigil, reactRenderer } from 'urbit-sigil-js'; export class Sigil extends Component { render() { const { props } = this; const classes = props.classes || ''; const rgb = { r: parseInt(props.color.slice(1, 3), 16), g: parseInt(props.color.slice(3, 5), 16), b: parseInt(props.color.slice(5, 7), 16) }; const brightness = ((299 * rgb.r) + (587 * rgb.g) + (114 * rgb.b)) / 1000; const whiteBrightness = 255; let foreground = 'white'; if ((whiteBrightness - brightness) < 50) { foreground = 'black'; } if (props.ship.length > 14) { return ( <div className={'bg-black dib ' + classes} style={{ width: props.size, height: props.size }} ></div> ); } else { return ( <div className={'dib ' + classes} style={{ flexBasis: props.size, backgroundColor: props.color }} > {sigil({ patp: props.ship, renderer: reactRenderer, size: props.size, colors: [props.color, foreground] })} </div> ); } } }
src/svg-icons/image/compare.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCompare = (props) => ( <SvgIcon {...props}> <path d="M10 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h5v2h2V1h-2v2zm0 15H5l5-6v6zm9-15h-5v2h5v13l-5-6v9h5c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ImageCompare = pure(ImageCompare); ImageCompare.displayName = 'ImageCompare'; ImageCompare.muiName = 'SvgIcon'; export default ImageCompare;
app.js
teamhacksmiths/food-drivr-frontend
import express from 'express'; // import React from 'react'; // import { renderToString } from 'react-dom/server' // import { match, RouterContext } from 'react-router' //import routes from './app/config/routes'; const app = express(); const path = require('path'); const port = process.env.NODE_ENV === 'production' ? process.env.PORT : 3000; // app.use((req, res) => { // // Note that req.url here should be the full URL path from // // the original request, including the query string. // match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { // if (error) { // res.status(500).send(error.message); // } else if (redirectLocation) { // res.redirect(302, redirectLocation.pathname + redirectLocation.search); // } else if (renderProps) { // // You can also check renderProps.components or renderProps.routes for // // your "not found" component or route respectively, and send a 404 as // // below, if you're using a catch-all route. // res.status(200).send(renderToString(<RouterContext {...renderProps} />)); // } else { // res.status(404).send('Not found'); // } // }); // }); app.use(express.static(__dirname + '/build')); app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'build/index.html')); }); app.listen(port, '0.0.0.0', (err) => { if (err) { console.warn(err); } console.info('==> 🌎 Listening on port %s. Open up http://0.0.0.0:%s/ in your browser.', port, port); });
src/components/fluid-commons/fluid-table/TableEditableColumn.js
great-design-and-systems/cataloguing-app
import { TABLE_CANCEL_EDIT, TABLE_EDIT_SUBMIT, TABLE_SET_NEW_VALUE, TABLE_SUBMIT_NEW_VALUE } from './fluid.info'; import FluidFunc from 'fluid-func'; import PropTypes from 'prop-types'; import React from 'react'; export class TableEditableColumn extends React.Component { constructor(props) { super(props); this.state = { value: '' }; this.thisOnChange = this.onChange.bind(this); this.thisOnSubmit = this.onSubmit.bind(this); } componentWillMount() { this.setValue(this.props.value[this.props.column.field]); } onSubmit(event) { event.preventDefault(); if (FluidFunc.exists(`${TABLE_EDIT_SUBMIT}${this.props.tableName}`)) { if (this.props.value.isNew) { FluidFunc.start([`${TABLE_SUBMIT_NEW_VALUE}${this.props.tableName}`, `${TABLE_EDIT_SUBMIT}${this.props.tableName}`, `${TABLE_CANCEL_EDIT}${this.props.tableName}`], { isNew: true }); } else { const updatedValue = { ...this.props.value }; updatedValue[this.props.column.field] = this.state.value; FluidFunc.start([`${TABLE_EDIT_SUBMIT}${this.props.tableName}`, `${TABLE_CANCEL_EDIT}${this.props.tableName}`], { updatedValue, currentValue: this.props.value }); } } } onChange(event) { if (this.props.value.isNew) { FluidFunc.start(`${TABLE_SET_NEW_VALUE}${this.props.tableName}`, { field: this.props.column.field, value: event.target.value }); } this.setValue(event.target.value); } setValue(value) { this.setState({ value }); } render() { let colElem = <td />; const className = `${this.props.column.className || ''} ${this.props.columnClass || ''}`; if (this.props.column.editableComponent) { colElem = (<td style={this.props.column.style} className={className}> <form onSubmit={this.thisOnSubmit} onChange={this.thisOnChange} className="editable-column-form">{colElem.editableComponent({ value: this.props.value, column: this.props.column, currentValue: this.state.value })}</form></td>); } else { colElem = (<td style={this.props.column.style} className={className}> <form onSubmit={this.thisOnSubmit} onChange={this.thisOnChange} className="editable-column-form"> <input name={this.props.column.field} className="editable-column" value={this.state.value} /></form> </td>); } return colElem; } } TableEditableColumn.propTypes = { column: PropTypes.object.isRequired, value: PropTypes.object, columnClass: PropTypes.string, tableName: PropTypes.string.isRequired, };
web/utils/select-styles.js
earaujoassis/watchman
import React from 'react'; const groupStyles = { display: 'flex', alignItems: 'center', justifyContent: 'space-between' }; const groupBadgeStyles = { backgroundColor: '#EBECF0', borderRadius: '2em', color: '#172B4D', display: 'inline-block', fontSize: 12, fontWeight: 'normal', lineHeight: '1', minWidth: 1, padding: '0.16666666666667em 0.5em', textAlign: 'center' }; export const formatGroupLabel = data => ( <div style={groupStyles}> <span>{data.label}</span> <span style={groupBadgeStyles}>{data.options.length}</span> </div> );
react-flux-mui/js/material-ui/src/svg-icons/content/content-copy.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentContentCopy = (props) => ( <SvgIcon {...props}> <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/> </SvgIcon> ); ContentContentCopy = pure(ContentContentCopy); ContentContentCopy.displayName = 'ContentContentCopy'; ContentContentCopy.muiName = 'SvgIcon'; export default ContentContentCopy;
src/containers/LoginStatus.js
ftorre104/todolist-redux
import React from 'react' import { connect } from 'react-redux' import { login, logout } from '../actions' let LoginStatus = ({ dispatch, user }) => { let input // dispatch({ // type: 'LOG_IN', // name: 'fede', // email: 'ft@gm' // }) // These are EQUIVALENT. // dispatch(login('fede', 'fede@gmail.com')) if (!user.loggedIn) { return ( <div> <button onClick={() => { console.log('logging in...') dispatch(login('fede', 'fede@gmail.com')) }}> Login </button> </div> ) } else { return ( <div> <button onClick={() => { console.log('goodbye. logging out...') dispatch(logout()) }}> logout </button> <p> hello {user.name} </p> <p> {user.email} </p> </div> ) } } // this function says "from our root master store // object, aka state, pull out state.user and pass it in to // my component as a prop called 'user'" const mapStateToProps = (state) => { return { user: state.user } } // this simply binds the mapStateToProps fn we just defined // it will effectively listen to changes in our store's state.user // if something changes, pass props into LoginStatus. LoginStatus = connect(mapStateToProps)(LoginStatus) // in this component, we mixed the presentation and container logic // the container logic is literally just the mapStateToProps // the presentation logic is the render fn above. export default LoginStatus
src/mixins/OverlayMixin.js
jiachitor/TOTO-UI
'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; /** * Overlay Mixin * * @desc `overlay` is something like Popover, Modal, etc. * */ module.exports = { //propTypes: { // container: React.PropTypes.node //}, componentDidMount: function () { this._renderOverlay(); }, componentDidUpdate: function () { this._renderOverlay(); }, // Remove Overlay related DOM node componentWillUnmount: function () { this._unmountOverlay(); if (this._overlayWrapper) { this.getContainerDOMNode().removeChild(this._overlayWrapper); this._overlayWrapper = null; } }, // Create Overlay wrapper _mountOverlayWrapper: function () { this._overlayWrapper = document.createElement('div'); this.getContainerDOMNode().appendChild(this._overlayWrapper); }, // Render Overlay to wrapper _renderOverlay: function () { if (!this._overlayWrapper) { this._mountOverlayWrapper(); } let overlay = this.renderOverlay(); if (overlay !== null) { this._overlayInstance = ReactDOM.render(overlay, this._overlayWrapper); } else { // Unmount if the component is null for transitions to null this._unmountOverlay(); } }, // Remove a mounted Overlay from wrapper _unmountOverlay: function () { React.unmountComponentAtNode(this._overlayWrapper); this._overlayInstance = null; }, getOverlayDOMNode: function () { if (this._overlayInstance) { return ReactDOM.findDOMNode(this._overlayInstance); } return null; }, getContainerDOMNode: function () { return ReactDOM.findDOMNode(this.props.container) || document.body; }, };
app/containers/Shop.js
suyiya/wantplus-react-native
/** * Created by SUYIYA on 16/8/30. */ 'use strict'; import React, { Component } from 'react'; import { View, StyleSheet, Image, Text, Platform } from 'react-native'; export default class Shop extends Component { render() { return ( <View style={styles.container}> <View style={{flex: 1, backgroundColor: 'red'}}> <Text>welcome to shop</Text> </View> </View> ); } } const styles = StyleSheet.create({ container: { marginTop:(Platform.OS === 'android' ? 0 : 20), flex: 1, }, });
src/native/app/components/Text.js
xiankai/triple-triad-solver
import React from 'react'; import theme from '../themes/initial'; import { StyleSheet, Text } from 'react-native'; // https://github.com/facebook/react-native/issues/7877 const round = value => Math.round(value); const styles = StyleSheet.create({ text: { // eslint-disable-line react-native/no-unused-styles color: theme.textColor, fontFamily: theme.fontFamily, fontSize: theme.fontSize, lineHeight: round(theme.fontSize * theme.lineHeight), }, }); // Normalize multiline strings because Text component preserves spaces. const normalizeMultilineString = message => message.replace(/ +/g, ' ').trim(); class AppText extends React.Component { static propTypes = { children: React.PropTypes.node, style: Text.propTypes.style, }; onTextRef(text) { this.text = text; } setNativeProps(nativeProps) { this.text.setNativeProps(nativeProps); } getTextStyleWithMaybeComputedLineHeight() { const { style } = this.props; if (!style) { return styles.text; } const customFontSize = StyleSheet.flatten(style).fontSize; if (!Number.isInteger(customFontSize)) { return [styles.text, style]; } const lineHeight = round(customFontSize * theme.lineHeight); return [styles.text, style, { lineHeight }]; } render() { const { children } = this.props; const textStyle = this.getTextStyleWithMaybeComputedLineHeight(); return ( <Text {...this.props} ref={text => this.onTextRef(text)} style={textStyle} > {typeof children === 'string' ? normalizeMultilineString(children) : children } </Text> ); } } export default AppText;
src/decorators/withViewport.js
tcrosen/nhl-scores
/*! 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 'fbjs/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_EVENT, 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}); // eslint-disable-line react/no-set-state } }; } export default withViewport;
src/components/Footer/Footer.js
jackgardner/tactics
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import s from './Footer.scss'; import withStyles from '../../decorators/withStyles'; import Link from '../Link'; @withStyles(s) class Footer extends Component { render() { return ( <div className={s.root}> <div className={s.container}> <span className={s.text}>© Your Company</span> <span className={s.spacer}>·</span> <a className={s.link} href="/" onClick={Link.handleClick}>Home</a> <span className={s.spacer}>·</span> <a className={s.link} href="/privacy" onClick={Link.handleClick}>Privacy</a> <span className={s.spacer}>·</span> <a className={s.link} href="/not-found" onClick={Link.handleClick}>Not Found</a> </div> </div> ); } } export default Footer;
src/components/Adv/Adv.js
febobo/react-redux-start
import React from 'react' import ad4 from '../../static/images/ad4.jpg' import classes from './Adv.scss' type Props = { }; export class Adv extends React.Component { props: Props; render () { const advProps = { style : {display:"inline-block",width:"970px",height:"90px"}, client : 'ca-pub-5722932343401905', slot : '1843492278', // advBoxStyle : { paddingTop:"25px", textAlign : "center"} } return ( <div className={classes.adTop}> <a href="#"><img src={ad4} /></a> </div> ) } } export default Adv
app/components/Calendar/Calendar.js
zchen9/DonutTab
import React from 'react'; import Weather from '../Weather/Weather.js'; require('./Calendar.scss'); const WEEKS = ['Sun', 'Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat']; const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; export default class Calendar extends React.Component { constructor(props) { super(props); this.state = { curDateVal: this._getDateVal(), curWeeks: [], pickWeek: this._getDateVal().week }; } componentDidMount() { let curWeeks = this._genCurWeek(this._getDateVal()); this.setState({ curWeeks: curWeeks, pickWeek: this._getDateVal().week }); } weekClick(ev) { let pickWeek = +ev.target.getAttribute('data-week'); this.weekChange(pickWeek); } weekChange(week) { this.setState({ pickWeek: week }); } _getDateVal() { var self = this, curTime = new Date(), day = curTime.getDate(), month = curTime.getMonth(), year = curTime.getFullYear(), week = curTime.getDay(); return { year: year, month: month, day: day, week: week }; } _getMonthLen(month, year) { switch(month + 1) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; break; case 4: case 6: case 9: case 11: return 30; break; case 2: if ((year % 100 === 0 && year % 400 === 0) || (year % 100 !== 0 && year % 4 === 0)) { return 29; } else { return 28; } break; } } _genCurWeek(time) { var weekLen = 7, curDay = time.day || this._getDateVal().day, curWeek = +(time.week + '' || this._getDateVal().week), curMonth = +(time.month + '' || this._getDateVal().month), curYear = time.year || this._getDateVal().year, weekArr = [], beforeDay = curDay - curWeek, afterDay = curDay, firstDay = 1, lastDay = this._getMonthLen(curMonth, curYear); for (var i = 0; i < weekLen; i++) { if (i < curWeek) { if (beforeDay > 0) { weekArr.push(beforeDay); beforeDay += 1; } else { weekArr.push(''); beforeDay += 1; } } else if (i > curWeek) { if (afterDay < lastDay) { afterDay += 1; weekArr.push(afterDay); } else { weekArr.push(firstDay++); } } } weekArr.splice(curWeek, 0, curDay); return weekArr; } _convertTime(time, type) { var timeTmp = ''; switch(type) { case 'week': timeTmp = WEEKS[time]; break; case 'month': timeTmp = MONTHS[time]; break; case 'hour': case 'min': case 'sec': default: timeTmp = time >= 10 ? time : '0' + time; break; } return timeTmp; } render() { var self = this, curDateVal = this.state.curDateVal, curWeeks = this.state.curWeeks, pickWeek = this.state.pickWeek; return ( <div className="calendar-container"> <h3 className="calendar-head"> <i className="fa fa-fw fa-calendar-o"></i> <span className="calendar-title"> {curDateVal.year} {this._convertTime(curDateVal.month, 'month')} <small>{this._convertTime(curDateVal.day, 'day')}</small></span> </h3> <ul className="calendar-week clearfix"> {WEEKS.map((item, idx) => { return ( <li key={idx}>{item}</li> ) })} </ul> <ul className="calendar-week clearfix"> {curWeeks.map((item, idx) => { return ( <li key={idx}> {item ? (<span className={pickWeek === idx ? 'active' : ''} data-week={idx} onClick={self.weekClick.bind(self)}>{item}</span>) : item } </li> ) })} </ul> <Weather pickIndex={pickWeek - curDateVal.week} /> </div> ); } }
src/routes/Counter/components/Counter.js
salvocanna/shotio
import React from 'react' import PropTypes from 'prop-types' export const Counter = ({ counter, increment, doubleAsync }) => ( <div style={{ margin: '0 auto' }} > <h2>Counter: {counter}</h2> <button className='btn btn-primary' onClick={increment}> Increment </button> {' '} <button className='btn btn-secondary' onClick={doubleAsync}> Double (Async) </button> </div> ) Counter.propTypes = { counter: PropTypes.number.isRequired, increment: PropTypes.func.isRequired, doubleAsync: PropTypes.func.isRequired, } export default Counter
pootle/static/js/shared/components/ModalContainer.js
evernote/zing
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import cx from 'classnames'; import React from 'react'; import tabInScope from 'utils/tabInScope'; import './lightbox.css'; const classNames = { lock: 'lightbox-lock', }; const keys = { ESC: 27, TAB: 9, }; const ModalContainer = React.createClass({ propTypes: { children: React.PropTypes.node.isRequired, onClose: React.PropTypes.func.isRequired, className: React.PropTypes.string, style: React.PropTypes.object, }, /* Lifecycle */ componentWillMount() { this._previousFocus = document.activeElement; }, componentDidMount() { if (!document.body.classList.contains(classNames.lock)) { this._ownsLock = true; document.body.classList.add(classNames.lock); document.addEventListener('keydown', this.handleKeyDown); } }, componentWillUnmount() { if (this._ownsLock) { document.body.classList.remove(classNames.lock); document.removeEventListener('keydown', this.handleKeyDown); } this._previousFocus.focus(); }, _previousFocus: null, _ownsLock: false, /* Handlers */ handleKeyDown(e) { if (e.keyCode === keys.TAB) { tabInScope(this.refs.body, e); } if (e.keyCode === keys.ESC) { this.props.onClose(); } }, /* Layout */ render() { return ( <div className="lightbox-bg"> <div className="lightbox-container"> <div className={cx('lightbox-body', this.props.className)} ref="body" style={this.props.style} tabIndex="-1" > {this.props.children} </div> </div> </div> ); }, }); export default ModalContainer;
src/routes/DebisResources/components/DebisResourcesView.js
houston88/housty-home-react
import React from 'react' // import { Link } from 'react-router' import Card from '../../../components/Card' import './DebisResourcesView.scss' import TPT from '../assets/Hands.jpg' import ART from '../assets/Art.jpg' import SHOP from '../assets/Store.jpg' import ESCAP from '../assets/Escape.jpg' // import WEEK from '../assets/week.jpg' import LESS from '../assets/Lessons.jpg' import ORIE from '../assets/Orient.jpg' // pure render component export const DebisResourcesView = (props) => ( <div className='debis-resources'> <div className='container'> {/* <section className='top-panel'> <div className='info'> <a className='button' target='_blank' href='https://www.teacherspayteachers.com/Store/The-Tutors-Assistant'> My Store </a> <Link className='button' to='/debis-resources/orientation'>Orientation</Link> </div> </section> */} <div className='grade-sections'> <section> <h2>Foundations</h2> <div className='cards'> <Card image={ART} brand='pdf' url='https://www.teacherspayteachers.com/Product/Giotto-Biogrophy-for-Kids-CC-Cycle-1-Week-13-4523704' label='Scripts for Art Lesson' /> <Card image={TPT} brand='pdf' url='https://www.teacherspayteachers.com/Product/Giotto-Biogrophy-for-Kids-CC-Cycle-1-Week-13-4523704' label='Scripts for Hands-On Science Lesson' /> </div> </section> <section> <h2>Essentials</h2> <div className='cards'> <Card image={ORIE} brand='pdf' url='/debi/orientation.html' label='Orientation Meeting' /> {/* <Card image={WEEK} brand='pdf' url='/debi/lessonplans.html' label='Week by Week Resources' /> */} {/* <Card image={HANDY} brand='pdf' url='/debi' label='Handy Handouts' /> */} <Card image={LESS} brand='pdf' url='/debi/lessonplans.html' label='My Lesson Plans' /> <Card image={ESCAP} brand='pdf' url='https://www.teacherspayteachers.com/Store/The-Tutors-Assistant' label='Escape Room' /> </div> </section> <section> <h2>Shop</h2> <div className='cards'> <Card image={SHOP} brand='pdf' url='https://www.teacherspayteachers.com/Store/The-Tutors-Assistant' label='The Tutor&#39;s Assistant' /> </div> </section> </div> </div> </div> ) export default DebisResourcesView
app/components/gui/preferencesModal.js
todbot/Blink1Control2
"use strict"; // import React from 'react'; var React = require('react'); var Col = require('react-bootstrap').Col; var Row = require('react-bootstrap').Row; var Modal = require('react-bootstrap').Modal; var ButtonInput = require('react-bootstrap').ButtonInput; var Button = require('react-bootstrap').Button; var Form = require('react-bootstrap').Form; var FormControl = require('react-bootstrap').FormControl; var FormGroup = require('react-bootstrap').FormGroup; var ControlLabel = require('react-bootstrap').ControlLabel; var Radio = require('react-bootstrap').Radio; var Checkbox = require('react-bootstrap').Checkbox; var isAccelerator = require("electron-is-accelerator"); var PatternsService = require('../../server/patternsService'); var Blink1Service = require('../../server/blink1Service'); var ApiServer = require('../../server/apiServer'); var MenuMaker = require('../../menuMaker'); var conf = require('../../configuration'); var log = require('../../logger'); var Eventer = require('../../eventer'); var Blink1SerialOption = require('./blink1SerialOption'); var app = require('electron').remote.app; var path = require('path'); const propTypes = { }; var PreferencesModal = React.createClass({ propTypes: { show: React.PropTypes.bool, blink1Serials: React.PropTypes.array }, getInitialState: function() { return this.loadSettings(); }, // doing this so we get guaranteed fresh config componentWillReceiveProps: function(nextProps) { // if (!this.props.show) { if( !this.props.show && nextProps.show ) { var settings = this.loadSettings(); this.setState(settings); } }, loadSettings: function() { var patterns = PatternsService.getAllPatterns(); var settings = { hideDockIcon: conf.readSettings('startup:hideDockIcon') || false, startMinimized: conf.readSettings('startup:startMinimized') || false, startAtLogin: conf.readSettings('startup:startAtLogin') || false, startupPattern: conf.readSettings('startup:startupPattern') || "", // FIXME: not used yet shortcutPrefix: conf.readSettings('startup:shortcutPrefix') || 'CommandOrControl+Shift', shortcutResetKey: conf.readSettings('startup:shortcutResetKey') || 'R', enableGamma: conf.readSettings('blink1Service:enableGamma') || false, hostId: Blink1Service.getHostId(), blink1ToUse: conf.readSettings('blink1Service:blink1ToUse') || "0", // 0 == use first avail allowMultiBlink1: conf.readSettings('blink1Service:allowMulti') || false, apiServerEnable: conf.readSettings('apiServer:enabled') || false, apiServerPort: conf.readSettings('apiServer:port') || 8934, apiServerHost: conf.readSettings('apiServer:host') || 'localhost', proxyEnable: conf.readSettings('proxy:enable') || false, proxyHost: conf.readSettings('proxy:host') || 'localhost', proxyPort: conf.readSettings('proxy:port') || 8080, proxyUser: conf.readSettings('proxy:username') || '', proxyPass: conf.readSettings('proxy:password') || '', playingSerialize: conf.readSettings('patternsService:playingSerialize') || false, patterns: patterns, patternId: 'whiteflashes', nonComputerPattern: patterns[0].id, errorMsg: '' }; return settings; }, saveSettings: function() { if (!Blink1Service.setHostId(this.state.hostId)) { this.setState({errormsg: 'HostId must be 8-digit hexadecimal'}); return false; } conf.saveSettingsMem('startup:hideDockIcon', this.state.hideDockIcon); conf.saveSettingsMem('startup:startMinimized', this.state.startMinimized); conf.saveSettingsMem('startup:startAtLogin', this.state.startAtLogin); // conf.saveSettings('startup:startupPattern', this.state.startupPattern); conf.saveSettingsMem('startup:shortcutPrefix', this.state.shortcutPrefix); conf.saveSettingsMem('startup:shortcutResetKey', this.state.shortcutResetKey); conf.saveSettingsMem('blink1Service:enableGamma', this.state.enableGamma); conf.saveSettingsMem('blink1Service:blink1ToUse', this.state.blink1ToUse); conf.saveSettingsMem('blink1Service:allowMulti', this.state.allowMultiBlink1); conf.saveSettingsMem('apiServer:enabled', this.state.apiServerEnable); conf.saveSettingsMem('apiServer:port', this.state.apiServerPort); conf.saveSettingsMem('apiServer:host', this.state.apiServerHost); conf.saveSettingsMem('proxy:enable', this.state.proxyEnable); conf.saveSettingsMem('proxy:host', this.state.proxyHost); conf.saveSettingsMem('proxy:port', this.state.proxyPort); conf.saveSettingsMem('proxy:username', this.state.proxyUser); conf.saveSettingsMem('proxy:password', this.state.proxyPass); conf.saveSettingsMem('patternsService:playingSerialize', this.state.playingSerialize); conf.saveSettingsSync(); // save settings to disk Blink1Service.reloadConfig(); ApiServer.reloadConfig(); PatternsService.reloadConfig(); MenuMaker.setupMainMenu(); // FIXME: find way to do spot edit of shortcut keys? MenuMaker.updateTrayMenu(); this.updateStartAtLogin(); if (process.platform === 'darwin') { if (this.state.hideDockIcon) { app.dock.hide(); } else { app.dock.show(); } } // FIXME: a hack to get ToolTable to refetch allowMulti pref Eventer.addStatus({type: 'info', source: 'preferences', text: 'settings updated'}); return true; }, updateStartAtLogin: function() { // log.msg("PreferencesModal.updateStartAtLogin:",this.state.startAtLogin); app.setLoginItemSettings({ openAtLogin: this.state.startAtLogin, }); }, close: function() { if( this.saveSettings() ) { this.props.onSave(this.state); } }, cancel: function() { this.props.onCancel(); }, handleBlink1SerialChange: function(serial) { log.msg("handleBlink1SerialChange: ", serial); PatternsService.playPatternFrom('prefs', '~blink:#888888-3', serial); this.setState({blink1ToUse: serial}); }, handleBlink1NonComputerSet: function(event) { var choice = event.target.value log.msg("handleBlink1NonComputerSet: ",choice, ",", this.state.nonComputerPattern ); var err = ''; if( choice === 'off' ) { log.msg("settting OFF"); var patt = PatternsService.newPatternFromString( 'offpatt', '0,#000000,0.0,0'); err = Blink1Service.writePatternToBlink1(patt,true,0); } else if( choice === 'default' ) { log.msg("settting default:",Blink1Service.defaultPatternStr); var patt = PatternsService.newPatternFromString('default', Blink1Service.defaultPatternStr); err = Blink1Service.writePatternToBlink1(patt,true,0); } else if ( choice === 'pattern' ) { var patt = PatternsService.getPatternById(this.state.nonComputerPattern); log.msg("setting pattern:",patt); err = Blink1Service.writePatternToBlink1(patt,true,0); } err = ( !err ) ? "success" : err; this.setState({errorMsg: err}); }, handleInputChange: function(event) { var target = event.target; var value = target.type === 'checkbox' ? target.checked : target.value; var name = target.name; if( name == 'shortcutResetKey' && value != '') { var accel = this.state.shortcutPrefix +"+"+ value; log.msg("accel:",accel); if( !isAccelerator(accel) ) { this.setState({errorMsg: "Cannot use '"+value+"' as shortcut key"}); return; } } this.setState({[name]: value}); }, render: function() { var createPatternOption = function(patt, idx) { return (<option key={idx} value={patt.id}>{patt.name}</option>); }; var createShortcutPrefixOption = function(item, idx) { return (<option key={idx} value={item.what}>{item.what2}</option>); }; var isMac = (process.platform === 'darwin'); // var showIfMac = (isMac) ? '':'hidden'; var cmdKeyStr = (isMac) ? 'Cmd' : 'Ctrl'; var sectStyle = { border: '1px solid #ddd', paddingLeft: 15, paddingBottom: 10 }; var errorSectStyle = { paddingLeft: 15, color:'red'}; return ( <div> <Modal show={this.props.show} onHide={this.close} bsSize="large"> <Modal.Header> <Modal.Title style={{fontSize:"95%"}}>Preferences</Modal.Title> </Modal.Header> <Modal.Body style={{fontSize:"100%", paddingTop:0}}> <p style={{color: "#f00"}}>{this.state.errormsg}</p> <Row> <Col md={4}> <div style={sectStyle}> <h5><u> General </u></h5> <Form horizontal> <Checkbox bsSize="small" title="On next restart, app is systray/menubar only" name="startMinimized" checked={this.state.startMinimized} onChange={this.handleInputChange}> Start minimized </Checkbox> <Checkbox bsSize="small" title="Start app at login" name="startAtLogin" checked={this.state.startAtLogin} onChange={this.handleInputChange} > Start at login </Checkbox> {isMac ? <Checkbox bsSize="small" title="Don't show app in Dock" name="hideDockIcon" checked={this.state.hideDockIcon} onChange={this.handleInputChange} > Hide Dock Icon </Checkbox> : <div/>} <Checkbox bsSize="small" title="Use more accurate colors. When off, colors are brighter" name="enableGamma" checked={this.state.enableGamma} onChange={this.handleInputChange} > LED gamma-correction </Checkbox> <Checkbox bsSize="small" title="Only allow color patterns to play single-file, not at the same time" name="playingSerialize" checked={this.state.playingSerialize} onChange={this.handleInputChange} > Pattern play serialize </Checkbox> </Form> </div> <div style={sectStyle}> <h5><u> Global Shortcut Keys (on restart) </u></h5> <Form horizontal> <Row className="form-group form-group-sm"> <Col xs={3}> Reset Alerts </Col> <Col xs={5}> <FormControl bsSize="small" componentClass="select" name="shortcutPrefix" value={this.state.shortcutPrefix} onChange={this.handleInputChange} > <option value="CommandOrControl+Shift">{cmdKeyStr}+Shift</option> <option value="CommandOrControl">{cmdKeyStr}</option> <option value="CommandOrControl+Alt">{cmdKeyStr}+Alt</option> <option value="Alt">Alt</option> </FormControl> </Col> <Col xs={3}> <FormControl bsSize="small" type="text" label="" placeholder="" size="1" name="shortcutResetKey" value={this.state.shortcutResetKey} onChange={this.handleInputChange} /> </Col> </Row> </Form> </div> </Col> <Col md={4}> <div style={sectStyle}> <h5><u> blink(1) device use </u></h5> <Form horizontal> <FormGroup controlId="formHostId" bsSize="small"> <Col sm={6} componentClass={ControlLabel}> HostId </Col> <Col sm={5}> <FormControl type="text" label="HostId" placeholder="" name="hostId" value={this.state.hostId} onChange={this.handleInputChange} /> </Col> </FormGroup> <Blink1SerialOption label="Preferred device" defaultText="-use first-" labelColWidth={6} controlColWidth={5} bsSize="small" serial={this.state.blink1ToUse} onChange={this.handleBlink1SerialChange}/> <FormGroup bsSize="small"> <Col sm={11}> <Checkbox name="allowMultiBlink1" checked={this.state.allowMultiBlink1} onChange={this.handleInputChange}> Use multi blink(1) devices in rules </Checkbox> </Col> </FormGroup> </Form> </div> <div style={sectStyle}> <h5><u> API server configuration </u></h5> <Form horizontal> <FormGroup bsSize="small"> <Col sm={11}> <Checkbox name="apiServerEnable" checked={this.state.apiServerEnable} onChange={this.handleInputChange} > Start API server </Checkbox> </Col> </FormGroup> <FormGroup controlId="formPort" bsSize="small"> <Col sm={3} componentClass={ControlLabel}> port </Col> <Col sm={7}> <FormControl type="number" placeholder="" name="apiServerPort" value={this.state.apiServerPort} onChange={this.handleInputChange} /> </Col> </FormGroup> <FormGroup controlId="formHost" bsSize="small"> <Col sm={3} componentClass={ControlLabel}> host </Col> <Col sm={4}> <Radio name="apiServerHost" value="localhost" checked={this.state.apiServerHost==='localhost'} onChange={this.handleInputChange} > localhost </Radio> </Col> <Col xs={4}> <Radio name="apiServerHost" value="any" checked={this.state.apiServerHost==='any'} onChange={this.handleInputChange} > any </Radio> </Col> </FormGroup> </Form> </div> </Col> <Col md={4} title="Set what the blink(1) does when powered but no computer"> <div style={sectStyle}> <h5><u> blink(1) no-computer mode </u></h5> <small>Set what blink(1) does when powered but no computer controlling it, aka "nightlight mode". </small> <Form horizontal> <FormGroup controlId="formNonComputerMode" bsSize="small"> <Col sm={10}> <Button bsSize="xsmall" value="off" block title="blink(1) is off when powered but computer is off" onClick={this.handleBlink1NonComputerSet}> Set to Off </Button> <Button bsSize="xsmall" value="default" block title="blink(1) plays its default RGB pattern when powered but computer is off" onClick={this.handleBlink1NonComputerSet}> Set to Default </Button> <Button bsSize="xsmall" value="pattern" block title="blink(1) plays one the following patterns when powered but computer is off" onClick={this.handleBlink1NonComputerSet}> Set to Pattern: </Button> <FormControl bsSize="small" componentClass="select" name="nonComputerPattern" value={this.state.nonComputerPattern} onChange={this.handleInputChange} > {this.state.patterns.map( createPatternOption )} </FormControl> </Col> </FormGroup> </Form> </div> </Col> </Row> <Row> <Col> <div style={errorSectStyle}>{this.state.errorMsg}</div> </Col> </Row> </Modal.Body> <Modal.Footer> <Button bsSize="small" onClick={this.cancel}>Cancel</Button> <Button bsSize="small" onClick={this.close}>OK</Button> </Modal.Footer> </Modal> </div> ); } }); module.exports = PreferencesModal; // </div> style={{border:'1px solid #ddd', paddingLeft:15, opacity:0.5 }} > /* </Col> <Col md={4}> <div style={{border:'1px solid #ddd', paddingLeft:15, opacity:0.5 }} > <h5><u> blink(1) nightlight mode </u></h5> <form className="form-horizontal"> <Input labelClassName="col-xs-8" wrapperClassName="col-xs-12" bsSize="small" type="radio" label="Off / Dark" value="off" checked={this.state.blink1NonComputer==='off'} onChange={this.handleBlink1NonComputerChoice} /> <Input labelClassName="col-xs-8" wrapperClassName="col-xs-12" bsSize="small" type="radio" label="Default pattern" value="default" checked={this.state.blink1NonComputer==='default'} onChange={this.handleBlink1NonComputerChoice} /> <Row> <Col xs={4}> <Input labelClassName="col-xs-8" wrapperClassName="col-xs-12" bsSize="small" type="radio" label="Play:" value="pattern" checked={this.state.blink1NonComputer==='pattern'} onChange={this.handleBlink1NonComputerChoice} /> </Col><Col xs={8}> <Input labelClassName="col-xs-1" wrapperClassName="col-xs-10" bsSize="small" type="select" label="" name="patternId" value={this.state.patternId} onChange={this.handleInputChange} > {this.state.patterns.map( createPatternOption )} </Input> </Col></Row> <Row> <Col xs={1}></Col> <Col xs={2}> <ButtonInput bsSize="small" value="Set" onClick={this.handleBlink1NonComputerSet} /> </Col> </Row> </form> </div> </Col> </Row> */ /// old 3rd column /* <div style={{border:'1px solid #ddd', paddingLeft:15, opacity:0.5 }}> <h5><u> Proxy configuration </u></h5> <form className="form-horizontal"> <Input labelClassName="col-xs-8" wrapperClassName="col-xs-12" bsSize="small" type="checkbox" label="Use HTTP proxy" checkedLnk={this.linkState('proxyEnable')} /> <Input labelClassName="col-xs-3" wrapperClassName="col-xs-8" bsSize="small" type="text" label="host" placeholder="localhost" valueLink={this.lnkState('proxyHost')} /> <Input labelClassName="col-xs-3" wrapperClassName="col-xs-8" bsSize="small" type="number" label="port" placeholder="8080" valueLink={this.lnkState('proxyPort')} /> <Input labelClassName="col-xs-3" wrapperClassName="col-xs-8" bsSize="small" type="text" label="username" placeholder="" valueLink={this.lnkState('proxyUser')} /> <Input labelClassName="col-xs-3" wrapperClassName="col-xs-8" bsSize="small" type="text" label="password" placeholder="" valueLink={this.lnkState('proxyPass')} /> </form> </div> */
src/views/Login.js
astrauka/expensable-r1
import React from 'react'; export default class Login { render() { return ( <div> <h1>Login</h1> </div> ); } }
src/todos/components/TodoItem.js
nnance/react-backbone-flux-example
import React from 'react'; import TodoActions from '../TodoActions'; module.exports = React.createClass({ onToggle: function() { TodoActions.toggle(this.props.todo); }, onRemove: function(ev) { ev.preventDefault(); TodoActions.remove(this.props.todo); }, render: function() { var styles = { textDecoration: this.props.todo.get('complete') ? 'line-through' : 'none' }; return <div> <input type="checkbox" onClick={this.onToggle} />{' '} <span style={styles}>{this.props.todo.attributes.text}</span>{' '} <a href="#" onClick={this.onRemove}>[x]</a> </div> } });
js/components/layout/nested.js
mrcflorian/classbook
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { actions } from 'react-native-navigation-redux-helpers'; import { Container, Header, Title, Button, Icon, Left, Right, Body } from 'native-base'; import { Grid, Row, Col } from 'react-native-easy-grid'; import { Actions } from 'react-native-router-flux'; import { openDrawer } from '../../actions/drawer'; const { popRoute, } = actions; class NestedGrid extends Component { // eslint-disable-line static propTypes = { popRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } popRoute() { this.props.popRoute(this.props.navigation.key); } render() { return ( <Container> <Header> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="arrow-back" /> </Button> </Left> <Body> <Title>Nested Grid</Title> </Body> <Right /> </Header> <Grid> <Col style={{ backgroundColor: '#DD9E2C' }} /> <Col> <Row style={{ backgroundColor: '#00CE9F' }} /> <Row style={{ backgroundColor: '#635DB7' }} /> </Col> </Grid> </Container> ); } } function bindAction(dispatch) { return { popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(NestedGrid);
src/pages/sorting/Quicksort/Quicksort.js
hyy1115/react-redux-webpack3
import React from 'react' class Quicksort extends React.Component { render() { return ( <div>Quicksort</div> ) } } export default Quicksort
dev/js/uiComponents/text/store/text-container.js
artisnull/React-CMS
/* Filename: text-container.js Author: Zach Lambert Last Updated: 17 Apr 2017 Description: Connects Text to its reference in the store, exposes the available fonts from Google Fonts API, responds to deletion Props: ownData, fontObj, fontArr, activeElement, deleted PropMethods: none */ import React from 'react'; import {connect} from 'react-redux'; import Text from '../ui/text.jsx'; const mapStatetoProps = (state, ownProps) => { let activeElement = state.activeElemReducer.activeElement; let deleted = false; // Listen to store section corresponding to this container's id const type = ownProps.dataElement; const id = ownProps.id; let coll = state.elemCollReducer; const ownData = coll[type.toLowerCase() + 's'].byId[id] // If element has been deleted, don't continue if (ownData == null) { deleted = true; } return { ownData, fontObj: state.fontReducer.fontObj, fontArr: state.fontReducer.fontArr, activeElement, deleted, } } const mapDispatchToProps = (dispatch) => { return {} } export default connect(mapStatetoProps, mapDispatchToProps)(Text);
docs/src/examples/elements/Label/Types/LabelExampleIcon.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Icon, Label } from 'semantic-ui-react' const LabelExampleIcon = () => ( <div> <Label image> <img src='/images/avatar/small/ade.jpg' /> Adrienne <Icon name='delete' /> </Label> <Label image> <img src='/images/avatar/small/zoe.jpg' /> Zoe <Icon name='delete' /> </Label> <Label image> <img src='/images/avatar/small/nan.jpg' /> Nan <Icon name='delete' /> </Label> </div> ) export default LabelExampleIcon
spec/sections/LinkSection.js
kmees/react-fabric
import React from 'react' import Link from '../../src/Link' const LinkSection = () => ( <section> <h2>Link</h2> <Link href="http://react-fabric.github.io" title="docs">Docs</Link> </section> ) export default LinkSection
src/parser/shaman/shared/azerite/IgneousPotential.js
fyruna/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import { formatNumber } from 'common/format'; import TraitStatisticBox, { STATISTIC_ORDER } from 'interface/others/TraitStatisticBox'; import { calculateAzeriteEffects } from 'common/stats'; import calculateBonusAzeriteDamage from 'parser/core/calculateBonusAzeriteDamage'; import ItemDamageDone from 'interface/others/ItemDamageDone'; import StatTracker from 'parser/shared/modules/StatTracker'; class IgneousPotential extends Analyzer { static dependencies = { statTracker: StatTracker, }; damageGained = 0; traitBonus = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.IGNEOUS_POTENTIAL.id); if (!this.active) { return; } this.traitBonus = this.selectedCombatant.traitsBySpellId[SPELLS.IGNEOUS_POTENTIAL.id] .reduce((sum, rank) => sum + calculateAzeriteEffects(SPELLS.IGNEOUS_POTENTIAL.id, rank)[0], 0); this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.LAVA_BURST_DAMAGE), this._onLavaBurst); } _onLavaBurst(event) { this.damageGained += calculateBonusAzeriteDamage(event, [this.traitBonus], SPELLS.LAVA_BURST.coefficient, this.statTracker.currentIntellectRating)[0]; } statistic() { return ( <TraitStatisticBox position={STATISTIC_ORDER.OPTIONAL()} trait={SPELLS.IGNEOUS_POTENTIAL.id} value={<ItemDamageDone amount={this.damageGained} />} tooltip={`Igneous Potential did ${formatNumber(this.damageGained)} damage. Additional procs gained by the Lava Surge part are not calculated.`} /> ); } } export default IgneousPotential;
src/components/googe_map.js
framirez224/weather-app
import React, { Component } from 'react'; class GoogleMap extends Component { componentDidMount() { new google.maps.Map(this.map, { zoom: 12, center: { lat: this.props.lat, lng: this.props.lon, }, }); } render() { return ( <div ref={(m) => { this.map = m; }} /> // </div> ); } } export default GoogleMap;
frontend/app_v2/src/components/Story/StoryContainer.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' import StoryData from 'components/Story/StoryData' import StoryPresentation from 'components/Story/StoryPresentation' import StoryPresentationDrawer from 'components/Story/StoryPresentationDrawer' import Loading from 'components/Loading' function StoryContainer({ docId, isDrawer }) { const { entry, isLoading, sitename } = StoryData({ docId }) return ( <Loading.Container isLoading={isLoading}> {isDrawer ? <StoryPresentationDrawer entry={entry} sitename={sitename} /> : <StoryPresentation entry={entry} />} </Loading.Container> ) } // PROPTYPES const { bool, string } = PropTypes StoryContainer.propTypes = { docId: string, isDrawer: bool, } export default StoryContainer
fields/types/geopoint/GeoPointFilter.js
matthewstyers/keystone
import React from 'react'; import { FormField, FormInput, Grid, SegmentedControl, } from '../../../admin/client/App/elemental'; const DISTANCE_OPTIONS = [ { label: 'Max distance (km)', value: 'max' }, { label: 'Min distance (km)', value: 'min' }, ]; function getDefaultValue () { return { lat: undefined, lon: undefined, distance: { mode: DISTANCE_OPTIONS[0].value, value: undefined, }, }; } var TextFilter = React.createClass({ propTypes: { filter: React.PropTypes.shape({ lat: React.PropTypes.number, lon: React.PropTypes.number, distance: React.PropTypes.shape({ mode: React.PropTypes.string, value: React.PropTypes.number, }), }), }, statics: { getDefaultValue: getDefaultValue, }, getDefaultProps () { return { filter: getDefaultValue(), }; }, updateFilter (value) { this.props.onChange({ ...this.props.filter, ...value }); }, changeLat (evt) { this.updateFilter({ lat: evt.target.value }); }, changeLon (evt) { this.updateFilter({ lon: evt.target.value }); }, changeDistanceValue (evt) { this.updateFilter({ distance: { mode: this.props.filter.distance.mode, value: evt.target.value, }, }); }, changeDistanceMode (mode) { this.updateFilter({ distance: { mode, value: this.props.filter.distance.value, }, }); }, render () { const { filter } = this.props; const distanceModeVerb = filter.distance.mode === 'max' ? 'Maximum' : 'Minimum'; return ( <div> <Grid.Row xsmall="one-half" gutter={10}> <Grid.Col> <FormField label="Latitude" > <FormInput autoFocus onChange={this.changeLat} placeholder={'Latitude'} ref="latitude" required="true" step={0.01} type="number" value={filter.lat} /> </FormField> </Grid.Col> <Grid.Col> <FormField label="Longitude"> <FormInput onChange={this.changeLon} placeholder={'Longitude'} ref="longitude" required="true" step={0.01} type="number" value={filter.lon} /> </FormField> </Grid.Col> </Grid.Row> <FormField> <SegmentedControl equalWidthSegments onChange={this.changeDistanceMode} options={DISTANCE_OPTIONS} value={this.props.filter.distance.mode} /> </FormField> <FormInput onChange={this.changeDistanceValue} placeholder={distanceModeVerb + ' distance from point'} ref="distance" type="number" value={filter.distance.value} /> </div> ); }, }); module.exports = TextFilter;
src/components/CentreBox/CentreBox.js
GJMcGowan/personal_site
import React from 'react'; import './CentreBox.css'; const CentreBox = (props) => ( <div className='main'> <div className="center-box"> <div className="text"> {props.children} </div> </div> </div> ); export default CentreBox;
src/components/slide9-ref.js
lucky3mvp/react-demo
import React from 'react' export default React.createClass({ handleClick () { if (this.refs.myInput !== null) { this.refs.myInput.focus(); } }, render () { return ( <div className={this.props.className}> <input type="text" ref="myInput" /> <br /> <input type="button" value="Focus the text input" onClick={this.handleClick} /> </div> ) } })
app/javascript/flavours/glitch/features/compose/components/search.js
Kirishima21/mastodon
// Package imports. import classNames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import spring from 'react-motion/lib/spring'; import { injectIntl, FormattedMessage, defineMessages, } from 'react-intl'; import Overlay from 'react-overlays/lib/Overlay'; // Components. import Icon from 'flavours/glitch/components/icon'; // Utils. import { focusRoot } from 'flavours/glitch/util/dom_helpers'; import { searchEnabled } from 'flavours/glitch/util/initial_state'; import Motion from 'flavours/glitch/util/optional_motion'; const messages = defineMessages({ placeholder: { id: 'search.placeholder', defaultMessage: 'Search' }, }); class SearchPopout extends React.PureComponent { static propTypes = { style: PropTypes.object, }; render () { const { style } = this.props; const extraInformation = searchEnabled ? <FormattedMessage id='search_popout.tips.full_text' defaultMessage='Simple text returns statuses you have written, favourited, boosted, or have been mentioned in, as well as matching usernames, display names, and hashtags.' /> : <FormattedMessage id='search_popout.tips.text' defaultMessage='Simple text returns matching display names, usernames and hashtags' />; return ( <div style={{ ...style, position: 'absolute', width: 285, zIndex: 2 }}> <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}> {({ opacity, scaleX, scaleY }) => ( <div className='search-popout' style={{ opacity: opacity, transform: `scale(${scaleX}, ${scaleY})` }}> <h4><FormattedMessage id='search_popout.search_format' defaultMessage='Advanced search format' /></h4> <ul> <li><em>#example</em> <FormattedMessage id='search_popout.tips.hashtag' defaultMessage='hashtag' /></li> <li><em>@username@domain</em> <FormattedMessage id='search_popout.tips.user' defaultMessage='user' /></li> <li><em>URL</em> <FormattedMessage id='search_popout.tips.user' defaultMessage='user' /></li> <li><em>URL</em> <FormattedMessage id='search_popout.tips.status' defaultMessage='status' /></li> </ul> {extraInformation} </div> )} </Motion> </div> ); } } // The component. export default @injectIntl class Search extends React.PureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { value: PropTypes.string.isRequired, submitted: PropTypes.bool, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClear: PropTypes.func.isRequired, onShow: PropTypes.func.isRequired, openInRoute: PropTypes.bool, intl: PropTypes.object.isRequired, singleColumn: PropTypes.bool, }; state = { expanded: false, }; setRef = c => { this.searchForm = c; } handleChange = (e) => { const { onChange } = this.props; if (onChange) { onChange(e.target.value); } } handleClear = (e) => { const { onClear, submitted, value, } = this.props; e.preventDefault(); // Prevents focus change ?? if (onClear && (submitted || value && value.length)) { onClear(); } } handleBlur = () => { this.setState({ expanded: false }); } handleFocus = () => { this.setState({ expanded: true }); this.props.onShow(); if (this.searchForm && !this.props.singleColumn) { const { left, right } = this.searchForm.getBoundingClientRect(); if (left < 0 || right > (window.innerWidth || document.documentElement.clientWidth)) { this.searchForm.scrollIntoView(); } } } handleKeyUp = (e) => { const { onSubmit } = this.props; switch (e.key) { case 'Enter': onSubmit(); if (this.props.openInRoute) { this.context.router.history.push('/search'); } break; case 'Escape': focusRoot(); } } render () { const { intl, value, submitted } = this.props; const { expanded } = this.state; const hasValue = value.length > 0 || submitted; return ( <div className='search'> <label> <span style={{ display: 'none' }}>{intl.formatMessage(messages.placeholder)}</span> <input ref={this.setRef} className='search__input' type='text' placeholder={intl.formatMessage(messages.placeholder)} value={value || ''} onChange={this.handleChange} onKeyUp={this.handleKeyUp} onFocus={this.handleFocus} onBlur={this.handleBlur} /> </label> <div aria-label={intl.formatMessage(messages.placeholder)} className='search__icon' onClick={this.handleClear} role='button' tabIndex='0' > <Icon id='search' className={hasValue ? '' : 'active'} /> <Icon id='times-circle' className={hasValue ? 'active' : ''} /> </div> <Overlay show={expanded && !hasValue} placement='bottom' target={this}> <SearchPopout /> </Overlay> </div> ); } }