path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
src/PriceList.js
weizong85/coffee-test-code
import React from 'react'; class PriceList extends React.Component { addToOrderList() { this.props.addToOrderList(this) } render() { return ( <li> <div> {this.props.price.size} ${this.props.price.cost} <input type="button" onClick={this.addToOrderList.bind(this)} value='Add' /> </div> </li> ) } } export default PriceList;
stories/react/Input.stories.js
onap-sdc/sdc-ui
import React from 'react'; import { action } from '@storybook/addon-actions'; import Examples from './utils/Examples.js'; import ReactInput from '../../src/react/Input.js'; import InputDefaultHtml from '../../components/input/input.html'; import InputRequiredHtml from '../../components/input/input-required.html'; import InputNumberHtml from '../../components/input/input-number.html'; import InputViewOnlyHtml from '../../components/input/input-view-only.html'; import InputDisabledHtml from '../../components/input/input-disabled.html'; import InputPlaceholderHtml from '../../components/input/input-placeholder.html'; import InputErrorHtml from '../../components/input/input-error.html'; let examples = { 'Input Default': { jsx: <ReactInput name='input1' value='Default' label='I am a label' onChange={ action('input-change')}/>, html: InputDefaultHtml }, 'Input Required': { jsx: <ReactInput name='input2' value='Default' label='I am a label' onChange={ action('input-change')} isRequired/>, html: InputRequiredHtml }, 'Input Number': { jsx: <ReactInput name='input3' value='3' label='I am a label' type="number" onChange={ action('input-change')}/>, html: InputNumberHtml }, 'Input View Only': { jsx: <ReactInput value='Read Only Text' label='I am a label' onChange={ action('input-change')} readOnly/>, html: InputViewOnlyHtml }, 'Input Disabled': { jsx: <ReactInput value='Default' label='I am a label' onChange={ action('input-change')} disabled/>, html: InputDisabledHtml }, 'Input Placeholder': { jsx: <ReactInput name='input5' placeholder='Write Here...' label='I am a label' onChange={ action('input-change')}/>, html: InputPlaceholderHtml }, 'Input Error': { jsx: <ReactInput value='Default' name='input6' label='I am a label' errorMessage='This is the error message' onChange={ action('input-change')}/>, html: InputErrorHtml } } const Inputs = () => ( <Examples examples={examples} /> ); export default Inputs;
src/utils/devTools.js
Lukkub/Redux-ShopCartApp
import React from 'react'; import { createStore as initialCreateStore, compose } from 'redux'; export let createStore = initialCreateStore; let __DEV__ = false; if (__DEV__) { createStore = compose( require('redux-devtools').devTools(), require('redux-devtools').persistState( window.location.href.match(/[?&]debug_session=([^&]+)\b/) ), createStore ); } export function renderDevTools(store) { if (__DEV__) { let {DevTools, DebugPanel, LogMonitor} = require('redux-devtools/lib/react'); return ( <DebugPanel top right bottom> <DevTools store={store} monitor={LogMonitor} /> </DebugPanel> ); } return null; }
src/shared/form/RadioList.js
AusDTO/dto-digitalmarketplace-frontend
import React from 'react'; import PropTypes from 'prop-types' import { Control } from 'react-redux-form'; import StatefulError from './StatefulError'; const RadioList = (props) => { const { id, label, name, options, model, messages, validators } = props; return ( <div className="field"> <fieldset> <legend>{label}</legend> <StatefulError model={model} messages={messages} id={id} /> <div> {options.map((option, i) => { let fieldId = `${id}-${option.value}`; return ( <span key={i}> <Control.radio model={model} name={name} id={fieldId} value={option.value} validators={validators} /> <label htmlFor={fieldId}>{option.label}</label> </span> ) })} </div> </fieldset> </div> ); }; RadioList.propTypes = { id: PropTypes.string.isRequired, label: PropTypes.string.isRequired, name: PropTypes.string.isRequired, model: PropTypes.oneOfType([ PropTypes.func, PropTypes.string, ]).isRequired, options: PropTypes.arrayOf(PropTypes.shape({ label: PropTypes.oneOfType([ PropTypes.string, PropTypes.object ]), value: PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]) })).isRequired, validators: PropTypes.object, messages: PropTypes.object, }; export default RadioList;
src/html.js
jumpalottahigh/jumpalottahigh.github.io
import React from 'react' import PropTypes from 'prop-types' export default class HTML extends React.Component { render() { return ( <html {...this.props.htmlAttributes} lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="x-ua-compatible" content="ie=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> {this.props.headComponents} </head> <body {...this.props.bodyAttributes}> {this.props.preBodyComponents} <div key={`body`} id="___gatsby" dangerouslySetInnerHTML={{ __html: this.props.body }} /> {this.props.postBodyComponents} </body> </html> ) } } HTML.propTypes = { htmlAttributes: PropTypes.object, headComponents: PropTypes.array, bodyAttributes: PropTypes.object, preBodyComponents: PropTypes.array, body: PropTypes.string, postBodyComponents: PropTypes.array, }
test/index.android.js
ivanl001/ReactNative-Learning
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class test extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('test', () => test);
packages/material-ui-icons/src/ViewDay.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M2 21h19v-3H2v3zM20 8H3c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h17c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1zM2 3v3h19V3H2z" /></g> , 'ViewDay');
frontend/src/app/cmdb/group/edit.js
the-invoice/nab
import React, { Component } from 'react'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { pushPath } from 'redux-simple-router'; import { Route, IndexRoute } from 'react-router'; import { createSelector } from 'reselect'; import * as cmdbSelectors from 'app/cmdb/selectors'; import * as selectors from './selectors'; import * as actions from 'app/cmdb/actions'; import { View } from 'ui/layout'; import { GroupEditForm } from './edit-form'; function mapActionsToProps(dispatch) { return { actions: bindActionCreators(actions, dispatch), }; } const createModeSelector = (state, props) => props.route.createMode; const selector = createSelector( selectors.groupIdFromParams, selectors.currentGroup, cmdbSelectors.groupTypesList, createModeSelector, (group_id, group, groupTypesList, createMode) => { return { group_id, group, groupTypesList, createMode, } } ); @connect(selector, mapActionsToProps) export class GroupEdit extends Component { constructor(props) { super(props); this.state = {isSaving: false, msg: ''}; } componentDidMount() { const { groupTypesList, actions: { loadGroupTypes } } = this.props; if (!groupTypesList.length) { loadGroupTypes(); } } handleSubmitSave(formData) { const { group, actions: { saveItem, loadGroups } } = this.props; const item = { ...group, ...formData, }; this.setState({isSaving: true}); saveItem(item) .then(result => { this.setState({isSaving: false}); loadGroups([group.group_id,]); }) .catch((e) => { console.log(e); this.setState({isSaving: false}); }) } handleSubmitCreate(formData) { const { group, actions: { saveItem, loadGroupChildren } } = this.props; const parent_id = group && group.group_id; const item = { ...formData, type: 'group', parent_id, }; this.setState({isSaving: true}); saveItem(item) .then(result => { this.setState({isSaving: false}); loadGroupChildren(parent_id); }) .catch((e) => { console.log(e); this.setState({isSaving: false}); }) } render() { const { group, groupTypesList, groupTypes, createMode } = this.props; const { isSaving, msg } = this.state; return ( <div> <div> {isSaving ? 'Saving...' : (createMode ? 'Create new group' : 'Edit group')} </div> <GroupEditForm onSave={createMode ? this.handleSubmitCreate.bind(this) : this.handleSubmitSave.bind(this)} btnLabel={createMode ? 'Create' : 'Save'} initialValues={createMode ? {group_type_id: 1, name: ''} : group} groupTypesList={groupTypesList} /> </div> ); } }
src/interface/others/PlayerBreakdown.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import { Trans } from '@lingui/macro'; import SPECS from 'game/SPECS'; import SpecIcon from 'common/SpecIcon'; import { formatNumber } from 'common/format'; import { TooltipElement } from 'common/Tooltip'; import indexByProperty from 'common/indexByProperty'; import Toggle from 'react-toggle'; import SpellLink from 'common/SpellLink'; import PerformanceBar from 'interface/PerformanceBar'; class PlayerBreakdown extends React.Component { static propTypes = { report: PropTypes.object.isRequired, spellreport: PropTypes.object, players: PropTypes.array.isRequired, }; state = { showPlayers: true, }; calculatePlayerBreakdown(statsByTargetId, players) { const friendlyStats = []; const playersById = indexByProperty(players, 'id'); Object.keys(statsByTargetId) .forEach(targetId => { const playerStats = statsByTargetId[targetId]; const playerInfo = playersById[targetId]; if (playerInfo) { friendlyStats.push({ ...playerInfo, ...playerStats, masteryEffectiveness: playerStats.healingFromMastery / (playerStats.maxPotentialHealingFromMastery || 1), }); } }); return friendlyStats; } calculateSpellBreakdown(statsBySpellId) { const spellStats = []; Object.keys(statsBySpellId) .forEach(spellId => { const spell = statsBySpellId[spellId]; spellStats.push({ ...spell, masteryEffectiveness: spell.healingFromMastery / (spell.maxPotentialHealingFromMastery || 1), }); }); return spellStats; } render() { const { report, spellreport, players } = this.props; const friendlyStats = this.calculatePlayerBreakdown(report, players); const totalEffectiveHealing = Object.values(report).reduce((sum, player) => sum + player.effectiveHealing, 0); const highestEffectiveHealing = friendlyStats.reduce((highest, player) => Math.max(highest, player.effectiveHealing), 1); const highestMasteryEffectiveness = friendlyStats.reduce((highest, player) => Math.max(highest, player.masteryEffectiveness), 0); let spellStats = []; let totalSpellEffectiveHealing = 0; let highestSpellEffectiveHealing = 0; let highestSpellMasteryEffectiveness = 0; if (spellreport) { spellStats = this.calculateSpellBreakdown(spellreport); totalSpellEffectiveHealing = Object.values(spellreport).reduce((sum, spell) => sum + spell.effectiveHealing, 0); highestSpellEffectiveHealing = spellStats.reduce((highest, spell) => Math.max(highest, spell.effectiveHealing), 1); highestSpellMasteryEffectiveness = spellStats.reduce((highest, spell) => Math.max(highest, spell.masteryEffectiveness), 0); } return ( <> {spellreport && <div className="pad"> <div className="pull-right"> <div className="toggle-control pull-left" style={{ marginLeft: '.5em' }}> <label htmlFor="healing-toggle" style={{ marginLeft: '0.5em', marginRight: '1em' }}> Spells </label> <Toggle defaultChecked icons={false} onChange={event => this.setState({ showPlayers: event.target.checked })} id="healing-toggle" /> <label htmlFor="healing-toggle" style={{ marginLeft: '0.5em' }}> Players </label> </div> </div> </div> } <table className="data-table"> <thead> <tr style={{ textTransform: 'uppercase' }}> <th><Trans>Name</Trans></th> <th colSpan="2"><Trans>Mastery effectiveness</Trans></th> <th colSpan="3"><TooltipElement content={<Trans>This is the amount of healing done by spells affected by mastery. Things like Holy Paladin beacons or Restoration Shaman feeding are NOT included.</Trans>}><Trans>Healing done</Trans></TooltipElement></th> </tr> </thead> <tbody> {!this.state.showPlayers && spellStats && spellStats .sort((a, b) => b.masteryEffectiveness - a.masteryEffectiveness) .map((spell) => { // We want the performance bar to show a full bar for whatever healing done percentage is highest to make // it easier to see relative amounts. const performanceBarMasteryEffectiveness = spell.masteryEffectiveness / highestSpellMasteryEffectiveness; const performanceBarHealingDonePercentage = spell.effectiveHealing / highestSpellEffectiveHealing; const actualHealingDonePercentage = spell.effectiveHealing / totalSpellEffectiveHealing; return ( <tr key={spell.spellId}> <td style={{ width: '20%' }}> <SpellLink id={spell.spellId} /> </td> <td style={{ width: 50, textAlign: 'right' }}> {(Math.round(spell.masteryEffectiveness * 10000) / 100).toFixed(2)}% </td> <td style={{ width: '40%' }}> <PerformanceBar percent={performanceBarMasteryEffectiveness} /> </td> <td style={{ width: 50, textAlign: 'right' }}> {(Math.round(actualHealingDonePercentage * 10000) / 100).toFixed(2)}% </td> <td style={{ width: '40%' }}> <PerformanceBar percent={performanceBarHealingDonePercentage} /> </td> <td style={{ width: 50, textAlign: 'right' }}> {(formatNumber(spell.effectiveHealing))} </td> </tr> ); })} {this.state.showPlayers && friendlyStats && friendlyStats .sort((a, b) => b.masteryEffectiveness - a.masteryEffectiveness) .map((player) => { const combatant = player.combatant; if (!combatant) { console.error('Missing combatant:', player); return null; // pet or something } const spec = SPECS[combatant.specId]; const specClassName = spec.className.replace(' ', ''); // We want the performance bar to show a full bar for whatever healing done percentage is highest to make // it easier to see relative amounts. const performanceBarMasteryEffectiveness = player.masteryEffectiveness / highestMasteryEffectiveness; const performanceBarHealingReceivedPercentage = player.effectiveHealing / highestEffectiveHealing; const actualHealingReceivedPercentage = player.effectiveHealing / totalEffectiveHealing; return ( <tr key={combatant.id}> <td style={{ width: '20%' }}> <SpecIcon id={spec.id} />{' '} {combatant.name} </td> <td style={{ width: 50, textAlign: 'right' }}> {(Math.round(player.masteryEffectiveness * 10000) / 100).toFixed(2)}% </td> <td style={{ width: '40%' }}> <div className="flex performance-bar-container"> <div className={`flex-sub performance-bar ${specClassName}-bg`} style={{ width: `${performanceBarMasteryEffectiveness * 100}%` }} /> </div> </td> <td style={{ width: 50, textAlign: 'right' }}> {(Math.round(actualHealingReceivedPercentage * 10000) / 100).toFixed(2)}% </td> <td style={{ width: '40%' }}> <div className="flex performance-bar-container"> <div className={`flex-sub performance-bar ${specClassName}-bg`} style={{ width: `${performanceBarHealingReceivedPercentage * 100}%` }} /> </div> </td> <td style={{ width: 50, textAlign: 'right' }}> {(formatNumber(player.effectiveHealing))} </td> </tr> ); })} </tbody> </table> </> ); } } export default PlayerBreakdown;
src/admin/app/index.js
jgretz/node-bits-admin
import './styles/styles.scss'; import 'react-select/dist/react-select.css'; import 'react-virtualized/styles.css'; import './babelHelpers'; import 'core-js/es6/symbol'; import 'core-js/es6/promise'; import 'core-js/es6/array'; import 'core-js/es6/number'; import 'core-js/es6/object'; import React from 'react'; import {Provider} from 'react-redux'; import {browserHistory, Router} from 'react-router'; import {render} from 'react-dom'; import {syncHistoryWithStore} from 'react-router-redux'; import {configureHttp, configureToastr} from './util'; import configureStore from './store/configureStore'; import routes from './routes'; // configure stuff const store = configureStore(); configureHttp(store); configureToastr(); const history = syncHistoryWithStore(browserHistory, store); // render render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('app') );
stories/types/result-field-token-type.js
smclab/react-faceted-token-input
import React from 'react'; const FIELDS = { "product": "Product", "description": "Description" }; export const RESULTS = [ { "product": "NPMP50000", "description": "", "status": "1-Compilazione-Richiesta", "createDate": "21/02/2015" }, { "product": "NPMP50078", "description": "MODIFICA KIT RICAMBIO", "status": "4-Decisione-Richiedente", "createDate": "21/11/2014" }, { "product": "NPMP50045", "description": "MODIFICA FRONTALE DOT-MATRIX 5M LOW", "status": "4-Decisione-Richiedente", "createDate": "02/10/2014" }, { "product": "NPMP50046", "description": "GR SCHEDA HAGC03-8X03 GPL - NUOVO PRODOTTO", "status": "6-Verifica-Finale", "createDate": "02/10/2014" }, { "product": "NPMP50053", "description": "C63-0110 - MODIFICA HW", "status": "7-Chiusa", "createDate": "02/08/2014" } ]; export default class ResultFieldTokenType { constructor(field) { this.field = field; this.type = 'field-' + field; this.values = RESULTS.map(o => o[field]).filter(Boolean); } renderToken(token) { return { facet: FIELDS[token.field], description: token.fuzzy ? token.value + '…' : token.value }; } getTitle() { return FIELDS[this.field]; } getTokenSuggestions(searchText) { const search = String(searchText).trim().toLowerCase(); if (!search) { return []; } return [ { id: this.type + '-fuzzy-' + search, description: FIELDS[this.field] + ' contains: ' + search, result: { type: this.type, field: this.field, fuzzy: true, value: search } }, ...this.values .filter(value => value.toLowerCase().indexOf(search) === 0) .map((value, index) => ({ id: this.type + '-' + index, description: <em>{ value }</em>, result: { type: this.type, field: this.field, value: value } })) ]; } }
client/components/Main.js
gregmagdsick/learn-redux
import React from 'react'; import { Link } from 'react-router'; const Main = React.createClass({ render() { return ( <div> <h1> <Link to="/">Reduxtagram</Link> </h1> {React.cloneElement(this.props.children, this.props)} </div> ) } }); export default Main;
src/pages/yumarimel.js
vitorbarbosa19/ziro-online
import React from 'react' import BrandGallery from '../components/BrandGallery' export default () => ( <BrandGallery brand='Yumarimel' /> )
src/Parser/Shaman/Restoration/Modules/Items/EonarsCompassion.js
hasseboulen/WoWAnalyzer
import SPELLS from 'common/SPELLS'; import ITEMS from 'common/ITEMS'; import React from 'react'; import ItemHealingDone from 'Main/ItemHealingDone'; import CoreEonarsCompassion from 'Parser/Core/Modules/Items/Legion/AntorusTheBurningThrone/EonarsCompassion'; import CooldownThroughputTracker from '../Features/CooldownThroughputTracker'; const PANTHEON_MAX_SHIELD_PER_PROC = 4; class EonarsCompassion extends CoreEonarsCompassion { static dependencies = { ...CoreEonarsCompassion.dependencies, cooldownThroughputTracker: CooldownThroughputTracker, }; item() { const feeding = this.cooldownThroughputTracker.getIndirectHealing(SPELLS.EONARS_COMPASSION_HEAL.id); const minutes = this.owner.fightDuration / 1000 / 60; const basicPpm = this.trinketProc / minutes; const pantheonPpm = this.pantheonProc / minutes; const possibleShields = this.pantheonProc * PANTHEON_MAX_SHIELD_PER_PROC; return { item: ITEMS.EONARS_COMPASSION, result: ( <dfn data-tip={` Basic Procs <ul> <li>${this.owner.formatItemHealingDone(this.trinketHealing)}</li> <li>${this.trinketProc} procs (${basicPpm.toFixed(1)} PPM)</li> </ul> Pantheon Procs <ul> <li>${this.owner.formatItemHealingDone(this.pantheonShieldHealing)}</li> <li>${this.pantheonProc} procs (${pantheonPpm.toFixed(1)} PPM)</li> ${this.pantheonProc ? `<li>Applied ${this.pantheonShieldCast} shields (out of ${possibleShields} possible)</li>` : ``} </ul> Feeding <ul> <li>${this.owner.formatItemHealingDone(feeding)}</li> </ul> `} > <ItemHealingDone amount={this.totalHealing + feeding} /> </dfn> ), }; } } export default EonarsCompassion;
src/apps/tabs/components/InfiniteScroll.react.js
producthunt/producthunt-chrome-extension
/** * Dependencies. */ import React from 'react'; import ReactDOM from 'react-dom'; /** * Utils. */ function topPosition(domElt) { if (!domElt) { return 0; } return domElt.offsetTop + topPosition(domElt.offsetParent); } /** * InfiniteScroll component. */ export default class InfiniteScroll extends React.Component { constructor(props) { super(props); this.scrollListener = this.scrollListener.bind(this); } componentDidMount() { this.pageLoaded = this.props.pageStart; this.attachScrollListener(); } componentDidUpdate() { this.attachScrollListener(); } componentWillUnmount() { this.detachScrollListener(); } render() { return ( <div> {this.props.children} {this.props.hasMore && this.props.loader} </div> ); } scrollListener() { var el = ReactDOM.findDOMNode(this); var scrollTop = window.pageYOffset !== undefined ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop; if (topPosition(el) + el.offsetHeight - scrollTop - window.innerHeight < Number(this.props.threshold)) { this.detachScrollListener(); this.props.loadMore(this.pageLoaded += 1); } } attachScrollListener() { if (!this.props.hasMore) { return; } window.addEventListener('scroll', this.scrollListener); window.addEventListener('resize', this.scrollListener); this.scrollListener(); } detachScrollListener() { window.removeEventListener('scroll', this.scrollListener); window.removeEventListener('resize', this.scrollListener); } } InfiniteScroll.defaultProps = { pageStart: 0 , hasMore: false, loadMore: function() {}, threshold: 250, loader: <div></div>, };
src/scenes/works/works-navigation.js
mattmischuk/m1x
// @flow import React from 'react' import styled from 'styled-components' import theme from 'styled-theming' import { Navigation, NavigationItem } from '../../components/navigation' import route from '../../data/routes' import { myTheme } from '../../styles' const { color, space } = myTheme const borderColor = theme('mode', { dark: color.lightBlueGray, light: color.offWhite, }) const NavContainer = styled.div` margin-top: ${space.three}; border-top: 1px solid ${borderColor}; display: ${props => props.disabled && 'none'}; ` type Props = { disabled: boolean, } const WorksNavigation = ({ disabled }: Props) => ( <NavContainer disabled={disabled}> <Navigation> <NavigationItem to={route.mavenPro}>Maven Pro</NavigationItem> </Navigation> </NavContainer> ) export default WorksNavigation
examples/huge-apps/routes/Calendar/components/Calendar.js
brandonlilly/react-router
import React from 'react'; class Calendar extends React.Component { render () { var events = [{ id: 0, title: 'essay due' }]; return ( <div> <h2>Calendar</h2> <ul> {events.map(event => ( <li key={event.id}>{event.title}</li> ))} </ul> </div> ); } } export default Calendar;
src/Survey/Complex/Moth/Edit/Main/components/SpeciesList/components/SubSample/index.js
NERC-CEH/irecord-app
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import { observer } from 'mobx-react'; import { IonItemOption, IonItemOptions, IonItem, IonIcon, IonItemSliding, IonButton, } from '@ionic/react'; import { alert } from 'ionicons/icons'; import './styles.scss'; @observer class index extends Component { static propTypes = { occ: PropTypes.object.isRequired, increaseCount: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired, url: PropTypes.string.isRequired, }; getIncrementButton = occ => { const { increaseCount } = this.props; const onNumberIncrementClick = e => { e.preventDefault(); e.stopPropagation(); increaseCount(occ); }; return ( <IonButton class="count-edit-count" onClick={onNumberIncrementClick} fill="clear" > {occ.attrs.number} </IonButton> ); }; render() { const { occ, onDelete, url } = this.props; const survey = occ.getSurvey(); const invalids = survey.verify(occ.attrs); const isValid = _.isEmpty(invalids); const specie = occ.attrs.taxon || {}; const scientificName = specie.scientific_name; let commonName = specie.found_in_name >= 0 && specie.common_names[specie.found_in_name]; if (specie.found_in_name === 'common_name') { // This is just to be backwards compatible // TODO: remove in the next update commonName = specie.common_name; } return ( <IonItemSliding key={occ.cid}> <IonItem routerLink={`${url}/occ/${occ.cid}`} detail={false}> {this.getIncrementButton(occ)} <div className="details"> {commonName && ( <> <div className="species">{commonName}</div> <div className="species scientific">{scientificName}</div> </> )} {!commonName && ( <div className="species"> <i> <b>{scientificName}</b> </i> </div> )} </div> {!isValid && <IonIcon icon={alert} color="danger" slot="end" />} </IonItem> <IonItemOptions side="end"> <IonItemOption color="danger" onClick={onDelete}> {t('Delete')} </IonItemOption> </IonItemOptions> </IonItemSliding> ); } } export default index;
packages/cf-component-card/test/CardToolbarLink.js
koddsson/cf-ui
import React from 'react'; import renderer from 'react-test-renderer'; import CardToolbarLink from '../src/CardToolbarLink'; test('should render', () => { const component = renderer.create( <CardToolbarLink id="link" isActive={false} onClick={() => {}}> CardToolbarLink </CardToolbarLink> ); expect(component.toJSON()).toMatchSnapshot(); }); test('should render with isActive', () => { const component = renderer.create( <CardToolbarLink id="link" isActive={true} onClick={() => {}}> CardToolbarLink </CardToolbarLink> ); expect(component.toJSON()).toMatchSnapshot(); });
fields/types/cloudinaryimages/CloudinaryImagesColumn.js
alobodig/keystone
import React from 'react'; import CloudinaryImageSummary from '../../components/columns/CloudinaryImageSummary'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; const moreIndicatorStyle = { color: '#888', fontSize: '.8rem', }; var CloudinaryImagesColumn = React.createClass({ displayName: 'CloudinaryImagesColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderMany (value) { if (!value || !value.length) return; const items = []; for (let i = 0; i < 3; i++) { if (!value[i]) break; items.push(<CloudinaryImageSummary key={'image' + i} image={value[i]} />); } if (value.length > 3) { items.push(<span key="more" style={moreIndicatorStyle}>[...{value.length - 3} more]</span>); } return items; }, renderValue (value) { if (!value || !Object.keys(value).length) return; return <CloudinaryImageSummary image={value} />; }, render () { const value = this.props.data.fields[this.props.col.path]; const many = value.length > 1; return ( <ItemsTableCell> <ItemsTableValue field={this.props.col.type}> {many ? this.renderMany(value) : this.renderValue(value[0])} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = CloudinaryImagesColumn;
app/components/Labels/__tests__/LabelEdit-test.js
TailorDev/franklin
import React from 'react'; import { shallow, mount } from 'enzyme'; import { expect } from 'chai'; import sinon from 'sinon'; import Immutable from 'immutable'; // see: https://github.com/mochajs/mocha/issues/1847 const { describe, it } = global; import LabelEdit from '../LabelEdit'; import LabelForm from '../LabelForm'; describe('<LabelEdit />', () => { const dummyLabel = { name: 'foo', color: '#000', isActive: true, annotations: Immutable.List(), }; it('renders a label form', () => { const wrapper = shallow( <LabelEdit onActionEditCancelClick={() => {}} onLabelEdit={() => {}} label={dummyLabel} /> ); expect(wrapper.find(LabelForm)).to.have.length(1); }); it('fires label edition canceling', () => { const spy = sinon.spy(); const wrapper = mount( <LabelEdit onActionEditCancelClick={spy} onLabelEdit={() => {}} label={dummyLabel} /> ); wrapper.find('input[type="reset"]').simulate('click'); expect(spy.calledOnce).to.be.true; }); it('submits edited label', () => { const spy = sinon.spy(); const wrapper = mount( <LabelEdit onActionEditCancelClick={() => {}} onLabelEdit={spy} label={dummyLabel} /> ); wrapper.find('input[type="text"]').simulate('change', { persist: () => {}, target: { value: 'bar', }, }); wrapper.find('.button.submit').simulate('click'); expect(spy.calledOnce).to.be.true; expect( spy.calledWith({ name: 'bar', color: '#000', isActive: true, annotations: Immutable.List(), }) ).to.be.true; }); });
admin/app/src/index.js
wjwu/blog
import React from 'react'; import ReactDOM from 'react-dom'; import { createStore, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import { HashRouter, Switch, Route, Redirect } from 'react-router-dom'; import createSagaMiddleware from 'redux-saga'; import reducers from './reducers'; import sagas from './sagas'; import Login from './modules/login'; import MainContainer from './containers/main'; import NotFound from './modules/404'; const sagaMiddleware = createSagaMiddleware(); const store = createStore(reducers, applyMiddleware(sagaMiddleware)); sagaMiddleware.run(sagas); ReactDOM.render( <Provider store={ store }> <HashRouter> <div style={ { height: '100%', backgroundColor: '#ececec' } }> <Switch> <Route path='/login' component={ Login } /> <Route path='/main' component={ MainContainer }/> <Redirect from='/' to='/main' /> <Route component={ NotFound } /> </Switch> </div> </HashRouter> </Provider>, document.getElementById('app') );
components/chronicle/Chronicle.js
yudazilian/VisualJusticeTW
import React from 'react'; import ReactDom from 'react-dom'; import ChronicleHeader from './ChronicleHeader'; import ChronicleFooter from './ChronicleFooter'; import ChronicleBody from './ChronicleBody'; export default class Chronicle extends React.Component { render() { return ( <div id="Chronicle" className="row"> <ChronicleHeader/> <ChronicleBody /> <ChronicleFooter/> </div> ) } }
scripts/main.js
maratgaip/MusicApp
import 'babel-polyfill'; import 'fastclick'; import 'isomorphic-fetch'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import '../styles/main.scss'; import App from './containers/App'; import configureStore from './store/configureStore'; const store = configureStore(); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('main') );
admin/client/components/Lightbox.js
suryagh/keystone
import React from 'react'; import blacklist from 'blacklist'; import Portal from './Portal'; import Transition from 'react-addons-css-transition-group'; const BODY = document.getElementsByTagName('body')[0]; var Lightbox = React.createClass({ displayName: 'Lightbox', propTypes: { backdropClosesModal: React.PropTypes.bool, className: React.PropTypes.string, enableKeyboardInput: React.PropTypes.bool, height: React.PropTypes.number, images: React.PropTypes.array, initialImage: React.PropTypes.number, isOpen: React.PropTypes.bool, onCancel: React.PropTypes.func, showCloseButton: React.PropTypes.bool, width: React.PropTypes.number, }, getDefaultProps () { return { backdropClosesModal: true, enableKeyboardInput: true, initialImage: 0, height: 600, width: 900, }; }, getInitialState () { return { currentImage: this.props.initialImage, }; }, componentWillReceiveProps (nextProps) { this.setState({ currentImage: nextProps.initialImage, }); if (nextProps.isOpen && nextProps.enableKeyboardInput) { window.addEventListener('keydown', this.handleKeyboardInput); } else { window.removeEventListener('keydown', this.handleKeyboardInput); } if (nextProps.isOpen) { BODY.style.overflow = 'hidden'; } else { BODY.style.overflow = null; } }, handleKeyboardInput (event) { if (event.keyCode === 37) { this.gotoPrevious(); } else if (event.keyCode === 39) { this.gotoNext(); } else if (event.keyCode === 27) { this.props.onCancel(); } else { return false; } }, gotoPrevious () { if (this.state.currentImage === 0) return; this.setState({ currentImage: this.state.currentImage - 1, }); }, gotoNext () { if (this.state.currentImage === (this.props.images.length - 1)) return; this.setState({ currentImage: this.state.currentImage + 1, }); }, renderArrowPrev () { return ( <Transition transitionName="react-transitiongroup-fade" transitionEnterTimeout={200} transitionLeaveTimeout={200}> {(this.state.currentImage > 0) && <button type="button" style={Object.assign({}, styles.arrow, styles.arrowPrev)} onClick={this.gotoPrevious} className="octicon octicon-chevron-left" />} </Transition> ); }, renderArrowNext () { return ( <Transition transitionName="react-transitiongroup-fade" transitionEnterTimeout={200} transitionLeaveTimeout={200}> {(this.state.currentImage < (this.props.images.length - 1)) && <button type="button" style={Object.assign({}, styles.arrow, styles.arrowNext)} onClick={this.gotoNext} className="octicon octicon-chevron-right" />} </Transition> ); }, renderBackdrop () { if (!this.props.isOpen) return; return <div key="backdrop" style={styles.backdrop} onClick={this.props.backdropClosesModal ? this.props.onCancel : null} />; }, renderCloseButton () { if (!this.props.showCloseButton) return; return <button key="close" style={styles.close} onClick={this.props.onCancel}>Close</button>; }, renderDialog () { if (!this.props.isOpen) return; return ( <div key="dialog" style={Object.assign({}, styles.dialog, { height: this.props.height, width: this.props.width })}> {this.renderImages()} {this.renderArrowPrev()} {this.renderArrowNext()} {this.renderCloseButton()} </div> ); }, renderImages () { const { images } = this.props; const { currentImage } = this.state; if (!images || !images.length) return; return ( <Transition transitionName="react-transitiongroup-fade" style={styles.imageContainer} component="div" transitionEnterTimeout={200} transitionLeaveTimeout={200}> <img key={'image' + currentImage} src={images[currentImage]} style={styles.image} /> </Transition> ); }, render () { const props = blacklist(this.props, 'backdropClosesModal', 'initialImage', 'height', 'images', 'isOpen', 'onCancel', 'showCloseButton', 'width'); return ( <Portal {...props}> <Transition transitionName="react-transitiongroup-fade" component="div" transitionEnterTimeout={200} transitionLeaveTimeout={200}> {this.renderDialog()} </Transition> <Transition transitionName="react-transitiongroup-fade" component="div" transitionEnterTimeout={200} transitionLeaveTimeout={200}> {this.renderBackdrop()} </Transition> </Portal> ); }, }); const styles = { arrow: { background: 'none', border: 'none', bottom: 0, color: 'white', fontSize: 48, right: 0, outline: 'none', padding: 0, position: 'absolute', top: 0, width: '10%', zIndex: 1002, // disable user select WebkitTouchCallout: 'none', WebkitUserSelect: 'none', MozUserSelect: 'none', msUserSelect: 'none', userSelect: 'none', }, arrowNext: { right: 0, }, arrowPrev: { left: 0, }, backdrop: { backgroundColor: 'rgba(0,0,0,0.66)', bottom: 0, left: 0, position: 'fixed', right: 0, top: 0, zIndex: 1000, }, close: { background: 'none', border: 'none', bottom: -32, color: 'white', fontSize: 16, height: 32, left: 0, marginLeft: 'auto', marginRight: 'auto', outline: 'none', padding: 0, position: 'absolute', right: 0, textAlign: 'center', textTransform: 'uppercase', width: 100, }, dialog: { // backgroundColor: 'rgba(255,255,255,0.26)', left: 0, lineHeight: 1, marginLeft: 'auto', marginRight: 'auto', maxHeight: '100%', maxWidth: '100%', position: 'fixed', right: 0, top: '50%', zIndex: 1001, WebkitTransform: 'translateY(-50%)', MozTransform: 'translateY(-50%)', msTransform: 'translateY(-50%)', transform: 'translateY(-50%)', }, image: { boxShadow: '0 1px 4px rgba(0,0,0,0.25)', maxHeight: '100%', maxWidth: '80%', position: 'absolute', // center the image within the dialog left: '50%', top: '50%', WebkitTransform: 'translate(-50%, -50%)', MozTransform: 'translate(-50%, -50%)', msTransform: 'translate(-50%, -50%)', transform: 'translate(-50%, -50%)', // disable user select WebkitTouchCallout: 'none', WebkitUserSelect: 'none', MozUserSelect: 'none', msUserSelect: 'none', userSelect: 'none', }, }; module.exports = Lightbox;
actor-apps/app-web/src/app/components/sidebar/ContactsSectionItem.react.js
fhchina/actor-platform
import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; import DialogActionCreators from 'actions/DialogActionCreators'; import AvatarItem from 'components/common/AvatarItem.react'; const {addons: { PureRenderMixin }} = addons; @ReactMixin.decorate(PureRenderMixin) class ContactsSectionItem extends React.Component { static propTypes = { contact: React.PropTypes.object }; constructor(props) { super(props); } openNewPrivateCoversation = () => { DialogActionCreators.selectDialogPeerUser(this.props.contact.uid); } render() { const contact = this.props.contact; return ( <li className="sidebar__list__item row" onClick={this.openNewPrivateCoversation}> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> </li> ); } } export default ContactsSectionItem;
packages/component/src/ScreenReaderText.js
billba/botchat
/* eslint react/forbid-dom-props: ["off"] */ import PropTypes from 'prop-types'; import React from 'react'; import useStyleToEmotionObject from './hooks/internal/useStyleToEmotionObject'; const ROOT_STYLE = { // .sr-only - This component is intended to be invisible to the visual Web Chat user, but read by the AT when using a screen reader color: 'transparent', height: 1, overflow: 'hidden', position: 'absolute', // We need to set top: 0, otherwise, it will repro: // - Run NVDA // - Make the transcript long enough to show the scrollbar // - Press SHIFT-TAB, focus on upload button // - Press up arrow multiple times top: 0, whiteSpace: 'nowrap', width: 1 }; const ScreenReaderText = ({ id, text }) => { const rootClassName = useStyleToEmotionObject()(ROOT_STYLE) + ''; return ( <div className={rootClassName} id={id}> {text} </div> ); }; ScreenReaderText.defaultProps = { id: undefined }; ScreenReaderText.propTypes = { id: PropTypes.string, text: PropTypes.string.isRequired }; export default ScreenReaderText;
src/pages/dashboard/components/user.js
zuiidea/antd-admin
import React from 'react' import PropTypes from 'prop-types' import { Button, Avatar } from 'antd' import CountUp from 'react-countup' import { Color } from 'utils' import styles from './user.less' const countUpProps = { start: 0, duration: 2.75, useEasing: true, useGrouping: true, separator: ',', } function User({ avatar, username, sales = 0, sold = 0 }) { return ( <div className={styles.user}> <div className={styles.header}> <div className={styles.headerinner}> <Avatar size="large" src={avatar} /> <h5 className={styles.name}>{username}</h5> </div> </div> <div className={styles.number}> <div className={styles.item}> <p>EARNING SALES</p> <p style={{ color: Color.green }}> <CountUp end={sales} prefix="$" {...countUpProps} /> </p> </div> <div className={styles.item}> <p>ITEM SOLD</p> <p style={{ color: Color.blue }}> <CountUp end={sold} {...countUpProps} /> </p> </div> </div> <div className={styles.footer}> <Button type="ghost" size="large"> View Profile </Button> </div> </div> ) } User.propTypes = { avatar: PropTypes.string, username: PropTypes.string, sales: PropTypes.number, sold: PropTypes.number, } export default User
react/features/base/dialog/components/native/ConfirmDialog.js
gpolitis/jitsi-meet
// @flow import React from 'react'; import { View } from 'react-native'; import Dialog from 'react-native-dialog'; import { translate } from '../../../i18n'; import { connect } from '../../../redux'; import AbstractDialog from '../AbstractDialog'; import { renderHTML } from '../functions.native'; import styles from './styles'; /** * The type of the React {@code Component} props of * {@link ConfirmDialog}. */ type Props = { /** * The i18n key of the text label for the cancel button. */ cancelLabel: string, /** * The React {@code Component} children. */ children?: React$Node, /** * The i18n key of the text label for the confirm button. */ confirmLabel: string, /** * Dialog description key for translations. */ descriptionKey?: string | Object, /** * Whether or not the nature of the confirm button is destructive. */ isConfirmDestructive?: Boolean, /** * Invoked to obtain translated strings. */ t: Function, /** * Dialog title. */ title?: string, }; /** * React Component for getting confirmation to stop a file recording session in * progress. * * @augments Component */ class ConfirmDialog extends AbstractDialog<Props> { /** * Default values for {@code ConfirmDialog} component's properties. * * @static */ static defaultProps = { isConfirmDestructive: false }; /** * Renders the dialog description. * * @returns {React$Component} */ _renderDescription() { const { descriptionKey, t } = this.props; const description = typeof descriptionKey === 'string' ? t(descriptionKey) : renderHTML( t(descriptionKey?.key, descriptionKey?.params) ); return ( <Dialog.Description> { description } </Dialog.Description> ); } /** * Implements {@code Component#render}. * * @inheritdoc */ render() { const { cancelLabel, children, confirmLabel, isConfirmDestructive, t, title } = this.props; const dialogButtonStyle = isConfirmDestructive ? styles.destructiveDialogButton : styles.dialogButton; return ( <View> <Dialog.Container visible = { true }> { title && <Dialog.Title> { t(title) } </Dialog.Title> } { this._renderDescription() } { children } <Dialog.Button label = { t(cancelLabel || 'dialog.confirmNo') } onPress = { this._onCancel } style = { styles.dialogButton } /> <Dialog.Button label = { t(confirmLabel || 'dialog.confirmYes') } onPress = { this._onSubmit } style = { dialogButtonStyle } /> </Dialog.Container> </View> ); } _onCancel: () => void; _onSubmit: (?string) => void; } export default translate(connect()(ConfirmDialog));
src/neuralNetwork/infoButtons/InfoButtons.js
csenn/nn-visualizer
import React from 'react'; import RaisedButton from 'material-ui/lib/raised-button'; import * as graphConstants from '../networkGraph/graphConstants'; import InputLayerInfo from './InputLayerInfo'; import HiddenLayerInfo from './HiddenLayerInfo'; import BiasHistoryInfo from './BiasHistoryInfo'; import ActivationHistoryInfo from './ActivationHistoryInfo'; import OutputLayerInfo from './OutputLayerInfo'; export default class InfoButtons extends React.Component { constructor(props) { super(props); this._isLong = this._isLong.bind(this); this._renderHiddenLayerButtons = this._renderHiddenLayerButtons.bind(this); } _isLong() { const biases = this.props.selectedNetwork.snapshots[0].biases; return biases.length === 3; } _renderHiddenLayerButtons() { const buttons = []; if (!this._isLong()) { buttons.push( <BiasHistoryInfo layer={0} selectedNetwork={this.props.selectedNetwork} style={{ top: '25px', left: `${graphConstants.WIDTH / 2 - 90}px` }} />, <ActivationHistoryInfo layer={1} selectedNetwork={this.props.selectedNetwork} selectedDrawing={this.props.selectedDrawing} selectedNetworkSummary={this.props.selectedNetworkSummary} style={{ top: '67px', left: `${graphConstants.WIDTH / 2 - 90}px` }} /> ); } else { buttons.push( <BiasHistoryInfo layer={0} selectedNetwork={this.props.selectedNetwork} style={{ top: '25px', left: `${graphConstants.WIDTH / 3 - 60}px` }} />, <BiasHistoryInfo layer={1} selectedNetwork={this.props.selectedNetwork} style={{ top: '25px', left: `${2 * graphConstants.WIDTH / 3 - 90}px` }} />, <ActivationHistoryInfo layer={1} selectedNetwork={this.props.selectedNetwork} selectedDrawing={this.props.selectedDrawing} selectedNetworkSummary={this.props.selectedNetworkSummary} style={{ top: '67px', left: `${graphConstants.WIDTH / 3 - 60}px` }} />, <ActivationHistoryInfo layer={2} selectedNetwork={this.props.selectedNetwork} selectedDrawing={this.props.selectedDrawing} selectedNetworkSummary={this.props.selectedNetworkSummary} style={{ top: '67px', left: `${2 * graphConstants.WIDTH / 3 - 90}px` }} /> ); } return buttons; } render() { const style = { position: 'relative', display: 'inline-block', width: `${graphConstants.WIDTH}px`, textAlign: 'left', marginTop: '10px' }; // <HiddenLayerInfo // style={{ top: '25px', left:`${graphConstants.WIDTH / 2 - 90}px` }} // /> return ( <div style={style}> <span style={{ fontSize: '13px', fontStyle: 'italic' }}> Click buttons for more info and charts </span> <InputLayerInfo style={{ top: '25px', left: 0 }}/> {this._renderHiddenLayerButtons()} <OutputLayerInfo style={{ top: '25px', right: '25px' }}/> <BiasHistoryInfo layer={this._isLong() ? 2 : 1} selectedNetwork={this.props.selectedNetwork} style={{ top: '67px', right: '25px' }} /> <ActivationHistoryInfo layer={this._isLong() ? 3 : 2} selectedNetwork={this.props.selectedNetwork} selectedDrawing={this.props.selectedDrawing} selectedNetworkSummary={this.props.selectedNetworkSummary} style={{ top: '110px', right: '25px' }} /> </div> ); } }
src/svg-icons/action/view-carousel.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionViewCarousel = (props) => ( <SvgIcon {...props}> <path d="M7 19h10V4H7v15zm-5-2h4V6H2v11zM18 6v11h4V6h-4z"/> </SvgIcon> ); ActionViewCarousel = pure(ActionViewCarousel); ActionViewCarousel.displayName = 'ActionViewCarousel'; ActionViewCarousel.muiName = 'SvgIcon'; export default ActionViewCarousel;
src/Foo.js
ferrannp/enzyme-example-jest
import React from 'react'; const Foo = React.createClass({ render() { return ( <p>I am not a very smart component...</p> ); } }); export default Foo;
test/OverlayTriggerSpec.js
brentertz/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import OverlayTrigger from '../src/OverlayTrigger'; import Popover from '../src/Popover'; import Tooltip from '../src/Tooltip'; describe('OverlayTrigger', function() { it('Should create OverlayTrigger element', function() { const instance = ReactTestUtils.renderIntoDocument( <OverlayTrigger overlay={<div>test</div>}> <button>button</button> </OverlayTrigger> ); const overlayTrigger = React.findDOMNode(instance); assert.equal(overlayTrigger.nodeName, 'BUTTON'); }); it('Should pass OverlayTrigger onClick prop to child', function() { const callback = sinon.spy(); const instance = ReactTestUtils.renderIntoDocument( <OverlayTrigger overlay={<div>test</div>} onClick={callback}> <button>button</button> </OverlayTrigger> ); const overlayTrigger = React.findDOMNode(instance); ReactTestUtils.Simulate.click(overlayTrigger); callback.called.should.be.true; }); it('Should show after click trigger', function() { const instance = ReactTestUtils.renderIntoDocument( <OverlayTrigger trigger='click' overlay={<div>test</div>}> <button>button</button> </OverlayTrigger> ); const overlayTrigger = React.findDOMNode(instance); ReactTestUtils.Simulate.click(overlayTrigger); instance.state.isOverlayShown.should.be.true; }); it('Should maintain overlay classname', function() { const instance = ReactTestUtils.renderIntoDocument( <OverlayTrigger trigger='click' overlay={<div className='test-overlay'>test</div>}> <button>button</button> </OverlayTrigger> ); const overlayTrigger = React.findDOMNode(instance); ReactTestUtils.Simulate.click(overlayTrigger); expect(document.getElementsByClassName('test-overlay').length).to.equal(1); }); it('Should pass transition callbacks to Transition', function (done) { let count = 0; let increment = ()=> count++; let overlayTrigger; let instance = ReactTestUtils.renderIntoDocument( <OverlayTrigger trigger='click' overlay={<div>test</div>} onHide={()=>{}} onExit={increment} onExiting={increment} onExited={()=> { increment(); expect(count).to.equal(6); done(); }} onEnter={increment} onEntering={increment} onEntered={()=> { increment(); ReactTestUtils.Simulate.click(overlayTrigger); }} > <button>button</button> </OverlayTrigger> ); overlayTrigger = React.findDOMNode(instance); ReactTestUtils.Simulate.click(overlayTrigger); }); it('Should forward requested context', function() { const contextTypes = { key: React.PropTypes.string }; const contextSpy = sinon.spy(); class ContextReader extends React.Component { render() { contextSpy(this.context.key); return <div />; } } ContextReader.contextTypes = contextTypes; const TriggerWithContext = OverlayTrigger.withContext(contextTypes); class ContextHolder extends React.Component { getChildContext() { return {key: 'value'}; } render() { return ( <TriggerWithContext trigger="click" overlay={<ContextReader />} > <button>button</button> </TriggerWithContext> ); } } ContextHolder.childContextTypes = contextTypes; const instance = ReactTestUtils.renderIntoDocument(<ContextHolder />); const overlayTrigger = React.findDOMNode(instance); ReactTestUtils.Simulate.click(overlayTrigger); contextSpy.calledWith('value').should.be.true; }); describe('overlay types', function() { [ { name: 'Popover', overlay: (<Popover>test</Popover>) }, { name: 'Tooltip', overlay: (<Tooltip>test</Tooltip>) } ].forEach(function(testCase) { describe(testCase.name, function() { let instance, overlayTrigger; beforeEach(function() { instance = ReactTestUtils.renderIntoDocument( <OverlayTrigger trigger="click" overlay={testCase.overlay}> <button>button</button> </OverlayTrigger> ); overlayTrigger = React.findDOMNode(instance); }); it('Should handle trigger without warnings', function() { ReactTestUtils.Simulate.click(overlayTrigger); }); }); }); }); describe('rootClose', function() { [ { label: 'true', rootClose: true, shownAfterClick: false }, { label: 'default (false)', rootClose: null, shownAfterClick: true } ].forEach(function(testCase) { describe(testCase.label, function() { let instance; beforeEach(function () { instance = ReactTestUtils.renderIntoDocument( <OverlayTrigger overlay={<div>test</div>} trigger='click' rootClose={testCase.rootClose} > <button>button</button> </OverlayTrigger> ); const overlayTrigger = React.findDOMNode(instance); ReactTestUtils.Simulate.click(overlayTrigger); }); it('Should have correct isOverlayShown state', function () { document.documentElement.click(); // Need to click this way for it to propagate to document element. instance.state.isOverlayShown.should.equal(testCase.shownAfterClick); }); }); }); describe('replaced overlay', function () { let instance; beforeEach(function () { class ReplacedOverlay extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.state = {replaced: false}; } handleClick() { this.setState({replaced: true}); } render() { if (this.state.replaced) { return ( <div>replaced</div> ); } else { return ( <div> <a id="replace-overlay" onClick={this.handleClick}> original </a> </div> ); } } } instance = ReactTestUtils.renderIntoDocument( <OverlayTrigger overlay={<ReplacedOverlay />} trigger='click' rootClose={true} > <button>button</button> </OverlayTrigger> ); const overlayTrigger = React.findDOMNode(instance); ReactTestUtils.Simulate.click(overlayTrigger); }); it('Should still be shown', function () { // Need to click this way for it to propagate to document element. const replaceOverlay = document.getElementById('replace-overlay'); replaceOverlay.click(); instance.state.isOverlayShown.should.be.true; }); }); }); });
docs/src/app/components/pages/components/DropDownMenu/ExampleOpenImmediate.js
barakmitz/material-ui
import React from 'react'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; export default class DropDownMenuOpenImmediateExample extends React.Component { constructor(props) { super(props); this.state = {value: 2}; } handleChange = (event, index, value) => this.setState({value}); render() { return ( <DropDownMenu value={this.state.value} onChange={this.handleChange} openImmediately={true}> <MenuItem value={1} primaryText="Never" /> <MenuItem value={2} primaryText="Every Night" /> <MenuItem value={3} primaryText="Weeknights" /> <MenuItem value={4} primaryText="Weekends" /> <MenuItem value={5} primaryText="Weekly" /> </DropDownMenu> ); } }
demo/src/index.js
Psykar/react-filtered-multiselect
import 'bootstrap/dist/css/bootstrap.min.css' import 'bootstrap/dist/css/bootstrap-theme.min.css' import React from 'react' import {render} from 'react-dom' import FilteredMultiSelect from '../../src/index' import CULTURE_SHIPS from './ships.json' const BOOTSTRAP_CLASSES = { filter: 'form-control', select: 'form-control', button: 'btn btn btn-block btn-default', buttonActive: 'btn btn btn-block btn-primary' } var BasicSelection = React.createClass({ getInitialState() { return { selectedOptions: [] } }, handleClearSelection() { this.setState({selectedOptions: []}) }, handleDeselect(index) { var selectedOptions = this.state.selectedOptions.slice() selectedOptions.splice(index, 1) this.setState({selectedOptions}) }, handleSelectionChange(selectedOptions) { selectedOptions.sort((a, b) => a.id - b.id) this.setState({selectedOptions}) }, render() { var {selectedOptions} = this.state return <div className="row"> <div className="col-md-5"> <FilteredMultiSelect classNames={BOOTSTRAP_CLASSES} onChange={this.handleSelectionChange} options={CULTURE_SHIPS} selectedOptions={selectedOptions} textProp="name" valueProp="id" /> <p className="help-block">Press Enter when there's only one matching item to select it.</p> </div> <div className="col-md-5"> {selectedOptions.length === 0 && <p>(nothing selected yet)</p>} {selectedOptions.length > 0 && <ol> {selectedOptions.map((ship, i) => <li key={ship.id}> {`${ship.name} `} <span style={{cursor: 'pointer'}} onClick={this.handleDeselect.bind(null, i)}> &times; </span> </li>)} </ol>} {selectedOptions.length > 0 && <button style={{marginLeft: 20}} className="btn btn-default" onClick={this.handleClearSelection}> Clear Selection </button>} </div> </div> } }) var AddRemoveSelection = React.createClass({ getInitialState() { return { selectedOptions: [] } }, handleDeselect(deselectedOptions) { var selectedOptions = this.state.selectedOptions.slice() deselectedOptions.forEach(option => { selectedOptions.splice(selectedOptions.indexOf(option), 1) }) this.setState({selectedOptions}) }, handleSelect(selectedOptions) { selectedOptions.sort((a, b) => a.id - b.id) this.setState({selectedOptions}) }, render() { var {selectedOptions} = this.state return <div className="row"> <div className="col-md-5"> <FilteredMultiSelect buttonText="Add" classNames={BOOTSTRAP_CLASSES} onChange={this.handleSelect} options={CULTURE_SHIPS} selectedOptions={selectedOptions} textProp="name" valueProp="id" /> </div> <div className="col-md-5"> <FilteredMultiSelect buttonText="Remove" classNames={{ filter: 'form-control', select: 'form-control', button: 'btn btn btn-block btn-default', buttonActive: 'btn btn btn-block btn-danger' }} onChange={this.handleDeselect} options={selectedOptions} textProp="name" valueProp="id" /> </div> </div> } }) var App = React.createClass({ render() { return <div className="container"> <div className="row header"> <div className="col-md-12"> <h1><a href="https://github.com/insin/react-filtered-multiselect">React &lt;FilteredMultiSelect/&gt;</a></h1> <p className="lead">A reusable React component for making and adding to selections using a filtered multi-select.</p> </div> </div> <h2>Basic Selection</h2> <p>Select some ships from <a href="http://en.wikipedia.org/wiki/The_Culture">The Culture</a>.</p> <BasicSelection/> <h2>Add &amp; Remove</h2> <p>Move items from one <code>&lt;FilteredMultiSelect/&gt;</code> to another and back again.</p> <AddRemoveSelection/> </div> } }) var app = document.querySelector('#app') if (!app) { app = document.createElement('div') app.id = 'app' document.body.appendChild(app) } render(<App/>, app)
packages/ringcentral-widgets/components/ActiveCallDialPad/index.js
u9520107/ringcentral-js-widget
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import DialPad from '../DialPad'; import CircleButton from '../CircleButton'; import BackHeader from '../BackHeader'; import audios from '../DialButton/audios'; import EndIcon from '../../assets/images/End.svg'; import styles from './styles.scss'; import i18n from './i18n'; const cleanRegex = /[^\d*#]/g; const filter = value => value.replace(cleanRegex, ''); const MAX_PASTE_LENGTH = 15; class ActiveCallDialPad extends Component { constructor(props) { super(props); this.state = { value: '', }; if (typeof document !== 'undefined' && document.createElement) { this.audio = document.createElement('audio'); } this.playAudio = (value) => { if (this.audio && this.audio.canPlayType('audio/ogg') !== '' && audios[value]) { if (!this.audio.paused) { this.audio.pause(); } this.audio.src = audios[value]; this.audio.currentTime = 0; this.audio.play(); } }; this.onButtonOutput = (key) => { this.setState((preState) => { const value = preState.value + key; this.props.onChange(key); return { value }; }); }; this.sendDTMFKeys = (keys) => { if (keys === '') { return; } keys.split('').forEach((key, index) => { setTimeout(() => { this.playAudio(key); this.props.onChange(key); }, 100 * index); }); }; this.onChange = (e) => { const value = filter(e.currentTarget.value); this.setState({ value }); }; this.onKeyDown = (e) => { const value = filter(e.key); this.sendDTMFKeys(value); }; this.onPaste = (e) => { const item = e.clipboardData.items[0]; item.getAsString((data) => { const value = filter(data); let keys = value; if (value.length > MAX_PASTE_LENGTH) { keys = value.slice(0, MAX_PASTE_LENGTH); } this.sendDTMFKeys(keys); if (value.length > MAX_PASTE_LENGTH) { this.setState(preState => ({ value: preState.value.replace(value, keys) })); } }); }; } render() { return ( <div className={styles.root}> <BackHeader onBackClick={this.props.hiddenDialPad}> {i18n.getString('keypad', this.props.currentLocale)} </BackHeader> <div className={styles.dialInput}> <input className={styles.input} value={this.state.value} onChange={this.onChange} onKeyDown={this.onKeyDown} onPaste={this.onPaste} autoFocus // eslint-disable-line /> </div> <div className={styles.padContainer}> <DialPad className={styles.dialPad} onButtonOutput={this.onButtonOutput} /> <div className={styles.buttonRow}> <div className={styles.button}> <CircleButton className={styles.stopButton} onClick={this.props.onHangup} icon={EndIcon} showBorder={false} /> </div> </div> </div> </div> ); } } ActiveCallDialPad.propTypes = { onChange: PropTypes.func.isRequired, hiddenDialPad: PropTypes.func.isRequired, onHangup: PropTypes.func.isRequired, currentLocale: PropTypes.string.isRequired, }; export default ActiveCallDialPad;
src/components/UserCell.js
rollo-zhou/look
import React from 'react'; import { ActivityIndicator, Image, PixelRatio, StyleSheet, Text, TouchableOpacity, View, Dimensions, } from 'react-native'; import globalVariables from '../globalVariables.js'; import User from './User.js'; import moment from 'moment'; import Icon from 'react-native-vector-icons/Ionicons'; import Storage from './Storage.js'; import Login from './Login.js'; const { width, height } = Dimensions.get('window'); var UserCell = React.createClass({ getDefaultProps() { return { user: {}, navigator:"", onSelect:false, showByline:false, needShowTime:true, title:"", time:"", needCenterView:false }; }, getInitialState() { return { isFaned:false, isMe:false, }; }, module:{ userFanned:null, user:null, }, componentWillMount() { if(!this.props.user){ return false; } globalVariables.getUser((user)=>{ if(user && user.id==this.props.user.id){ this.setState({ isMe:true, }); } }); globalVariables.getUserFanned((fanned)=>{ if(!fanned)return; this.module.userFanned=fanned; this.setState({isFaned:!!fanned[this.props.user.id]}); } ); }, shouldComponentUpdate: function(nextProps, nextState) { // return false; return JSON.stringify(nextState)!=JSON.stringify(this.state); }, getRightView(){ if(this.props.needShowTime||this.state.isFaned||this.state.isMe){ return( <View style={styles.timeView} > <Icon name="ios-clock-outline" color={globalVariables.textBase} size={20}/> <Text style={styles.timeText}> {globalVariables.formatDateToString(this.props.time)}</Text> </View> ); }else{ return ( <TouchableOpacity style={styles.cellfixed} activeOpacity={0.8} onPress={this.addUser}> <View style={styles.addUserView} > <Text style={styles.addUserText}>+</Text> </View> </TouchableOpacity>); } }, getCenterView(){ if(this.props.needCenterView){ return( <View style={styles.karmaView}> <Icon name="ios-flame-outline" color={globalVariables.base} size={20}/> <Text style={[styles.timeText,{color:globalVariables.base}]}> {this.props.user.karma_gain}</Text> </View> ); } }, render() { if(!this.props.user){ return false; } return ( <TouchableOpacity activeOpacity={0.8} style={styles.flexContainer} onPress={this.onSelect}> <View style={styles.cell}> <Image source={{uri:this.props.user.photo}} style={styles.avatar}/> <View style={styles.cellColumn}> <Text style={styles.userName}> {this.props.user.name} </Text> </View> </View> {this.getCenterView()} {this.getRightView()} </TouchableOpacity> ); }, addUser(){ globalVariables.getUser((user)=>{ if(!user){ this.props.navigator.push({ component: Login, backButtonTitle:' ', // backButtonIcon:this.state.backIcon, title: 'Login', passProps: { navigator:this.props.navigator, }, }); return; }else if(this.props.user && this.props.user.id){ var method=this.state.isFaned?"DELETE":"POST" this.setState({ isFaned:!this.state.isFaned, }); globalVariables.queryRromServer(globalVariables.apiUserServer+(this.props.user.id)+"/fan" ,this.processsResults ,{ method:method }); } }); return false; }, processsResults(data) { if(!data) return; if (data.status!="fanned") { delete this.module.userFanned[this.props.user.id]; this.setState({ isFaned:false, }); }else{ this.module.userFanned[this.props.user.id]=this.props.user.id; this.setState({ isFaned:true, }); } if (data && data.status){ globalVariables.setUserFanned(this.module.userFanned); } }, onSelect() { if(this.props.onSelect){ this.props.onSelect(this.props.user); }else{ this.props.navigator.push({ component: User, title: this.props.user.name, backButtonTitle:' ', passProps: { user:this.props.user, navigator:this.props.navigator, }, }); } }, }); const styles = StyleSheet.create({ flexContainer: { flex: 1, // 容器需要添加direction才能变成让子元素flex flexDirection: 'row', opacity:0.97, padding: 10, backgroundColor: globalVariables.background, alignItems: 'center', }, cellfixed: { width: 65, }, cell: { flexDirection: 'row', flex: 1, alignItems: 'center', }, cellColumn: { flexDirection: 'column', // justifyContent: 'flex-start', justifyContent: 'center', }, timeView:{ // flex: 1, // width: 50, alignItems:'center', flexDirection: 'row', marginRight:25, }, karmaView:{ // flex: 1, // width: 50, alignItems:'center', flexDirection: 'row', paddingRight:15, }, addUserView: { // flex: 1, width: 60, height: 30, borderWidth: 1, borderRadius: 3, borderColor: globalVariables.base, alignItems:'center', justifyContent: "center", // marginRight:10, }, addUserText:{ color:globalVariables.base, fontSize:16, // textAlign:"center", }, timeText:{ color:globalVariables.textBase, fontSize:14, marginLeft:3, }, userName: { // fontWeight: "400", color:globalVariables.base, // fontSize:12, marginLeft:3, }, avatar: { borderRadius: 18, width: 36, height: 36, marginRight: 5, marginLeft:5, backgroundColor:globalVariables.textBase2, } }); export default UserCell;
test/TagUncontroledGroupDemo.js
rsuite/rsuite-tag
import React, { Component } from 'react'; import { IconFont } from 'rsuite'; import Tag, { TagGroup } from '../src'; export default class TagUncontroledGroupDemo extends Component { constructor(props) { super(props); this.state = { tags: Object.keys(Tag.Color) }; } getColors = (color) => { const colors = Object.keys(Tag.Color); return colors.indexOf(color) > -1 ? color : Tag.Color.default; }; getTags = color => ( <Tag key={color} color={this.getColors(color)} closable={true} afterClose={() => { this.handleAfterClose(color); }} > <IconFont icon="bookmark" />{` ${color} 标签`} </Tag> ); handleAfterClose = (removeColor) => { let { tags } = this.state; tags = tags.filter(color => color !== removeColor); this.setState({ tags }); }; handleCreateInputConfirm = (tag) => { const state = this.state; let tags = state.tags; if (tag && tags.indexOf(tag) === -1) { tags = [...tags, tag]; } this.setState({ tags }); }; render() { return ( <div> <TagGroup onCreateInputConfirm={this.handleCreateInputConfirm}> {this.state.tags.map(this.getTags)} </TagGroup> </div> ); } }
client/modules/App/components/Footer/Footer.js
msucorey/street-canvas
import React from 'react'; import { Link } from 'react-router'; // Import Style import styles from './Footer.css'; export function Footer() { return ( <div className={styles.footer}> <ul> <li className={styles.bottomNav}> <Link to="/" >MAP</Link></li> <li className={styles.bottomNav}><Link to="/gallery" >GALLERY</Link></li> <li className={styles.addButton}><Link to="/add" >+</Link></li> </ul> </div> ); } export default Footer;
src/svg-icons/hardware/keyboard-arrow-up.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardArrowUp = (props) => ( <SvgIcon {...props}> <path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z"/> </SvgIcon> ); HardwareKeyboardArrowUp = pure(HardwareKeyboardArrowUp); HardwareKeyboardArrowUp.displayName = 'HardwareKeyboardArrowUp'; HardwareKeyboardArrowUp.muiName = 'SvgIcon'; export default HardwareKeyboardArrowUp;
src/components/BrowserHeader/index.js
bkrall/react-portfolio
import React, { Component } from 'react'; /* component styles */ import { styles } from './browserHeader.scss'; export class BrowserHeader extends Component { render() { const { title, showBioPic, showPageDescription, pageDescription, headingClassString, titleClass } = this.props; return ( <section className={styles}> <div className="browser"> <div className="browser-top"> <div className="browser-dots"></div> </div> <div className={`heading-title ${titleClass}`}> {showBioPic && <img src="http://sideproject.io/content/images/2016/09/2547195.jpeg" className="bio-pic" width="" alt="BK" /> } <h1 className={headingClassString}> {title} </h1> {showPageDescription && <p className="description text-center"> {pageDescription} </p> } <div className="button-container"> <a href="mailto:bkrall@gmail.com" target="_blank"> <i className="fa fa-envelope-o" aria-hidden="true"></i> &nbsp; Get in touch </a> &nbsp; &nbsp; </div> </div> </div> </section> ); } } BrowserHeader.propTypes = { title: React.PropTypes.string, titleClass: React.PropTypes.string, showBioPic: React.PropTypes.bool, showPageDescription: React.PropTypes.bool, headingClassString: React.PropTypes.string, pageDescription: React.PropTypes.string, };
frontend/app/utils/async/injectReducer.js
briancappello/flask-react-spa
import React from 'react' import PropTypes from 'prop-types' import hoistNonReactStatics from 'hoist-non-react-statics' import get from 'lodash/get' import getInjectors from './reducerInjectors' /** * Dynamically injects a reducer * * @param {string} key A key of the reducer * @param {function} reducer A reducer that will be injected * */ export default (props) => (WrappedComponent) => { if (get(props, '__esModule', false)) { props = { key: props.KEY, reducer: props.default, } } class ReducerInjector extends React.Component { static WrappedComponent = WrappedComponent static contextTypes = { store: PropTypes.object.isRequired, } static displayName = `withReducer(${(WrappedComponent.displayName || WrappedComponent.name || 'Component')})` componentWillMount() { const { injectReducer } = this.injectors injectReducer(props.key, props.reducer) } injectors = getInjectors(this.context.store) render() { return <WrappedComponent {...this.props} /> } } return hoistNonReactStatics(ReducerInjector, WrappedComponent) }
lavalab/html/node_modules/react-bootstrap/es/Col.js
LavaLabUSC/usclavalab.org
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import elementType from 'prop-types-extra/lib/elementType'; import { bsClass, prefix, splitBsProps } from './utils/bootstrapUtils'; import { DEVICE_SIZES } from './utils/StyleConfig'; var propTypes = { componentClass: elementType, /** * The number of columns you wish to span * * for Extra small devices Phones (<768px) * * class-prefix `col-xs-` */ xs: PropTypes.number, /** * The number of columns you wish to span * * for Small devices Tablets (≥768px) * * class-prefix `col-sm-` */ sm: PropTypes.number, /** * The number of columns you wish to span * * for Medium devices Desktops (≥992px) * * class-prefix `col-md-` */ md: PropTypes.number, /** * The number of columns you wish to span * * for Large devices Desktops (≥1200px) * * class-prefix `col-lg-` */ lg: PropTypes.number, /** * Hide column * * on Extra small devices Phones * * adds class `hidden-xs` */ xsHidden: PropTypes.bool, /** * Hide column * * on Small devices Tablets * * adds class `hidden-sm` */ smHidden: PropTypes.bool, /** * Hide column * * on Medium devices Desktops * * adds class `hidden-md` */ mdHidden: PropTypes.bool, /** * Hide column * * on Large devices Desktops * * adds class `hidden-lg` */ lgHidden: PropTypes.bool, /** * Move columns to the right * * for Extra small devices Phones * * class-prefix `col-xs-offset-` */ xsOffset: PropTypes.number, /** * Move columns to the right * * for Small devices Tablets * * class-prefix `col-sm-offset-` */ smOffset: PropTypes.number, /** * Move columns to the right * * for Medium devices Desktops * * class-prefix `col-md-offset-` */ mdOffset: PropTypes.number, /** * Move columns to the right * * for Large devices Desktops * * class-prefix `col-lg-offset-` */ lgOffset: PropTypes.number, /** * Change the order of grid columns to the right * * for Extra small devices Phones * * class-prefix `col-xs-push-` */ xsPush: PropTypes.number, /** * Change the order of grid columns to the right * * for Small devices Tablets * * class-prefix `col-sm-push-` */ smPush: PropTypes.number, /** * Change the order of grid columns to the right * * for Medium devices Desktops * * class-prefix `col-md-push-` */ mdPush: PropTypes.number, /** * Change the order of grid columns to the right * * for Large devices Desktops * * class-prefix `col-lg-push-` */ lgPush: PropTypes.number, /** * Change the order of grid columns to the left * * for Extra small devices Phones * * class-prefix `col-xs-pull-` */ xsPull: PropTypes.number, /** * Change the order of grid columns to the left * * for Small devices Tablets * * class-prefix `col-sm-pull-` */ smPull: PropTypes.number, /** * Change the order of grid columns to the left * * for Medium devices Desktops * * class-prefix `col-md-pull-` */ mdPull: PropTypes.number, /** * Change the order of grid columns to the left * * for Large devices Desktops * * class-prefix `col-lg-pull-` */ lgPull: PropTypes.number }; var defaultProps = { componentClass: 'div' }; var Col = function (_React$Component) { _inherits(Col, _React$Component); function Col() { _classCallCheck(this, Col); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Col.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = []; DEVICE_SIZES.forEach(function (size) { function popProp(propSuffix, modifier) { var propName = '' + size + propSuffix; var propValue = elementProps[propName]; if (propValue != null) { classes.push(prefix(bsProps, '' + size + modifier + '-' + propValue)); } delete elementProps[propName]; } popProp('', ''); popProp('Offset', '-offset'); popProp('Push', '-push'); popProp('Pull', '-pull'); var hiddenPropName = size + 'Hidden'; if (elementProps[hiddenPropName]) { classes.push('hidden-' + size); } delete elementProps[hiddenPropName]; }); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return Col; }(React.Component); Col.propTypes = propTypes; Col.defaultProps = defaultProps; export default bsClass('col', Col);
src/Jumbotron.js
deerawan/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import CustomPropTypes from './utils/CustomPropTypes'; const Jumbotron = React.createClass({ propTypes: { /** * You can use a custom element for this component */ componentClass: CustomPropTypes.elementType }, getDefaultProps() { return { componentClass: 'div' }; }, render() { const ComponentClass = this.props.componentClass; return ( <ComponentClass {...this.props} className={classNames(this.props.className, 'jumbotron')}> {this.props.children} </ComponentClass> ); } }); export default Jumbotron;
packages/ringcentral-widgets-docs/src/app/pages/Components/ConversationPanel/index.js
ringcentral/ringcentral-js-widget
import React from 'react'; import { parse } from 'react-docgen'; import CodeExample from '../../../components/CodeExample'; import ComponentHeader from '../../../components/ComponentHeader'; import PropTypeDescription from '../../../components/PropTypeDescription'; import Demo from './Demo'; // eslint-disable-next-line import demoCode from '!raw-loader!./Demo'; // eslint-disable-next-line import componentCode from '!raw-loader!ringcentral-widgets/components/ConversationPanel'; const ConversationPanelPage = () => { const info = parse(componentCode); return ( <div> <ComponentHeader name="ConversationPanel" description={info.description} /> <CodeExample code={demoCode} title="ConversationPanel Example"> <Demo /> </CodeExample> <PropTypeDescription componentInfo={info} /> </div> ); }; export default ConversationPanelPage;
examples/src/main.js
prometheusresearch/react-forms
import React from 'react'; import ReactDOM from 'react-dom'; import Examples from './Examples'; import './styles/main.css'; ReactDOM.render(( <Examples /> ), document.getElementById('root'));
src/js/components/icons/base/Play.js
odedre/grommet-final
/** * @description Play SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-play`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'play'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><polygon fill="none" stroke="#000" strokeWidth="2" points="3 22 21 12 3 2"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Play'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/components/Column.js
gakimball/react-inky
import React from 'react'; import PropTypes from 'prop-types'; import containsRow from '../util/containsRow'; import getAttrs from '../util/getAttrs'; import getColumnClasses from '../util/getColumnClasses'; import ContainerContext from '../util/containerContext'; /** * Grid column. Place sections of email content inside these. * @todo Remove expander if housing a nested grid * * @param {Object} props - Component props. * @returns {Object} Column HTML. * * @example * <Row> * <Column small="12" large="4"> * Left column * </Column> * <Column small="12" large="8"> * Right column * </Column> * </Row> */ export default function Column(props) { const hasRow = containsRow(props.children); return ( <ContainerContext.Consumer> {({columnCount}) => ( <th {...getAttrs(props, ['children', 'expander', 'first', 'last'], getColumnClasses(props, columnCount))}> <table> <tr> <th>{props.children}</th> {!hasRow && props.expander ? <th className="expander"/> : null} </tr> </table> </th> )} </ContainerContext.Consumer> ); } /** * Props for `<Column />`. * @type Object * @type {String} small - Width on small screens. * @type {String} large - Width on large screens. * @prop {Boolean} [expander=true] Include expander `<th />` in column. * @prop {Boolean} [first=false] Column is the first child. * @prop {Boolean} [last=false] Column is the last child. * @prop [children] - Child elements. */ Column.propTypes = { small: PropTypes.string, large: PropTypes.string, expander: PropTypes.bool, first: PropTypes.bool, last: PropTypes.bool, children: PropTypes.node }; /** * Default props for `<Column />`. * @type Object */ Column.defaultProps = { expander: true, first: false, last: false, children: null, small: null, large: null };
src/components/DevTools.js
yosiat/gc-flags-viz
import React from 'react'; // Exported from redux-devtools import { createDevTools } from 'redux-devtools'; // Monitors are separate packages, and you can make a custom one import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; // createDevTools takes a monitor and produces a DevTools component const DevTools = createDevTools( // Monitors are individually adjustable with props. // Consult their repositories to learn about those props. // Here, we put LogMonitor inside a DockMonitor. // Note: DockMonitor is visible by default. <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q' defaultIsVisible={true}> <LogMonitor theme='tomorrow' /> </DockMonitor> ); export default DevTools;
__tests__/components/NumberInput-test.js
odedre/grommet-final
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React from 'react'; import renderer from 'react-test-renderer'; import NumberInput from '../../src/js/components/NumberInput'; // needed because this: // https://github.com/facebook/jest/issues/1353 jest.mock('react-dom'); describe('NumberInput', () => { it('has correct default options', () => { const component = renderer.create( <NumberInput id="item2" name="item2" value={10} /> ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); });
front/app/js/rh-components/rh-IconCircleText.js
nudoru/learning-map
import React from 'react'; const IconCircleText = ({label, style, center, className}) => { let cls = 'rh-icon-circle-text'; if (style) { cls += '-' + style; } if (center) { cls += ' margin-center'; } if (className) { cls += ' ' + className; } return (<div className={cls}> <span>{label}</span> </div>); }; export default IconCircleText;
src/renderer/components/SyncView/SyncTarget.js
digidem/ecuador-map-editor
import React from 'react' import { makeStyles } from '@material-ui/core/styles' import PhoneIcon from '@material-ui/icons/PhoneAndroid' import LaptopIcon from '@material-ui/icons/Laptop' import FileIcon from '@material-ui/icons/Usb' import ErrorIcon from '@material-ui/icons/Error' import Paper from '@material-ui/core/Paper' import Typography from '@material-ui/core/Typography' import SyncButton from './SyncButton' import DateDistance from '../DateDistance' import { defineMessages, useIntl } from 'react-intl' const m = defineMessages({ // Message shown when there is an error while syncing errorMsg: 'Syncronization Error', // Shown before last sync time, e.g. 'Last synchronized: 2 hours ago' lastSync: 'Last synchronized:', // Prompt of how many database objects have synced database: 'Database: {sofar} / {total}', // Prompt for how many media items have synced media: 'Photos: {sofar} / {total}' }) const SyncTarget = ({ // Unique identifier for the peer id, // User friendly peer name name = 'Android Phone', // See above peerStatus status, // If connected connected, // Sync progress object, with props `percent`, `mediaSofar`, `mediaTotal`, // `dbSofar`, `dbTotal` progress, // The time of last completed sync in milliseconds since UNIX Epoch lastCompleted, errorMsg, // "mobile" or "desktop" or "file" deviceType, onClick }) => { const cx = useStyles() const { formatMessage: t, formatNumber } = useIntl() // TODO need to render device name in error screen return ( <Paper className={cx.root}> <div className={cx.wrapper}> <div className={cx.content}> {status === 'error' ? ( <ErrorIcon fontSize='inherit' className={cx.icon} style={{ color: 'red' }} /> ) : deviceType === 'desktop' ? ( <LaptopIcon fontSize='inherit' className={cx.icon} /> ) : deviceType === 'file' ? ( <FileIcon fontSize='inherit' className={cx.icon} /> ) : ( <PhoneIcon fontSize='inherit' className={cx.icon} /> )} <Typography variant='h5' component='h2'> {name} </Typography> {status === 'error' ? ( <Typography className={cx.errorDetail} align='center'> {errorMsg} </Typography> ) : status === 'progress' && progress ? ( <Typography className={cx.progress} align='center'> {t(m.database, { sofar: formatNumber(progress.dbSofar), total: formatNumber(progress.dbTotal) })} <br /> {t(m.media, { sofar: formatNumber(progress.mediaSofar), total: formatNumber(progress.mediaTotal) })} </Typography> ) : ( lastCompleted && ( <Typography className={cx.lastSync}> {t(m.lastSync)} <br /> <DateDistance date={lastCompleted} /> </Typography> ) )} </div> <SyncButton connected={connected} onClick={onClick} variant={status} progress={progress && progress.percent} /> </div> </Paper> ) } export default SyncTarget const useStyles = makeStyles(theme => ({ root: { paddingTop: '100%', position: 'relative' }, icon: { marginBottom: theme.spacing(2), fontSize: 48 }, lastSync: { textAlign: 'center', fontStyle: 'italic' }, errorDetail: { textAlign: 'center', fontStyle: 'italic' }, content: { flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }, wrapper: { alignItems: 'center', justifyContent: 'center', position: 'absolute', display: 'flex', flexDirection: 'column', top: 0, right: 0, bottom: 0, left: 0, padding: '10%' }, progress: { fontVariantNumeric: 'tabular-nums' } }))
docs/app/Examples/elements/Icon/Variations/IconExampleFitted.js
mohammed88/Semantic-UI-React
import React from 'react' import { Icon } from 'semantic-ui-react' const IconExampleFitted = () => ( <div> <p>Tight spacing</p> <Icon fitted name='help' /> <p>Tight spacing</p> </div> ) export default IconExampleFitted
src/svg-icons/editor/border-clear.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderClear = (props) => ( <SvgIcon {...props}> <path d="M7 5h2V3H7v2zm0 8h2v-2H7v2zm0 8h2v-2H7v2zm4-4h2v-2h-2v2zm0 4h2v-2h-2v2zm-8 0h2v-2H3v2zm0-4h2v-2H3v2zm0-4h2v-2H3v2zm0-4h2V7H3v2zm0-4h2V3H3v2zm8 8h2v-2h-2v2zm8 4h2v-2h-2v2zm0-4h2v-2h-2v2zm0 8h2v-2h-2v2zm0-12h2V7h-2v2zm-8 0h2V7h-2v2zm8-6v2h2V3h-2zm-8 2h2V3h-2v2zm4 16h2v-2h-2v2zm0-8h2v-2h-2v2zm0-8h2V3h-2v2z"/> </SvgIcon> ); EditorBorderClear = pure(EditorBorderClear); EditorBorderClear.displayName = 'EditorBorderClear'; EditorBorderClear.muiName = 'SvgIcon'; export default EditorBorderClear;
src/client/index.js
mitola/awesome-game
import React from 'react'; import ReactDOM from 'react-dom'; import './less/index.less'; import App from './App'; import registerServiceWorker from './utils/registerServiceWorker'; //TMP dependacy for material var injectTapEventPlugin = require("react-tap-event-plugin"); injectTapEventPlugin(); ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
src/routes/app/routes/ui/routes/menus/components/Menus.js
ahthamrin/kbri-admin2
import React from 'react'; import QueueAnim from 'rc-queue-anim'; import Menu from './Menu'; import IconMenu from './IconMenu'; import DropdownMenu from './DropdownMenu'; const Menus = () => ( <section className="container-fluid with-maxwidth chapter"> <QueueAnim type="bottom" className="ui-animate"> <div key="1"><Menu /></div> <div key="2"><IconMenu /></div> <div key="3"><DropdownMenu /></div> </QueueAnim> </section> ); module.exports = Menus;
core/subschema-test-support/src/index.js
subschema/subschema-devel
import React, { Component } from 'react'; import PropTypes from 'subschema-prop-types'; import ValueManager from 'subschema-valuemanager'; import loader from 'subschema-loader'; import injector from 'subschema-injection'; import ReactDOM from 'react-dom'; import { expect } from 'chai'; import { ReactWrapper, configure, mount as _mount } from 'enzyme'; function prettyLog(result) { console.log(JSON.stringify(result, null, '\t')); } function cleanUp() { const nodes = document.getElementsByClassName('__test__inserted__'); let node; while ((node = nodes[0])) { try { const ret = ReactDOM.unmountComponentAtNode(node); } catch (e) { console.trace(e); } nodes[0].parentNode.removeChild(node); } } let __id = 0; function into(node, debug) { const attachTo = document.createElement('div'); attachTo.className = `__test__inserted__`; attachTo.id = `__test_${__id++}`; if (debug === true) { document.body.appendChild(attachTo); } return _mount(node, { attachTo }); } function notByType(node, type, description) { const ret = byTypes(node, type); expect(ret.at(0), description).to.have.length(0); return ret; } function expected(nodes, length) { if (length === void(0)) { return nodes; } if (nodes.length !== length) { expect(nodes).to.have.length(length); } return nodes; } function byTypes(node, type, length) { const rest = expected(node.find(type), length); return rest; } function byType(node, type) { return node.find(type); } function byTag(node, tag) { return node.find(`${tag}`); } function byTags(node, tag, length) { return expected(node.find(`${tag}`), length); } function onlyOne(node) { expect(node).to.have.length(1); return node; } function byName(root, prop) { return root.find(`[name="${prop}"]`) } function filterProp(node, property, value) { node = Array.isArray(node) ? node : [node]; return node.filter((n) => { const props = (n instanceof Element) ? n.attributes : n.props; if (property in props) { if (value === null) { return true; } return props[property] === value; } return false; }) } function byId(node, id) { return onlyOne(node.find(`#${id}`)); } function click(node, form) { node.simulate('click'); form && form.update(); return node; } function change(node, value, form) { node.simulate('change', { target: { value } }); form && form.update(); return node; } function check(node, checked, value, form) { node.simulate('change', { target: { checked, value } }); form && form.update(); return node; } function blur(node, form) { node.simulate('blur'); form && form.update(); return node; } function focus(node, form) { node.simulate('focus') form && form.update() return node; } function submit(node, value, form){ node.simulate('submit', value) form && form.update(); return node; } function byComponent(node, comp) { return onlyOne(node.find(comp)); } function byComponents(node, comp, length) { return expected(node.find(comp), length); } function byClass(node, className) { return node.find(`.${className}`); } function findNode(n) { return n.getDOMNode(); } function defChildContext() { return { valueManager: ValueManager(), loader : loader, injector : injector }; } function intoWithContext(child, context, attachTo, contextTypes) { if (attachTo == true) { attachTo = document.createElement('div'); document.body.appendChild(attachTo); } else if (attachTo == null || attachTo == false) { attachTo = document.createElement('div'); } if (context && !contextTypes) { contextTypes = Object.keys(context).reduce(function (ret, key) { ret[key] = PropTypes[key] || PropTypes.any; return ret; }, {}); } return _mount(child, { context, attachTo, contextTypes, childContextTypes:contextTypes }); } function select(node, index) { const multiple = Array.isArray(index); const options = byTags(node, 'option').map(v => v.getDOMNode()); if (!multiple) { options.forEach((option, idx) => { option.selected = (idx === index); }) } else { options[index].selected = !options[index].selected } node.simulate('change', { target: { options, value: multiple ? options.map(o => o.value) : options[index].value } }); return node; } class StateWrapper extends Component { render() { return React.cloneElement(this.props.children, this.state); } } function intoWithState(child, state, debug) { const s = into(<StateWrapper>{child}</StateWrapper>, debug); if (state != null) { s.instance().setState(state); } return { state: s, child: s.first() } } function mount(node, debug) { if (debug) { const attachTo = document.createElement('div'); document.body.appendChild(attachTo); return _mount(node, { attachTo }); } return _mount(node); } export { mount, cleanUp, React, ReactDOM, intoWithState, into, intoWithContext, prettyLog, findNode, expect, byId, byName, byTags, byTag, byType, byTypes, notByType, filterProp, byClass, byComponent, byComponents, //trigger events select, click, change, check, blur, focus, expected, submit }
docs/app/Examples/elements/Divider/Variations/DividerExampleSection.js
shengnian/shengnian-ui-react
import React from 'react' import { Divider, Segment } from 'shengnian-ui-react' const DividerExampleSection = () => ( <Segment> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore... <Divider section /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore... </Segment> ) export default DividerExampleSection
src/js/components/AccordionPanel.js
hadnazzar/ModernBusinessBootstrap-ReactComponent
import React from 'react'; export default class AccordionPanel extends React.Component { render() { return( <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="panel-group" id="accordion"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href={this.props.hrefNumber}>{this.props.header}</a> </h4> </div> <div id={this.props.hrefId} class="panel-collapse collapse"> <div class="panel-body"> {this.props.content} </div> </div> </div> </div> </div> </div> </div> ); } }
app/comp/HorizontalProgressComp.js
iwgang/GankCamp-React-Native
import React, { Component } from 'react'; import { View, ProgressViewIOS, ProgressBarAndroid, Platform } from 'react-native'; class HorizontalProgressComp extends Component { render() { if (Platform.OS === 'android') { return ( <ProgressBarAndroid styleAttr="Horizontal" color={this.props.color} progress={60} style={this.props.style} /> ); } else { return ( <ProgressViewIOS progress={0.98} trackTintColor={'#CCCCCC'} progressTintColor={this.props.color} style={this.props.style} /> ); } } } export default HorizontalProgressComp;
src/components/Submit.js
nickorsk2020/agave-react-UI
/* * This file is part of the "Agave react UI" package * * Copyright (c) 2016 Stepanov Nickolay <nickorsk2020@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ import React from 'react'; import { Button } from 'react-bootstrap'; const Submit = React.createClass({ render() { return( <Button className={this.props.className} onClick={this.props.onSubmit}>{this.props.name}</Button> ); } }); export default Submit;
src/docs/layout/Footer.js
reactstrap/component-template
import React from 'react'; import { Container, Row, Col } from 'reactstrap'; const Footer = ({gh}) => { const [user, repo] = gh.split('/'); return ( <div className="footer mt-1"> <Container fluid> <Row> <Col className="text-center"> <p className="social"> <iframe src={`https://ghbtns.com/github-btn.html?user=${user}&repo=${repo}&type=star&count=true`} frameBorder="0" scrolling="0" width="100" height="20px" /> <iframe src={`https://ghbtns.com/github-btn.html?user=${user}&repo=${repo}&type=fork&count=true`} frameBorder="0" scrolling="0" width="100" height="20px" /> </p> </Col> </Row> </Container> </div> ); }; export default Footer;
src/common/components/DevTools/index.js
colinmeinke/universal-js
import DockMonitor from 'redux-devtools-dock-monitor' import LogMonitor from 'redux-devtools-log-monitor' import React from 'react' import { createDevTools } from 'redux-devtools' const DevTools = createDevTools( <DockMonitor changePositionKey='ctrl-q' toggleVisibilityKey='ctrl-h' > <LogMonitor /> </DockMonitor> ) export default DevTools
react/AndroidIcon/AndroidIcon.js
seekinternational/seek-asia-style-guide
import svgMarkup from './AndroidIcon.svg'; import React from 'react'; import Icon from '../private/Icon/Icon'; export default function AndroidIcon({ ...props }) { return <Icon markup={svgMarkup} {...props} />; } AndroidIcon.displayName = 'AndroidIcon';
src/svg-icons/image/filter-center-focus.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilterCenterFocus = (props) => ( <SvgIcon {...props}> <path d="M5 15H3v4c0 1.1.9 2 2 2h4v-2H5v-4zM5 5h4V3H5c-1.1 0-2 .9-2 2v4h2V5zm14-2h-4v2h4v4h2V5c0-1.1-.9-2-2-2zm0 16h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4zM12 9c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/> </SvgIcon> ); ImageFilterCenterFocus = pure(ImageFilterCenterFocus); ImageFilterCenterFocus.displayName = 'ImageFilterCenterFocus'; export default ImageFilterCenterFocus;
app/components/ListItem/index.js
ddobby94/szakdoge_admin
import React from 'react'; import Item from './Item'; import Wrapper from './Wrapper'; function ListItem(props) { return ( <Wrapper> <Item> {props.item} </Item> </Wrapper> ); } ListItem.propTypes = { item: React.PropTypes.any, }; export default ListItem;
src/Row.js
roderickwang/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import CustomPropTypes from './utils/CustomPropTypes'; const Row = React.createClass({ propTypes: { /** * You can use a custom element for this component */ componentClass: CustomPropTypes.elementType }, getDefaultProps() { return { componentClass: 'div' }; }, render() { let ComponentClass = this.props.componentClass; return ( <ComponentClass {...this.props} className={classNames(this.props.className, 'row')}> {this.props.children} </ComponentClass> ); } }); export default Row;
app/components/Reusables/RefreshableListView.js
ethan605/react-native-zero
/** * @providesModule ZeroProj.Components.Reusables.RefreshableListView */ import React from 'react'; import { ListView, RefreshControl } from 'react-native'; import _ from 'lodash'; export default class RefreshableListView extends React.PureComponent { static propTypes = { onError: React.PropTypes.func, onFetchData: React.PropTypes.func.isRequired, paginationEnabled: React.PropTypes.bool, placeholderData: React.PropTypes.object, refreshControlEnabled: React.PropTypes.bool, renderPlaceholderOnly: React.PropTypes.bool, }; static defaultProps = { onError: null, paginationEnabled: true, placeholderData: {}, refreshControlEnabled: true, renderPlaceholderOnly: false, }; constructor(props) { super(props); const { onFetchData, onError } = props; this.onError = onError && onError.bind(this); this.onFetchData = onFetchData && onFetchData.bind(this); // Component.isMounted is deprecated, this is a workaround this.mounted = false; } state = { currentPage: 1, dataSource: this.defaultDataSource, isLastPageReached: false, isLoading: false, isRefresing: false, }; componentDidMount() { this.mounted = true; // Initialize data list with placholders this.reset(); } componentWillReceiveProps(nextProps) { if (this.props.renderPlaceholderOnly && !nextProps.renderPlaceholderOnly) this.fetchData(); } componentWillUnmount() { this.mounted = false; } get defaultDataSource() { return new ListView.DataSource({ getRowData: ((dataBlob, sectionID, rowID) => dataBlob[sectionID][parseInt(rowID)]), getSectionHeaderData: (sectionID => sectionID), rowHasChanged: ((r1, r2) => r1 !== r2), sectionHeaderHasChanged: ((s1, s2) => s1 !== s2), }); } // Reset all contents reset = () => { const newState = { currentPage: 1, isLoading: true }; this.updateStates(newState, this.reloadData); }; renderRefreshControl = () => ( <RefreshControl refreshing={this.state.isRefresing} onRefresh={this.refreshData} /> ); reloadData = () => { const { placeholderData, renderPlaceholderOnly } = this.props; this.populateData(placeholderData); this.listView.scrollTo({ animated: false }); if (!renderPlaceholderOnly) this.fetchData(); }; // API requests fetchData = async () => { const { currentPage } = this.state; try { const { newData, isEmptyData = false, isLastPage = false, } = await this.onFetchData(currentPage); const willAppendData = currentPage > 1 && !isEmptyData; this.populateData(newData, willAppendData); this.resetStates(isLastPage); } catch (error) { this.resetStates(); this.onError && this.onError(error); } }; // Pull to refresh refreshData = () => { const newState = { currentPage: 1, isRefresing: true, isLoading: true }; this.updateStates(newState, this.fetchData); }; // Pagination pullMoreData = () => { const { isLoading, isLastPageReached } = this.state; if (isLoading || isLastPageReached) return; const newState = { currentPage: this.state.currentPage + 1, isLoading: true }; this.updateStates(newState, this.fetchData); }; populateData = (newRawData, willAppendData = false) => { const { dataSource } = this.state; /* eslint-disable no-underscore-dangle */ const originalData = willAppendData ? dataSource._dataBlob : {}; /* eslint-enable no-underscore-dangle */ const newData = this.mergeData(originalData, newRawData); const newDataSource = dataSource.cloneWithRowsAndSections(newData); const newState = Object.assign({}, this.state, { dataSource: newDataSource }); this.updateStates(newState); }; mergeData = (original, updated) => { const mergedData = {}; const allKeys = _.uniq(_.concat(Object.keys(original), Object.keys(updated))); allKeys.forEach(key => { const originalData = original[key] || []; const updatedData = updated[key] || []; mergedData[key] = _.concat(originalData, updatedData); }); return mergedData; }; resetStates = isLastPage => { const lastPageState = isLastPage == null ? {} : { isLastPageReached: isLastPage }; const newState = { isLoading: false, isRefresing: false, ...lastPageState }; this.updateStates(newState); }; updateStates = (newState, callback) => { if (!this.mounted) return; this.setState(newState, callback != null ? callback : undefined); } render() { const { paginationEnabled, refreshControlEnabled } = this.props; const refreshProps = refreshControlEnabled ? { refreshControl: this.renderRefreshControl() } : null; const paginationProps = paginationEnabled ? { onEndReached: this.pullMoreData } : null; return ( <ListView {...this.props} dataSource={this.state.dataSource} removeClippedSubviews={false} ref={ref => this.listView = ref} {...paginationProps} {...refreshProps} /> ); } }
app/assets/javascripts/libNmrSim/SampleDetailsTabName.js
ComPlat/nmr_sim
import React from 'react'; export default <div style={{ maxHeight: 25 }}>NMR</div>;
app/components/Sidebar/Sidebar.js
RichardLilja/BMC
// @flow import React, { Component } from 'react'; import styles from './Sidebar.scss'; export default class Sidebar extends Component { render() { return ( <section className={styles.container}> <header className={styles.header}> <h1 className={styles.headerHeading1}>Header</h1> </header> <ul className={styles.menuList}> <li className={styles.menuListItem}>Item 1</li> <li className={styles.menuListItem}>Item 2</li> </ul> </section> ); } }
src/App.js
kosmologist/andromeda-web
import React from 'react'; import 'react-circular-progressbar/dist/styles.css' import Landing from "./components/Landing"; import {initFirebase} from "./firebase/fire"; import {store} from './store/DataStore' import Spinner from "./components/Spinner"; import Dashboard from "./components/Dashboard"; export default class App extends React.Component { constructor(props) { super(props) initFirebase(); this.state = {isAuthenticated: false, isReady: false}; store.subscribe(() => { this.setState({isAuthenticated: store.getState().isLoggedIn, isReady: true}) }) } render() { return (this.state.isReady ? (this.state.isAuthenticated ? <Dashboard/> : <Landing/>) : <Spinner/>) } }
src/scenes/SettingsConfig/SettingsConfigContainer.js
jmlweb/paskman
import React, { Component } from 'react'; import PT from 'prop-types'; import { connect } from 'react-redux'; import { settingsFetchAction, settingsSaveAction, settingsChangeAction, } from '../../data/settings/duck'; import Loading from '../../components/Loading/Loading'; import SettingsConfig from './SettingsConfig'; import constants from './constants'; class SettingsConfigContainer extends Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); this.handleTargetSlider = this.handleTargetSlider.bind(this); this.handleConfirmEndingTaskChange = this.handleConfirmEndingTaskChange.bind(this); this.handlePauseBetweenChange = this.handlePauseBetweenChange.bind(this); } state = { isFetching: true, } componentDidMount() { const { settingsFetch } = this.props; settingsFetch(); } componentWillReceiveProps(nextProps) { const { isFetching, target, pauseBetween, confirmEndingTask, } = nextProps; this.setState({ isFetching, target, pauseBetween, confirmEndingTask, }); } handleSubmit(e) { const { settingsSave } = this.props; e.preventDefault(); settingsSave({ ...this.state, }); } handleTargetSlider(mode) { return (value) => { this.setState({ target: { ...this.state.target, [`${mode}`]: value, }, }); }; } handleConfirmEndingTaskChange(e) { this.setState({ confirmEndingTask: e.target.value === 'true' && true, }); } handlePauseBetweenChange(e) { this.setState({ pauseBetween: e.target.value === 'true' && true, }); } render() { if (this.props.isFetching || this.state.isFetching) { return <Loading text="Loading data..." />; } return ( <div> {this.props.isSaving && <Loading text="Saving data..." />} <SettingsConfig target={this.state.target} pauseBetween={this.state.pauseBetween} confirmEndingTask={this.state.confirmEndingTask} handleSubmit={this.handleSubmit} handleTargetSlider={this.handleTargetSlider} handleConfirmEndingTaskChange={this.handleConfirmEndingTaskChange} handlePauseBetweenChange={this.handlePauseBetweenChange} defaults={constants} /> </div> ); } } SettingsConfigContainer.defaultProps = { isFetching: false, isSaving: false, pauseBetween: false, confirmEndingTask: false, }; SettingsConfigContainer.propTypes = { isFetching: PT.bool, isSaving: PT.bool, target: PT.shape({ working: PT.number, resting: PT.number, }).isRequired, pauseBetween: PT.bool, confirmEndingTask: PT.bool, settingsFetch: PT.func.isRequired, settingsSave: PT.func.isRequired, }; export function mapStateToProps(state) { return { ...state.data.settings }; } export const mapDispatchToProps = { settingsFetch: settingsFetchAction, settingsSave: settingsSaveAction, settingsChange: settingsChangeAction, }; const SettingsConfigConnectedContainer = connect( mapStateToProps, mapDispatchToProps, )(SettingsConfigContainer); export default SettingsConfigConnectedContainer;
actor-apps/app-web/src/app/components/sidebar/ContactsSectionItem.react.js
xiaotaijun/actor-platform
import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; import DialogActionCreators from 'actions/DialogActionCreators'; import AvatarItem from 'components/common/AvatarItem.react'; const {addons: { PureRenderMixin }} = addons; @ReactMixin.decorate(PureRenderMixin) class ContactsSectionItem extends React.Component { static propTypes = { contact: React.PropTypes.object }; constructor(props) { super(props); } openNewPrivateCoversation = () => { DialogActionCreators.selectDialogPeerUser(this.props.contact.uid); } render() { const contact = this.props.contact; return ( <li className="sidebar__list__item row" onClick={this.openNewPrivateCoversation}> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> </li> ); } } export default ContactsSectionItem;
packages/bonde-admin/src/components/dev-tools/index.js
ourcities/rebu-client
import React from 'react' // Exported from redux-devtools import { createDevTools } from 'redux-devtools' // Monitors are separate packages, and you can make a custom one import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' // createDevTools takes a monitor and produces a DevTools component const DevTools = createDevTools( // Monitors are individually adjustable with props. // Consult their repositories to learn about those props. // Here, we put LogMonitor inside a DockMonitor. // Note: DockMonitor is visible by default. <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q' defaultIsVisible={false}> <LogMonitor theme='tomorrow' /> </DockMonitor> ) export default DevTools
es/mobile/components/RoomHistory/HistoryList.js
welovekpop/uwave-web-welovekpop.club
import _extends from "@babel/runtime/helpers/builtin/extends"; import React from 'react'; import ReactDOM from 'react-dom'; import withProps from 'recompose/withProps'; import List from "@material-ui/core/es/List"; import Base from '../../../components/MediaList/BaseMediaList'; import HistoryRow from './Row'; var HistoryList = withProps({ className: 'RoomHistory-list', listComponent: React.forwardRef(function (props, _ref) { return React.createElement(List, _extends({}, props, { ref: function ref(list) { return _ref(list && ReactDOM.findDOMNode(list)); } // eslint-disable-line react/no-find-dom-node })); }), rowComponent: HistoryRow })(Base); export default HistoryList; //# sourceMappingURL=HistoryList.js.map
src/components/ListItem.js
dazhifu/react-touch-ui
import React from 'react'; import assign from 'object-assign' import classnames from 'classnames'; import { View } from "./View.js" import Utils from "./common/Utils.js" import './ListItem.scss' import ArrowRight from 'react-icons/lib/io/ios-arrow-forward'; export class ListItem extends React.Component { static propTypes = { // 主标题 title: React.PropTypes.string, //子标题 subTitle: React.PropTypes.string, // 是否显示右箭头,默认不显示, = true 显示 indicator: React.PropTypes.string, // 右上角 时间 after: React.PropTypes.string, // 描述 desc: React.PropTypes.string, // 左icon media: React.PropTypes.string, } static defaultProps = { } constructor(props) { super(props); }; renderTitleRow() { let { title, subTitle, indicator, } = this.props; let itemTitle = title ? ( <div key="itemTitle" className={ classnames('aui-item-title')} > {title} </div> ) : null; let titleChildren = [ itemTitle, this.renderAddon('after'), indicator ? ( <div className={classnames('aui-item-icon')} > <ArrowRight /> </div> ) : null, ]; return subTitle ? ( <div className={ classnames('aui-item-title-row') } key="itemTitleRow" > {titleChildren} </div> ) : titleChildren; }; renderMain() { let { media, subTitle, desc, children } = this.props; let titleRow = this.renderTitleRow(); let notJustTitle = media || subTitle || desc || children; // remove wrapper if without media/subTitle/children return notJustTitle ? ( <div className={classnames('aui-item-main') } > {titleRow} {this.renderAddon('subTitle')} {this.renderAddon('desc')} {children} </div> ) : titleRow; }; wrapLink(children) { let { linkComponent, linkProps, href, target, } = this.props; return linkComponent ? React.createElement(linkComponent, linkProps, children) : ( <a href={href} target={target} > {children} </a>); }; renderAddon(type) { return this.props[type] ? ( <div className={classnames('aui-item-' +type.toLowerCase()) } > {this.props[type]} </div> ) : null; }; onTouchTapEvent(e) { let { tag, } = this.props; if (this.onTouchTap) this.onTouchTap(e,tag) } render() { let { className, role, subTitle, onTouchTap, media, children, indicator, nested, ...props } = this.props; this.onTouchTap = onTouchTap; delete props.title; delete props.after; delete props.linkProps; delete props.desc; let itemChildren = [ this.renderAddon('media'), this.renderMain(), ]; let classSet = {}; classSet[classnames('aui-item-' + nested)] = nested; classSet[classnames('aui-item-header')] = role === 'header'; classSet[classnames('aui-item-linked')] = indicator; subTitle && (classSet[classnames('aui-item-content')] = true); return ( <li {...props} onTouchTap={this.onTouchTapEvent.bind(this)} className={classnames("aui-item",classSet, className)} > {role === 'header' ? children : (indicator) ? this.wrapLink(itemChildren) : itemChildren} </li> ); } }
test/integration/css-fixtures/bad-custom-configuration-arr-2/pages/_app.js
zeit/next.js
import React from 'react' import App from 'next/app' import '../styles/global.css' class MyApp extends App { render() { const { Component, pageProps } = this.props return <Component {...pageProps} /> } } export default MyApp
app/containers/BudgetGrid/__tests__/index-test.js
ModusCreateOrg/budgeting-sample-app-webpack2
import React from 'react'; import renderer from 'react-test-renderer'; import { BudgetGrid } from '../index'; // mock nested component jest.mock('containers/EntryFormRow'); it('renders correctly', () => { const tree = renderer.create(<BudgetGrid transactions={[]} />).toJSON(); expect(tree).toMatchSnapshot(); });
lib/cli/test/fixtures/react_scripts_v2/src/index.js
storybooks/react-storybook
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: http://bit.ly/CRA-PWA serviceWorker.unregister();
app/javascript/mastodon/features/ui/components/column_link.js
Craftodon/Craftodon
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; const ColumnLink = ({ icon, text, to, href, method }) => { if (href) { return ( <a href={href} className='column-link' data-method={method}> <i className={`fa fa-fw fa-${icon} column-link__icon`} /> {text} </a> ); } else { return ( <Link to={to} className='column-link'> <i className={`fa fa-fw fa-${icon} column-link__icon`} /> {text} </Link> ); } }; ColumnLink.propTypes = { icon: PropTypes.string.isRequired, text: PropTypes.string.isRequired, to: PropTypes.string, href: PropTypes.string, method: PropTypes.string, }; export default ColumnLink;
js/src/components/Editor/__test__/editorTest.js
understory-dev/react-draft-wysiwyg
/* @flow */ import React from 'react'; import { expect, assert } from 'chai'; import { shallow, mount } from 'enzyme'; import Editor from '..'; describe('Editor test suite', () => { it('should have a div when rendered', () => { expect(shallow(<Editor />).html().startsWith('<div')).to.be.true; }); it('should have an editorState object in state', () => { const editor = shallow(<Editor />); assert.isDefined(editor.state().editorState); assert.isDefined(editor.state().editorFocused); }); it('should have toolbarHidden as false by default', () => { const editor = shallow(<Editor />); expect(editor.find('.rdw-editor-toolbar')).to.have.length(1); }); it('should not have toolbar if toolbarHidden is set to true', () => { const editor = shallow(<Editor toolbarHidden />); expect(editor.find('.rdw-editor-toolbar')).to.have.length(0); }); });
src/svg-icons/action/receipt.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionReceipt = (props) => ( <SvgIcon {...props}> <path d="M18 17H6v-2h12v2zm0-4H6v-2h12v2zm0-4H6V7h12v2zM3 22l1.5-1.5L6 22l1.5-1.5L9 22l1.5-1.5L12 22l1.5-1.5L15 22l1.5-1.5L18 22l1.5-1.5L21 22V2l-1.5 1.5L18 2l-1.5 1.5L15 2l-1.5 1.5L12 2l-1.5 1.5L9 2 7.5 3.5 6 2 4.5 3.5 3 2v20z"/> </SvgIcon> ); ActionReceipt = pure(ActionReceipt); ActionReceipt.displayName = 'ActionReceipt'; ActionReceipt.muiName = 'SvgIcon'; export default ActionReceipt;
react-router-demo/src/index.js
iosWorker/iosWorker.github.io
import React from 'react'; import ReactDOM from 'react-dom'; import Root from './Root'; ReactDOM.render( <Root />, document.getElementById('root') );
src/components/settings/password-form.js
Lokiedu/libertysoil-site
/* This file is a part of libertysoil.org website Copyright (C) 2016 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import PropTypes from 'prop-types'; import React from 'react'; import { form as inform, from, DisabledFormSubmit } from 'react-inform'; import { omit, reduce } from 'lodash'; import classNames from 'classnames'; import Message from '../message'; const staticFields = { oldPassword: { label: 'Current password:' }, newPassword: { label: 'New password:' }, newPasswordRepeat: { label: 'Repeat new password:' }, }; const PasswordForm = ({ fields, form, onSubmit }) => ( <form action="" autoComplete="off" onSubmit={onSubmit}> <input name="autofillWorkaround" style={{ display: 'none' }} type="password" /> {reduce( fields, (acc, fieldValue, fieldName) => { const wrapClassName = classNames('input_wrap', { 'input_wrap-error': !!fieldValue.error }); acc.push( <div className="paper__page paper__page--no_padding" key={fieldName}> <div className="old-form__row paper__page--medium"> <label className="old-form__label" htmlFor={fieldName}> {staticFields[fieldName].label} </label> <div className={wrapClassName}> <input autoFocus={fieldName === 'oldPassword'} className="input input-block input-narrow input-transparent" id={fieldName} name={fieldName} required type="password" {...omit(fieldValue, ['error'])} /> </div> </div> {fieldValue.error && <div> <Message message={fieldValue.error} /> </div> } </div> ); return acc; }, [] )} <div className="paper__page paper__page--medium layout__raw_grid layout__raw_grid--reverse"> <DisabledFormSubmit className="button button-wide button-green button--new" type="submit" value="Save" /> </div> </form> ); PasswordForm.displayName = 'PasswordForm'; PasswordForm.propTypes = { fields: PropTypes.shape({ oldPassword: PropTypes.shape({ error: PropTypes.string }).isRequired, newPassword: PropTypes.shape({ error: PropTypes.string }).isRequired, newPasswordRepeat: PropTypes.shape({ error: PropTypes.string }).isRequired }).isRequired, form: PropTypes.shape({ isValid: PropTypes.func }), onSubmit: PropTypes.func }; PasswordForm.defaultProps = { onSubmit: () => {} }; const validateNewPassword = (password) => { if (password && password.length < 8) { return false; } return true; }; const validateNewPasswordChars = (password) => { if (!password.match(/[\x20-\x7E]$/)) { return false; } return true; }; const validateNewPasswordRepeat = (newPasswordRepeat, form) => { if (form.newPassword !== newPasswordRepeat) { return false; } return true; }; const WrappedPasswordForm = inform(from({ oldPassword: { 'Enter your current password': o => o }, newPassword: { 'Enter new password': n => n, 'Password must contain at least 8 symbols': validateNewPassword, 'Password must contain only ASCII characters': validateNewPasswordChars }, newPasswordRepeat: { 'Passwords don\'t match': validateNewPasswordRepeat } }))(PasswordForm); export default WrappedPasswordForm;
public/javascripts/pages/main.js
kenticny/CasualData
import React from 'react'; import { Menu, Breadcrumb, Icon } from 'antd'; const ReactRouter = require('react-router'); module.exports = React.createClass({ getInitialState: function() { return { current: 'dashboard' } }, handleClick: function(e) { this.setState({ current: e.key }); }, render: function() { return ( <div id="casual-data-app"> <div id="header"> <div className="logo">Casual Data</div> <Menu className="menu-bar" onClick={this.handleClick} selectedKeys={[this.state.current]} mode="horizontal"> <Menu.Item className="menu-item" key="properties"> <Icon type="setting" />Properties </Menu.Item> <Menu.Item className="menu-item" key="datasources"> <Icon type="cloud" />DataSources </Menu.Item> <Menu.Item className="menu-item" key="projects"> <a href="/#/projects"><Icon type="folder" />Projects</a> </Menu.Item> <Menu.Item className="menu-item" key="dashboard"> <a href="/#/dashboard"><Icon type="appstore" />Dashboard</a> </Menu.Item> </Menu> </div> <div id="nav"> <Breadcrumb {...this.props} router={ReactRouter} /> </div> <div id="content">{this.props.children}</div> </div> ); } });
imports/ui/components/UploadPdfCopy/UploadPdfCopy.js
jamiebones/Journal_Publication
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { Table, Alert, Button , Row , Col } from 'react-bootstrap'; import { Bert } from 'meteor/themeteorchef:bert'; import { Capitalize } from '../../../modules/utilities'; import { SortReturnRecentOne, StripHtml } from '../../../modules/utilities2'; import Loading from '../../components/Loading/Loading'; import Uploader from '../Uploader/Uploader'; import { createContainer } from 'meteor/react-meteor-data'; import { Meteor } from 'meteor/meteor'; import './UploadPdfCopy.scss'; const removePdfCopy = ( paperId , paperToRemove ) => { const obj = paperToRemove; const askMe = confirm('Are you sure '); if (askMe){ Meteor.call('paper.deletePdfCopy' , paperId , obj , (error , response) => { if ( error ){ Bert.alert(`Error : || ${error}` , danger ); } else{ Bert.alert(`Pdf copy deleted` , 'success'); } }) } } const UploadPdfCopy = ({loading , paper}) => (!loading ? ( <Row> <Col md={3} mdOffset={3}> {paper && paper.pdf ? ( <div><p> <a download className="downloadAnchor" href= { paper.pdf.paperUrl }> <img src="/image/pdf.jpg" className="img img-responsive" /> <br/> download pdf </a> <br/> <span><b>File Name :{SortReturnRecentOne( paper && paper.paperUploads).fileName}</b></span> <br/> <span> <Button onClick={()=>removePdfCopy(paper && paper._id , SortReturnRecentOne(paper && paper.paperUploads))} bsSize="xsmall" bsStyle="danger"> delete pdf </Button> </span> </p> </div> ) : <p> <a download className="downloadAnchor" href= {SortReturnRecentOne( paper && paper.paperUploads).paperUrl}> <img src="/image/word.png"/> <br/> download approved paper </a> <br/> <span><b>File Name :{SortReturnRecentOne( paper && paper.paperUploads).fileName}</b></span> </p> } </Col> <Col md={3}> {paper && paper.pdf ? ( <Alert bsStyle="success">Pdf copy available</Alert> ) : <Uploader paperId={paper && paper._id} slingshot='uploadPdfDocument' methodName='paper.uploadPdfCopy' uploadMessage="upload pdf copy of approved paper" /> } </Col> </Row> ) : <Loading /> ) export default UploadPdfCopy
features/apimgt/org.wso2.carbon.apimgt.store.feature/src/main/resources/store/source/src/app/components/Apis/Details/LifeCycle/TransitionStateButton.js
ChamNDeSilva/carbon-apimgt
import React from 'react' import {Radio} from 'antd' const Button = Radio.Button; const TransitionStateButton = (props) => { return ( <Button value={props.state.targetState}>{props.state.event}</Button> ); }; export default TransitionStateButton
packages/website/src/components/TypeDoc/ApiClass.js
mucsi96/w3c-webdriver
import React from 'react'; import ApiFunction from './ApiFunction'; import Heading from '../content/Heading'; import ApiDescription from './ApiDescription'; const ApiClass = ({ name, children, minLevel, comment }) => { const items = children.filter(item => item.kindString === 'Method' && item.flags.isPublic); items.sort((a, b) => { return a.sources[0].line - b.sources[0].line; }); return ( <> <Heading level={minLevel}>{name}</Heading> <ApiDescription {...comment} /> {items.map(method => { const signatures = method.signatures.map(signature => ({ ...signature, name: `${name.charAt(0).toLowerCase() + name.slice(1)}.${signature.name}` })); return <ApiFunction key={method.id} {...method} signatures={signatures} />; })} </> ); }; ApiClass.defaultProps = { minLevel: 2 }; export default ApiClass;
src/__tests__/For.js
damaera/react-conditioner
import React from 'react'; import { mount } from 'enzyme'; import { expect } from 'chai'; import For from '../For'; describe('<For />', () => { it('should render children with length 3', () => { const Children = <span>Hello</span> const items = [0,1,2] const wrapper = mount( <For of={items} each="$item" > {Children} </For> ); expect(wrapper.find('span').children()).to.have.length(items.length); }); });
source/components/_STATELESS.react.js
argaskins/ThinkReact-Jenkins
import React from 'react'; const <NAME> = (parameters) => ( <div>{parameters}</div> ); export default <NAME>;
examples/huge-apps/routes/Grades/components/Grades.js
moudy/react-router
import React from 'react'; class Grades extends React.Component { render () { return ( <div> <h2>Grades</h2> </div> ); } } export default Grades;
components/input/Input.js
KerenChandran/react-toolbox
import React from 'react'; import ClassNames from 'classnames'; import FontIcon from '../font_icon'; import style from './style'; class Input extends React.Component { static propTypes = { children: React.PropTypes.any, className: React.PropTypes.string, disabled: React.PropTypes.bool, error: React.PropTypes.string, floating: React.PropTypes.bool, hint: React.PropTypes.string, icon: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.element ]), label: React.PropTypes.string, maxLength: React.PropTypes.number, multiline: React.PropTypes.bool, onBlur: React.PropTypes.func, onChange: React.PropTypes.func, onFocus: React.PropTypes.func, onKeyPress: React.PropTypes.func, required: React.PropTypes.bool, type: React.PropTypes.string, value: React.PropTypes.any }; static defaultProps = { className: '', hint: '', disabled: false, floating: true, multiline: false, required: false, type: 'text' }; handleChange = (event) => { if (this.props.onChange) this.props.onChange(event.target.value, event); }; blur () { this.refs.input.blur(); } focus () { this.refs.input.focus(); } render () { const { children, disabled, error, floating, hint, icon, label: labelText, maxLength, multiline, required, type, value, ...others} = this.props; const length = maxLength && value ? value.length : 0; const labelClassName = ClassNames(style.label, {[style.fixed]: !floating}); const className = ClassNames(style.root, { [style.disabled]: disabled, [style.errored]: error, [style.hidden]: type === 'hidden', [style.withIcon]: icon }, this.props.className); const valuePresent = value !== null && value !== undefined && value !== '' && !Number.isNaN(value); const InputElement = React.createElement(multiline ? 'textarea' : 'input', { ...others, className: ClassNames(style.input, {[style.filled]: valuePresent}), onChange: this.handleChange, ref: 'input', role: 'input', disabled, required, type, value, maxLength }); return ( <div data-react-toolbox='input' className={className}> {InputElement} {icon ? <FontIcon className={style.icon} value={icon} /> : null} <span className={style.bar}></span> {labelText ? <label className={labelClassName}> {labelText} {required ? <span className={style.required}> * </span> : null} </label> : null} {hint ? <span className={style.hint}>{hint}</span> : null} {error ? <span className={style.error}>{error}</span> : null} {maxLength ? <span className={style.counter}>{length}/{maxLength}</span> : null} {children} </div> ); } } export default Input;
src/frame/rePCUI/tabs/base-tabs/InkTabBarMixin.js
gejialun8888/shop-react
import { setTransform, isTransformSupported } from './utils'; import React from 'react'; import classnames from 'classnames'; export function getScroll(w, top) { let ret = w[`page${top ? 'Y' : 'X'}Offset`]; const method = `scroll${top ? 'Top' : 'Left'}`; if (typeof ret !== 'number') { const d = w.document; // ie6,7,8 standard mode ret = d.documentElement[method]; if (typeof ret !== 'number') { // quirks mode ret = d.body[method]; } } return ret; } function offset(elem) { let box; let x; let y; const doc = elem.ownerDocument; const body = doc.body; const docElem = doc && doc.documentElement; box = elem.getBoundingClientRect(); x = box.left; y = box.top; x -= docElem.clientLeft || body.clientLeft || 0; y -= docElem.clientTop || body.clientTop || 0; const w = doc.defaultView || doc.parentWindow; x += getScroll(w); y += getScroll(w, true); return { left: x, top: y, }; } function componentDidUpdate(component, init) { const refs = component.refs; const { styles } = component.props; const wrapNode = refs.nav || refs.root; const containerOffset = offset(wrapNode); const inkBarNode = refs.inkBar; const activeTab = refs.activeTab; const inkBarNodeStyle = inkBarNode.style; const tabBarPosition = component.props.tabBarPosition; if (init) { // prevent mount animation inkBarNodeStyle.display = 'none'; } if (activeTab) { const tabNode = activeTab; const tabOffset = offset(tabNode); const transformSupported = isTransformSupported(inkBarNodeStyle); if (tabBarPosition === 'top' || tabBarPosition === 'bottom') { let left = tabOffset.left - containerOffset.left; let width = tabNode.offsetWidth; if (styles.inkBar && styles.inkBar.width !== undefined) { width = parseFloat(styles.inkBar.width, 10); if (width) { left = left + (tabNode.offsetWidth - width) / 2; } } // use 3d gpu to optimize render if (transformSupported) { setTransform(inkBarNodeStyle, `translate3d(${left}px,0,0)`); inkBarNodeStyle.width = `${width}px`; inkBarNodeStyle.height = ''; } else { inkBarNodeStyle.left = `${left}px`; inkBarNodeStyle.top = ''; inkBarNodeStyle.bottom = ''; inkBarNodeStyle.right = `${wrapNode.offsetWidth - left - width}px`; } } else { let top = tabOffset.top - containerOffset.top; let height = tabNode.offsetHeight; if (styles.inkBar && styles.inkBar.height !== undefined) { height = parseFloat(styles.inkBar.height, 10); if (height) { top = top + (tabNode.offsetHeight - height) / 2; } } if (transformSupported) { setTransform(inkBarNodeStyle, `translate3d(0,${top}px,0)`); inkBarNodeStyle.height = `${height}px`; inkBarNodeStyle.width = ''; } else { inkBarNodeStyle.left = ''; inkBarNodeStyle.right = ''; inkBarNodeStyle.top = `${top}px`; inkBarNodeStyle.bottom = `${wrapNode.offsetHeight - top - height}px`; } } } inkBarNodeStyle.display = activeTab ? 'block' : 'none'; } export default { getDefaultProps() { return { inkBarAnimated: true, }; }, componentDidUpdate() { componentDidUpdate(this); }, componentDidMount() { componentDidUpdate(this, true); }, getInkBarNode() { const { prefixCls, styles, inkBarAnimated } = this.props; const className = `${prefixCls}-ink-bar`; const classes = classnames({ [className]: true, [ inkBarAnimated ? `${className}-animated` : `${className}-no-animated` ]: true, }); return ( <div style={styles.inkBar} className={classes} key="inkBar" ref="inkBar" /> ); }, };
src/pages/tags.js
akilbekov/blog
import React from 'react'; import { Link } from 'gatsby'; import { Helmet } from 'react-helmet'; import kebabCase from 'lodash/kebabCase'; import Sidebar from '../components/Sidebar'; import { graphql } from 'gatsby'; class TagsRoute extends React.Component { render() { const { title } = this.props.data.site.siteMetadata; const tags = this.props.data.allMarkdownRemark.group; return ( <div> <Helmet title={`All Tags - ${title}`} /> <Sidebar {...this.props} /> <div className="content"> <div className="content__inner"> <div className="page"> <h1 className="page__title">Tags</h1> <div className="page__body"> <div className="tags"> <ul className="tags__list"> {tags.map((tag) => ( <li key={tag.fieldValue} className="tags__list-item"> <Link to={`/tags/${kebabCase(tag.fieldValue)}/`} className="tags__list-item-link" > {tag.fieldValue} ({tag.totalCount}) </Link> </li> ))} </ul> </div> </div> </div> </div> </div> </div> ); } } export default TagsRoute; export const pageQuery = graphql` query TagsQuery { site { siteMetadata { title subtitle copyright menu { label path } author { name email github rss so linkedin } } } allMarkdownRemark( limit: 2000 filter: { frontmatter: { layout: { eq: "post" }, draft: { ne: true } } } ) { group(field: frontmatter___tags) { fieldValue totalCount } } } `;
docs/src/app/components/pages/discover-more/Community.js
ngbrown/material-ui
import React from 'react'; import Title from 'react-title-component'; import MarkdownElement from '../../MarkdownElement'; import communityText from './community.md'; const Community = () => ( <div> <Title render={(previousTitle) => `Community - ${previousTitle}`} /> <MarkdownElement text={communityText} /> </div> ); export default Community;
app/javascript/mastodon/features/account_timeline/components/header.js
Craftodon/Craftodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import InnerHeader from '../../account/components/header'; import ActionBar from '../../account/components/action_bar'; import MissingIndicator from '../../../components/missing_indicator'; import ImmutablePureComponent from 'react-immutable-pure-component'; import MovedNote from './moved_note'; export default class Header extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map, onFollow: PropTypes.func.isRequired, onBlock: PropTypes.func.isRequired, onMention: PropTypes.func.isRequired, onReblogToggle: PropTypes.func.isRequired, onReport: PropTypes.func.isRequired, onMute: PropTypes.func.isRequired, onBlockDomain: PropTypes.func.isRequired, onUnblockDomain: PropTypes.func.isRequired, }; static contextTypes = { router: PropTypes.object, }; handleFollow = () => { this.props.onFollow(this.props.account); } handleBlock = () => { this.props.onBlock(this.props.account); } handleMention = () => { this.props.onMention(this.props.account, this.context.router.history); } handleReport = () => { this.props.onReport(this.props.account); } handleReblogToggle = () => { this.props.onReblogToggle(this.props.account); } handleMute = () => { this.props.onMute(this.props.account); } handleBlockDomain = () => { const domain = this.props.account.get('acct').split('@')[1]; if (!domain) return; this.props.onBlockDomain(domain, this.props.account.get('id')); } handleUnblockDomain = () => { const domain = this.props.account.get('acct').split('@')[1]; if (!domain) return; this.props.onUnblockDomain(domain, this.props.account.get('id')); } render () { const { account } = this.props; if (account === null) { return <MissingIndicator />; } return ( <div className='account-timeline__header'> {account.get('moved') && <MovedNote from={account} to={account.get('moved')} />} <InnerHeader account={account} onFollow={this.handleFollow} /> <ActionBar account={account} onBlock={this.handleBlock} onMention={this.handleMention} onReblogToggle={this.handleReblogToggle} onReport={this.handleReport} onMute={this.handleMute} onBlockDomain={this.handleBlockDomain} onUnblockDomain={this.handleUnblockDomain} /> </div> ); } }
src/icons/ColorLensIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class ColorLensIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M24 6C14.06 6 6 14.06 6 24s8.06 18 18 18c1.66 0 3-1.34 3-3 0-.78-.29-1.48-.78-2.01-.47-.53-.75-1.22-.75-1.99 0-1.66 1.34-3 3-3H32c5.52 0 10-4.48 10-10 0-8.84-8.06-16-18-16zM13 24c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm6-8c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm10 0c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm6 8c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z"/></svg>;} };
src/js/components/icons/base/Checkmark.js
linde12/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-checkmark`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'checkmark'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><polyline fill="none" stroke="#000" strokeWidth="2" points="2 14 9 20 22 4"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Checkmark'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/components/Tickets/AddProject.js
nadavspi/UnwiseConnect
import React, { Component } from 'react'; export default class AddProject extends Component { state = { projectId: '', }; submit = (e) => { e.preventDefault(); this.props.onAdd(this.state.projectId); } render() { return ( <form onSubmit={this.submit}> <div><label htmlFor="projectId">Project ID</label></div> <div className="input-group input-group-sm"> <input id="projectId" onChange={e => this.setState({ projectId: e.target.value })} type="number" value={this.state.projectId} className="form-control" placeholder="123" /> <div className="input-group-btn"> <button type="submit" className="btn btn-primary">Add</button> </div> </div> </form> ); } }
client/src/containers/NotFoundPage/index.js
steThera/react-mobx-koa
import React from 'react'; import ContentWrapper from 'components/ContentWrapper'; const NotFoundPage = () => ( <ContentWrapper> <section className="content"> Not found page </section> </ContentWrapper> ); export default NotFoundPage;