path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
docs/src/sections/GridStyleSection.js
yyssc/ssc-grid
import React from 'react'; import Anchor from '../Anchor'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function GridStyleSection() { return ( <div className="bs-docs-section"> <h3><Anchor id="grid-style">表格样式</Anchor></h3> <p>沿用bootstrap的样式,具体参照 <a href="http://getbootstrap.com/css/#tables-striped">Striped rows</a>等</p> <p>通过添加<code>bordered</code>为表格和其中的每个单元格增加边框。</p> <p>通过添加<code>striped</code>可以给表体之内的每一行增加斑马条纹样式。</p> <p>通过添加<code>condensed</code>可以让表格更加紧凑,单元格中的内补(padding)均会减半。</p> <p>通过添加<code>hover</code>可以让表体中的每一行对鼠标悬停状态作出响应</p> <ReactPlayground codeText={Samples.GridStyle} /> </div> ); }
assets/jqwidgets/jqwidgets-react/react_jqxdraw.js
juannelisalde/holter
/* jQWidgets v4.5.4 (2017-June) Copyright (c) 2011-2017 jQWidgets. License: http://jqwidgets.com/license/ */ import React from 'react'; const JQXLite = window.JQXLite; export default class JqxDraw extends React.Component { componentDidMount() { let options = this.manageAttributes(); this.createComponent(options); }; manageAttributes() { let properties = ['renderEngine']; let options = {}; for(let item in this.props) { if(item === 'settings') { for(let itemTwo in this.props[item]) { options[itemTwo] = this.props[item][itemTwo]; } } else { if(properties.indexOf(item) !== -1) { options[item] = this.props[item]; } } } return options; }; createComponent(options) { if(!this.style) { for (let style in this.props.style) { JQXLite(this.componentSelector).css(style, this.props.style[style]); } } if(this.props.className !== undefined) { let classes = this.props.className.split(' '); for (let i = 0; i < classes.length; i++ ) { JQXLite(this.componentSelector).addClass(classes[i]); } } if(!this.template) { JQXLite(this.componentSelector).html(this.props.template); } JQXLite(this.componentSelector).jqxDraw(options); }; setOptions(options) { JQXLite(this.componentSelector).jqxDraw('setOptions', options); }; getOptions() { if(arguments.length === 0) { throw Error('At least one argument expected in getOptions()!'); } let resultToReturn = {}; for(let i = 0; i < arguments.length; i++) { resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxDraw(arguments[i]); } return resultToReturn; }; on(name,callbackFn) { JQXLite(this.componentSelector).on(name,callbackFn); }; off(name) { JQXLite(this.componentSelector).off(name); }; renderEngine(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxDraw('renderEngine', arg) } else { return JQXLite(this.componentSelector).jqxDraw('renderEngine'); } }; attr(element, attributes) { JQXLite(this.componentSelector).jqxDraw('attr', element, attributes); }; circle(cx, cy, r, attributes) { return JQXLite(this.componentSelector).jqxDraw('circle', cx, cy, r, attributes); }; clear() { JQXLite(this.componentSelector).jqxDraw('clear'); }; getAttr(element, attributes) { return JQXLite(this.componentSelector).jqxDraw('getAttr', element, attributes); }; getSize() { return JQXLite(this.componentSelector).jqxDraw('getSize'); }; line(x1, y1, x2, y2, attributes) { return JQXLite(this.componentSelector).jqxDraw('line', x1, y1, x2, y2, attributes); }; measureText(text, angle, attributes) { return JQXLite(this.componentSelector).jqxDraw('measureText', text, angle, attributes); }; on(element, event, func) { JQXLite(this.componentSelector).jqxDraw('on', element, event, func); }; off(element, event, func) { JQXLite(this.componentSelector).jqxDraw('off', element, event, func); }; path(path, attributes) { return JQXLite(this.componentSelector).jqxDraw('path', path, attributes); }; pieslice(cx, xy, innerRadius, outerRadius, fromAngle, endAngle, centerOffset, attributes) { return JQXLite(this.componentSelector).jqxDraw('pieslice', cx, xy, innerRadius, outerRadius, fromAngle, endAngle, centerOffset, attributes); }; refresh() { JQXLite(this.componentSelector).jqxDraw('refresh'); }; rect(x, y, width, height, attributes) { return JQXLite(this.componentSelector).jqxDraw('rect', x, y, width, height, attributes); }; saveAsJPEG(image, url) { JQXLite(this.componentSelector).jqxDraw('saveAsJPEG', image, url); }; saveAsPNG(image, url) { JQXLite(this.componentSelector).jqxDraw('saveAsPNG', image, url); }; text(text, x, y, width, height, angle, attributes, clip, halign, valign, rotateAround) { return JQXLite(this.componentSelector).jqxDraw('text', text, x, y, width, height, angle, attributes, clip, halign, valign, rotateAround); }; render() { let id = 'jqxDraw' + JQXLite.generateID(); this.componentSelector = '#' + id; return ( <div id={id}>{this.props.value}{this.props.children}</div> ) }; };
app/javascript/mastodon/features/public_timeline/components/column_settings.js
MitarashiDango/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { injectIntl, FormattedMessage } from 'react-intl'; import SettingToggle from '../../notifications/components/setting_toggle'; export default @injectIntl class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, columnId: PropTypes.string, }; render () { const { settings, onChange } = this.props; return ( <div> <div className='column-settings__row'> <SettingToggle settings={settings} settingPath={['other', 'onlyMedia']} onChange={onChange} label={<FormattedMessage id='community.column_settings.media_only' defaultMessage='Media only' />} /> <SettingToggle settings={settings} settingPath={['other', 'onlyRemote']} onChange={onChange} label={<FormattedMessage id='community.column_settings.remote_only' defaultMessage='Remote only' />} /> </div> </div> ); } }
modules/Lifecycle.js
axross/react-router
import React from 'react' import invariant from 'invariant' const { object } = React.PropTypes /** * The Lifecycle mixin adds the routerWillLeave lifecycle method to a * component that may be used to cancel a transition or prompt the user * for confirmation. * * On standard transitions, routerWillLeave receives a single argument: the * location we're transitioning to. To cancel the transition, return false. * To prompt the user for confirmation, return a prompt message (string). * * During the beforeunload event (assuming you're using the useBeforeUnload * history enhancer), routerWillLeave does not receive a location object * because it isn't possible for us to know the location we're transitioning * to. In this case routerWillLeave must return a prompt message to prevent * the user from closing the window/tab. */ const Lifecycle = { contextTypes: { history: object.isRequired, // Nested children receive the route as context, either // set by the route component using the RouteContext mixin // or by some other ancestor. route: object }, propTypes: { // Route components receive the route object as a prop. route: object }, componentDidMount() { invariant( this.routerWillLeave, 'The Lifecycle mixin requires you to define a routerWillLeave method' ) const route = this.props.route || this.context.route invariant( route, 'The Lifecycle mixin must be used on either a) a <Route component> or ' + 'b) a descendant of a <Route component> that uses the RouteContext mixin' ) this._unlistenBeforeLeavingRoute = this.context.history.listenBeforeLeavingRoute( route, this.routerWillLeave ) }, componentWillUnmount() { if (this._unlistenBeforeLeavingRoute) this._unlistenBeforeLeavingRoute() } } export default Lifecycle
src/index.js
travi/admin.travi.org-components
import React from 'react'; import Helmet from 'react-helmet'; export default function Index() { return ( <div className="jumbotron"> <Helmet title="Home" /> <h2>Reference API Client</h2> <p>Administration for Travi.org</p> </div> ); } Index.displayName = 'Index';
src/svg-icons/action/compare-arrows.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionCompareArrows = (props) => ( <SvgIcon {...props}> <path d="M9.01 14H2v2h7.01v3L13 15l-3.99-4v3zm5.98-1v-3H22V8h-7.01V5L11 9l3.99 4z"/> </SvgIcon> ); ActionCompareArrows = pure(ActionCompareArrows); ActionCompareArrows.displayName = 'ActionCompareArrows'; export default ActionCompareArrows;
src/amo/routes.js
muffinresearch/addons-frontend
import React from 'react'; import { IndexRoute, Route } from 'react-router'; import HandleLogin from 'core/containers/HandleLogin'; import App from './containers/App'; import Home from './containers/Home'; import DetailPage from './containers/DetailPage'; import SearchPage from './containers/SearchPage'; export default ( <Route path="/:lang/:application" component={App}> <IndexRoute component={Home} /> <Route path="addon/:slug/" component={DetailPage} /> <Route path="fxa-authenticate" component={HandleLogin} /> <Route path="search/" component={SearchPage} /> </Route> );
src/main/react/src/routes/Home/HomeContainer.js
mbrossard/cryptonit-cloud
import React from 'react'; import PropTypes from 'prop-types'; class HomeContainer extends React.Component { static contextTypes = { router: PropTypes.object.isRequired }; componentDidMount() { this.context.router.push('/'); }; render() { return (<span></span>); }; } export default HomeContainer;
app/javascript/mastodon/components/avatar_overlay.js
rutan/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { autoPlayGif } from '../initial_state'; export default class AvatarOverlay extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, friend: ImmutablePropTypes.map.isRequired, animate: PropTypes.bool, }; static defaultProps = { animate: autoPlayGif, }; render() { const { account, friend, animate } = this.props; const baseStyle = { backgroundImage: `url(${account.get(animate ? 'avatar' : 'avatar_static')})`, }; const overlayStyle = { backgroundImage: `url(${friend.get(animate ? 'avatar' : 'avatar_static')})`, }; return ( <div className='account__avatar-overlay'> <div className='account__avatar-overlay-base' style={baseStyle} /> <div className='account__avatar-overlay-overlay' style={overlayStyle} /> </div> ); } }
src/primitives/other/collapsible-table/index.js
mpigsley/sectors-without-number
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { PlusCircle, Circle } from 'react-feather'; import Table from 'primitives/other/table'; import { without, includes } from 'constants/lodash'; import './style.scss'; export default class CollapsibleTable extends Component { constructor(props) { super(props); const { data, dataIdAccessor } = props; this.state = { openRows: data.map(row => row[dataIdAccessor]), }; } get filteredData() { const { data, dataIdAccessor } = this.props; const { openRows } = this.state; return data.reduce((allData, { children, ...parentRow }) => { const isRowOpen = includes(openRows, parentRow[dataIdAccessor]); const childRows = isRowOpen ? children.map(c => ({ ...c, collapsible: 'child', rowClass: 'CollapsibleTable-Child', })) : []; return [ ...allData, { collapsible: 'parent', ...parentRow }, ...childRows, ]; }, []); } get composedColumns() { const { columns, data, dataIdAccessor } = this.props; const { openRows } = this.state; const isHeaderOpen = openRows.length; const HeaderIcon = isHeaderOpen ? PlusCircle : Circle; return [ { accessor: 'collapsible', columnClass: classNames('CollapsibleTable-Icon', { 'CollapsibleTable-Icon--open': isHeaderOpen, 'CollapsibleTable-Icon--closed': !isHeaderOpen, }), onClick: rowId => { let newOpenRows = []; if (rowId && includes(openRows, rowId)) { newOpenRows = without(openRows, rowId); } else if (rowId) { newOpenRows = [...openRows, rowId]; } else if (!isHeaderOpen) { newOpenRows = data.map(row => row[dataIdAccessor]); } this.setState({ openRows: newOpenRows }); }, Header: () => <HeaderIcon size={16} />, Cell: (collapsible, row) => { if (collapsible === 'parent') { const isCellOpen = includes(openRows, row[dataIdAccessor]); const CellIcon = isCellOpen ? PlusCircle : Circle; return <CellIcon size={16} />; } return null; }, }, ...columns, ]; } render() { return ( <Table {...this.props} data={this.filteredData} columns={this.composedColumns} /> ); } } CollapsibleTable.propTypes = { dataIdAccessor: PropTypes.string.isRequired, data: PropTypes.arrayOf( PropTypes.shape({ children: PropTypes.arrayOf(PropTypes.shape()).isRequired, }), ).isRequired, columns: PropTypes.arrayOf(PropTypes.shape()).isRequired, };
src/Parser/Mage/Frost/CHANGELOG.js
enragednuke/WoWAnalyzer
import React from 'react'; import { Sharrq, sref } from 'MAINTAINERS'; import Wrapper from 'common/Wrapper'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; export default [ { date: new Date('2018-01-01'), changes: <Wrapper>Added a 'Fish for procs' entry to the Checklist, and reworded/updated several suggestion metrics.</Wrapper>, contributors: [sref], }, { date: new Date('2017-12-29'), changes: <Wrapper>Added support for <SpellLink id={SPELLS.FROST_MAGE_T21_4SET_BONUS_BUFF.id} /></Wrapper>, contributors: [sref], }, { date: new Date('2017-12-27'), changes: 'Converted Changelog to new format', contributors: [Sharrq], }, { date: new Date('2017-12-24'), changes: 'Added Checklist', contributors: [sref], }, { date: new Date('2017-12-01'), changes: <Wrapper>Added support for <SpellLink id={SPELLS.FROST_MAGE_T21_2SET_BONUS_BUFF.id} /></Wrapper>, contributors: [sref], }, { date: new Date('2017-11-04'), changes: 'Reworked and updated Glacial Spike module', contributors: [sref], }, { date: new Date('2017-11-04'), changes: 'Added support for T20 4pc Bonus', contributors: [sref], }, { date: new Date('2017-11-04'), changes: 'Added support for Ice Time and Lady Vashj\'s Grasp Legendaries', contributors: [sref], }, { date: new Date('2017-10-30'), changes: 'Added Cancelled Casts module', contributors: [Sharrq], }, { date: new Date('2017-10-29'), changes: 'Added Ice Lance Utilization module', contributors: [Sharrq], }, { date: new Date('2017-10-28'), changes: 'Enhanced display of Winter\'s Chill and Brain Freeze statistics', contributors: [sref], }, { date: new Date('2017-10-28'), changes: 'Added Splitting Ice module', contributors: [sref], }, { date: new Date('2017-10-17'), changes: 'Added Frost Bomb, Unstable Magic, and Arctic Gale modules', contributors: [sref], }, { date: new Date('2017-10-17'), changes: 'Added Rune of Power and Mirror Image modules', contributors: [sref], }, { date: new Date('2017-10-16'), changes: 'Added Cooldown Reduction Tracking for Frozen Orb and Icy Veins', contributors: [Sharrq], }, { date: new Date('2017-10-15'), changes: 'Added Support for Zann\'esu Journey, Magtheridon\'s Banished Bracers, and Shattered Fragments of Sindragosa', contributors: [Sharrq], }, { date: new Date('2017-10-08'), changes: 'Added spec', contributors: [Sharrq], }, ];
components/Carousel/Carousel.story.js
rdjpalmer/bloom
import PropTypes from 'prop-types'; import React from 'react'; import { storiesOf, action } from '@storybook/react'; import PictureCard from '../Cards/PictureCard/PictureCard'; import Carousel from './Carousel'; import ControlledCarousel from './ControlledCarousel'; const StorySlide = ({ number }) => ( <div key={ `slide-${number}` } style={ { paddingLeft: '2%', paddingRight: '2%' } }> <PictureCard src={ `http://placekitten.com/g/287/4${(number * 2) + 10}` } style={ { height: '300px', verticalAlign: 'middle', textAlign: 'center', fontSize: '5rem', } } center href="#" > { number } </PictureCard> </div> ); StorySlide.propTypes = { number: PropTypes.number }; const slides = [...Array(10).keys()].map(i => <StorySlide number={ i } key={ i } />); storiesOf('Carousel', module) .add('Default', () => ( <Carousel onChange={ action('Slide changed') }> { slides } </Carousel> )); storiesOf('Controlled Carousel', module) .add('Default', () => ( <ControlledCarousel> { slides } </ControlledCarousel> )) .add('Muliple in view 💯', () => ( <ControlledCarousel slidesToShow={ 3 }> { slides } </ControlledCarousel> )) .add('Infinite ∞', () => ( <ControlledCarousel wrapAround> { slides } </ControlledCarousel> )) .add('Peaking 🐦', () => ( <ControlledCarousel peaking> { slides } </ControlledCarousel> )) .add('🐦 + ∞ + 💯', () => ( <ControlledCarousel peaking wrapAround slidesToShow={ 3 }> { slides } </ControlledCarousel> ));
src/Parser/Hunter/Survival/Modules/Features/AlwaysBeCasting.js
hasseboulen/WoWAnalyzer
import React from 'react'; import CoreAlwaysBeCasting from 'Parser/Core/Modules/AlwaysBeCasting'; import Combatants from 'Parser/Core/Modules/Combatants'; import SPELLS from 'common/SPELLS/index'; import { formatPercentage } from 'common/format'; import { STATISTIC_ORDER } from 'Main/StatisticBox'; import SpellLink from 'common/SpellLink'; import Wrapper from 'common/Wrapper'; class AlwaysBeCasting extends CoreAlwaysBeCasting { static dependencies = { ...CoreAlwaysBeCasting.dependencies, combatants: Combatants, }; get suggestionThresholds() { return { actual: this.downtimePercentage, isGreaterThan: { minor: 0.1, average: 0.15, major: 0.20, }, style: 'percentage', }; } statisticOrder = STATISTIC_ORDER.CORE(1); suggestions(when) { when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => { return suggest( <Wrapper>Your downtime can be improved. Try to reduce the delay between casting spells. If everything is on cooldown, try and use <SpellLink id={SPELLS.RAPTOR_STRIKE.id} icon /> or <SpellLink id={SPELLS.LACERATE.id} icon /> to stay off the focus cap and do some damage. </Wrapper>) .icon('spell_mage_altertime') .actual(`${formatPercentage(actual)}% downtime`) .recommended(`<${formatPercentage(recommended)}% is recommended`); }); } } export default AlwaysBeCasting;
fusion/CardGrid.js
pagesource/fusion
import React from 'react'; import { css } from 'emotion'; import PropTypes from 'prop-types'; import { withTheme } from 'theming'; import Card from './Card'; const cardGrid = css` display: flex; flex-direction: row; width: 100%; `; const cardData = [ { index: '1', title: 'Tasty Food', description: ' lorem lipsum do re me', rating: 4, image: 'http://lorempixel.com/250/150/food/', }, { index: '2', title: 'Amazing Food', description: ' Amazing lorem lipsum do re me', rating: 5, image: 'http://lorempixel.com/250/150/food/', }, { index: '3', title: 'Good Food', description: ' Good lipsum do re me', rating: 3, image: 'http://lorempixel.com/250/150/food/', }, ]; const CardGrid = () => ( <div className={cardGrid}> <Card cardData={cardData} /> </div> ); Card.propTypes = { /** * Card Data */ cardData: PropTypes.arrayOf(PropTypes.shape({})), }; export default withTheme(CardGrid);
docs/src/app/components/pages/components/Slider/ExampleDisabled.js
ngbrown/material-ui
import React from 'react'; import Slider from 'material-ui/Slider'; const SliderExampleDisabled = () => ( <div> <Slider disabled={true} /> <Slider disabled={true} value={0.5} /> <Slider disabled={true} value={1} /> </div> ); export default SliderExampleDisabled;
spec/javascripts/jsx/gradebook/default_gradebook/components/GradeInput/PointsSpec.js
djbender/canvas-lms
/* * Copyright (C) 2019 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import {render} from '@testing-library/react' import GradeInput from 'jsx/gradebook/default_gradebook/components/GradeInput' import GradeInputDriver from './GradeInputDriver' QUnit.module('Gradebook > Default Gradebook > Components > GradeInput', suiteHooks => { let $container let component let gradeInput let props suiteHooks.beforeEach(() => { const assignment = { anonymizeStudents: false, gradingType: 'points', pointsPossible: 10 } const submission = { enteredGrade: '7.8', enteredScore: 7.8, excused: false, id: '2501' } const gradingScheme = [ ['A', 0.9], ['B', 0.8], ['C', 0.7], ['D', 0.6], ['F', 0] ] props = { assignment, disabled: false, enterGradesAs: 'points', gradingScheme, onSubmissionUpdate: sinon.stub(), pendingGradeInfo: null, submission } $container = document.body.appendChild(document.createElement('div')) component = null gradeInput = null }) suiteHooks.afterEach(() => { component.unmount() $container.remove() }) function renderComponent() { if (component == null) { component = render(<GradeInput {...props} />, {container: $container}) gradeInput = GradeInputDriver.find($container) } else { component.rerender(<GradeInput {...props} />) } } QUnit.module('when entering grades as points', () => { test('displays a label of "Grade out of <points possible>"', () => { renderComponent() equal(gradeInput.labelText, 'Grade out of 10') }) test('sets the formatted entered score of the submission as the input value', () => { renderComponent() strictEqual(gradeInput.value, '7.8') }) test('rounds the formatted entered score to two decimal places', () => { props.submission.enteredScore = 7.816 renderComponent() strictEqual(gradeInput.value, '7.82') }) test('strips insignificant zeros', () => { props.submission.enteredScore = 8.0 renderComponent() strictEqual(gradeInput.value, '8') }) test('is blank when the submission is not graded', () => { props.submission.enteredGrade = null props.submission.enteredScore = null renderComponent() strictEqual(gradeInput.value, '') }) QUnit.module('when the submission is excused', () => { test('sets the input value to "Excused"', () => { props.submission.excused = true renderComponent() deepEqual(gradeInput.value, 'Excused') }) test('disables the input', () => { props.submission.excused = true renderComponent() strictEqual(gradeInput.inputIsDisabled, true) }) }) test('is blank when the assignment has anonymized students', () => { props.assignment.anonymizeStudents = true renderComponent() strictEqual(gradeInput.value, '') }) test('disables the input when disabled is true', () => { props.disabled = true renderComponent() strictEqual(gradeInput.inputIsDisabled, true) }) QUnit.module('when the input receives a new value', hooks => { hooks.beforeEach(() => { renderComponent() gradeInput.inputValue('9.8') }) test('updates the input to the given value', () => { strictEqual(gradeInput.value, '9.8') }) test('does not call the onSubmissionUpdate prop', () => { strictEqual(props.onSubmissionUpdate.callCount, 0) }) }) QUnit.module('when the input blurs after receiving a new value', () => { test('calls the onSubmissionUpdate prop', () => { renderComponent() gradeInput.inputValue('9.8') gradeInput.blurInput() strictEqual(props.onSubmissionUpdate.callCount, 1) }) test('calls the onSubmissionUpdate prop with the submission', () => { renderComponent() gradeInput.inputValue('9.8') gradeInput.blurInput() const [updatedSubmission] = props.onSubmissionUpdate.lastCall.args strictEqual(updatedSubmission, props.submission) }) test('calls the onSubmissionUpdate prop with the current grade info', () => { renderComponent() gradeInput.inputValue('9.8') gradeInput.blurInput() const [, gradeInfo] = props.onSubmissionUpdate.lastCall.args strictEqual(gradeInfo.score, 9.8) }) QUnit.module('when a point value is entered', contextHooks => { let gradeInfo contextHooks.beforeEach(() => { renderComponent() gradeInput.inputValue('8.9') gradeInput.blurInput() gradeInfo = props.onSubmissionUpdate.lastCall.args[1] }) test('calls the onSubmissionUpdate prop with the entered grade', () => { strictEqual(gradeInfo.grade, '8.9') }) test('calls the onSubmissionUpdate prop with the score form of the entered grade', () => { strictEqual(gradeInfo.score, 8.9) }) test('calls the onSubmissionUpdate prop with the enteredAs set to "points"', () => { strictEqual(gradeInfo.enteredAs, 'points') }) }) QUnit.module('when a percent value is entered', contextHooks => { let gradeInfo contextHooks.beforeEach(() => { renderComponent() gradeInput.inputValue('89%') gradeInput.blurInput() gradeInfo = props.onSubmissionUpdate.lastCall.args[1] }) test('calls the onSubmissionUpdate prop with the points form of the entered grade', () => { strictEqual(gradeInfo.grade, '8.9') }) test('calls the onSubmissionUpdate prop with the score form of the entered grade', () => { strictEqual(gradeInfo.score, 8.9) }) test('calls the onSubmissionUpdate prop with the enteredAs set to "percent"', () => { strictEqual(gradeInfo.enteredAs, 'percent') }) }) QUnit.module('when a grading scheme value is entered', contextHooks => { let gradeInfo contextHooks.beforeEach(() => { renderComponent() gradeInput.inputValue('B') gradeInput.blurInput() gradeInfo = props.onSubmissionUpdate.lastCall.args[1] }) test('calls the onSubmissionUpdate prop with the points form of the entered grade', () => { strictEqual(gradeInfo.grade, '8.9') }) test('calls the onSubmissionUpdate prop with the score form of the entered grade', () => { strictEqual(gradeInfo.score, 8.9) }) test('calls the onSubmissionUpdate prop with the enteredAs set to "gradingScheme"', () => { strictEqual(gradeInfo.enteredAs, 'gradingScheme') }) }) QUnit.module('when an invalid grade value is entered', contextHooks => { let gradeInfo contextHooks.beforeEach(() => { renderComponent() gradeInput.inputValue('unknown') gradeInput.blurInput() gradeInfo = props.onSubmissionUpdate.lastCall.args[1] }) test('calls the onSubmissionUpdate prop with the points form set to the given value', () => { strictEqual(gradeInfo.grade, 'unknown') }) test('calls the onSubmissionUpdate prop with a null score form', () => { strictEqual(gradeInfo.score, null) }) test('calls the onSubmissionUpdate prop with enteredAs set to null', () => { strictEqual(gradeInfo.enteredAs, null) }) test('calls the onSubmissionUpdate prop with valid set to false', () => { strictEqual(gradeInfo.valid, false) }) }) }) QUnit.module('when the input blurs without having received a new value', hooks => { hooks.beforeEach(() => { renderComponent() gradeInput.inputValue('9.8') // change the input value gradeInput.inputValue('7.8') // revert to the initial value gradeInput.blurInput() }) test('does not call the onSubmissionUpdate prop', () => { strictEqual(props.onSubmissionUpdate.callCount, 0) }) }) QUnit.module('when the submission grade is updating', hooks => { hooks.beforeEach(() => { props.submission = {...props.submission, enteredGrade: null, enteredScore: null} props.submissionUpdating = true props.pendingGradeInfo = {grade: '9.8', valid: true, excused: false} }) test('updates the text input with the value of the pending grade', () => { renderComponent() strictEqual(gradeInput.value, '9.8') }) test('sets the text input to "Excused" when the submission is being excused', () => { props.pendingGradeInfo = {grade: null, valid: false, excused: true} renderComponent() equal(gradeInput.value, 'Excused') }) test('sets the input to "read only"', () => { renderComponent() strictEqual(gradeInput.isReadOnly, true) }) QUnit.module('when the submission grade finishes updating', moreHooks => { moreHooks.beforeEach(() => { renderComponent() props.submission = {...props.submission, enteredGrade: '9.8'} props.submissionUpdating = false renderComponent() }) test('updates the input value with the updated grade', () => { strictEqual(gradeInput.value, '9.8') }) test('enables the input', () => { strictEqual(gradeInput.isReadOnly, false) }) }) }) QUnit.module('when the submission is otherwise being updated', () => { test('does not update the input value when the submission begins updating', () => { renderComponent() props.submission = {...props.submission, enteredGrade: '9.8'} props.submissionUpdating = true renderComponent() strictEqual(gradeInput.value, '7.8') }) test('updates the input value when the submission finishes updating', () => { props.submissionUpdating = true renderComponent() props.submission = {...props.submission, enteredGrade: '9.8', enteredScore: 9.8} props.submissionUpdating = false renderComponent() strictEqual(gradeInput.value, '9.8') }) }) }) })
pages/col.js
jonheslop/colwiki
import React from 'react' import App from '../components/app' import Header from '../components/header' import PostSingle from '../components/post-single' import withData from '../lib/with-data' export default withData(props => ( <App> <Header pathname={props.url.pathname} query={props.url.query}/> <main role="main" className="ml7-ns dark-gray"> <PostSingle slug={props.url.query.id}/> </main> </App> ))
app/javascript/mastodon/features/ui/components/confirmation_modal.js
kibousoft/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl, FormattedMessage } from 'react-intl'; import Button from '../../../components/button'; @injectIntl export default class ConfirmationModal extends React.PureComponent { static propTypes = { message: PropTypes.node.isRequired, confirm: PropTypes.string.isRequired, onClose: PropTypes.func.isRequired, onConfirm: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; componentDidMount() { this.button.focus(); } handleClick = () => { this.props.onClose(); this.props.onConfirm(); } handleCancel = () => { this.props.onClose(); } setRef = (c) => { this.button = c; } render () { const { message, confirm } = this.props; return ( <div className='modal-root__modal confirmation-modal'> <div className='confirmation-modal__container'> {message} </div> <div className='confirmation-modal__action-bar'> <Button onClick={this.handleCancel} className='confirmation-modal__cancel-button'> <FormattedMessage id='confirmation_modal.cancel' defaultMessage='Cancel' /> </Button> <Button text={confirm} onClick={this.handleClick} ref={this.setRef} /> </div> </div> ); } }
app/javascript/mastodon/features/follow_requests/index.js
tootsuite/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { debounce } from 'lodash'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import AccountAuthorizeContainer from './containers/account_authorize_container'; import { fetchFollowRequests, expandFollowRequests } from '../../actions/accounts'; import ScrollableList from '../../components/scrollable_list'; import { me } from '../../initial_state'; const messages = defineMessages({ heading: { id: 'column.follow_requests', defaultMessage: 'Follow requests' }, }); const mapStateToProps = state => ({ accountIds: state.getIn(['user_lists', 'follow_requests', 'items']), isLoading: state.getIn(['user_lists', 'follow_requests', 'isLoading'], true), hasMore: !!state.getIn(['user_lists', 'follow_requests', 'next']), locked: !!state.getIn(['accounts', me, 'locked']), domain: state.getIn(['meta', 'domain']), }); export default @connect(mapStateToProps) @injectIntl class FollowRequests extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, hasMore: PropTypes.bool, isLoading: PropTypes.bool, accountIds: ImmutablePropTypes.list, locked: PropTypes.bool, domain: PropTypes.string, intl: PropTypes.object.isRequired, multiColumn: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchFollowRequests()); } handleLoadMore = debounce(() => { this.props.dispatch(expandFollowRequests()); }, 300, { leading: true }); render () { const { intl, accountIds, hasMore, multiColumn, locked, domain, isLoading } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = <FormattedMessage id='empty_column.follow_requests' defaultMessage="You don't have any follow requests yet. When you receive one, it will show up here." />; const unlockedPrependMessage = locked ? null : ( <div className='follow_requests-unlocked_explanation'> <FormattedMessage id='follow_requests.unlocked_explanation' defaultMessage='Even though your account is not locked, the {domain} staff thought you might want to review follow requests from these accounts manually.' values={{ domain: domain }} /> </div> ); return ( <Column bindToDocument={!multiColumn} icon='user-plus' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <ScrollableList scrollKey='follow_requests' onLoadMore={this.handleLoadMore} hasMore={hasMore} isLoading={isLoading} emptyMessage={emptyMessage} bindToDocument={!multiColumn} prepend={unlockedPrependMessage} > {accountIds.map(id => <AccountAuthorizeContainer key={id} id={id} />, )} </ScrollableList> </Column> ); } }
src/components/saundra.js
dempah14/gitDemostration
import React, { Component } from 'react'; export default class Saundra extends Component { render() { return ( <div>Saundra</div> ); } }
src/index.js
laniywh/game-of-life
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import App from './components/app'; import reducers from './reducers'; require("./style/style.scss"); const store = createStore(reducers, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); render( <Provider store={store}> <App /> </Provider> , document.querySelector('.container'));
imports/client/ui/pages/Admin/AdminTable/Users.js
mordka/fl-events
import React from 'react'; import CancelDeleteBtns from './../CancelDeleteBtns/CancelDeleteBtns' import { parseData} from './helper' const Users = ({ user, deleteUser }) => { const userName = parseData('user', user ); let button = <CancelDeleteBtns idToDelete={user._id} deleteDocument={deleteUser} deleteText={'del'} />; return ( <React.Fragment> {button}{userName} </React.Fragment> ) } export default Users;
node_modules/react-bootstrap/es/InputGroupAddon.js
mohammed52/door-quote-automator
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var InputGroupAddon = function (_React$Component) { _inherits(InputGroupAddon, _React$Component); function InputGroupAddon() { _classCallCheck(this, InputGroupAddon); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } InputGroupAddon.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('span', _extends({}, elementProps, { className: classNames(className, classes) })); }; return InputGroupAddon; }(React.Component); export default bsClass('input-group-addon', InputGroupAddon);
src/Interpolate.js
dongtong/react-bootstrap
// https://www.npmjs.org/package/react-interpolate-component // TODO: Drop this in favor of es6 string interpolation import React from 'react'; import ValidComponentChildren from './utils/ValidComponentChildren'; const REGEXP = /\%\((.+?)\)s/; const Interpolate = React.createClass({ displayName: 'Interpolate', propTypes: { component: React.PropTypes.node, format: React.PropTypes.string, unsafe: React.PropTypes.bool }, getDefaultProps() { return { component: 'span', unsafe: false }; }, render() { let format = (ValidComponentChildren.hasValidComponent(this.props.children) || (typeof this.props.children === 'string')) ? this.props.children : this.props.format; let parent = this.props.component; let unsafe = this.props.unsafe === true; let props = {...this.props}; delete props.children; delete props.format; delete props.component; delete props.unsafe; if (unsafe) { let content = format.split(REGEXP).reduce((memo, match, index) => { let html; if (index % 2 === 0) { html = match; } else { html = props[match]; delete props[match]; } if (React.isValidElement(html)) { throw new Error('cannot interpolate a React component into unsafe text'); } memo += html; return memo; }, ''); props.dangerouslySetInnerHTML = { __html: content }; return React.createElement(parent, props); } let kids = format.split(REGEXP).reduce((memo, match, index) => { let child; if (index % 2 === 0) { if (match.length === 0) { return memo; } child = match; } else { child = props[match]; delete props[match]; } memo.push(child); return memo; }, []); return React.createElement(parent, props, kids); } }); export default Interpolate;
sites/all/themes/osbee/grunt/node_modules/grunt-browser-sync/node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
benjaminbwright/osbee-staging
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
docs/src/examples/modules/Tab/Types/TabExampleBasicAll.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Tab } from 'semantic-ui-react' const panes = [ { menuItem: 'Tab 1', pane: 'Tab 1 Content' }, { menuItem: 'Tab 2', pane: 'Tab 2 Content' }, { menuItem: 'Tab 3', pane: 'Tab 3 Content' }, ] const TabExampleBasicAll = () => <Tab panes={panes} renderActiveOnly={false} /> export default TabExampleBasicAll
src/pages/resume/languages/index.en.js
angeloocana/angeloocana
import React from 'react'; import LanguagesPage from '../../../components/Resume/LanguagesPage'; import graphql from 'graphql'; export default (props) => <LanguagesPage {...props} />; export const pageQuery = graphql` query ResumeLanguagesEn { site { siteMetadata { resume { menu { label link } languages{ name { en } level key } } } } } `;
src/containers/board/PostReply.js
jvallexm/message-board
import React from 'react'; export default class PostReply extends React.Component{ constructor(props) { super(props); this.state = { reply: { text: "", posted_on: 0, delete_password: "", replies: [], flagged: false }, message: "" }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(e) { let reply = this.state.reply; if(e.target.name == "text" && e.target.value.length > 500) { this.setState({message: "Sorry, posts can't be longer than 500 characters"}); return false; } if(e.target.name == "delete_password" && e.target.value.length > 20) { this.setState({message: "Sorry, detele keys can't be longer than 20 characters"}); return false; } reply[e.target.name] = e.target.value; reply.posted_on = Math.round((new Date()).getTime() / 1000); reply._id = Math.round((new Date()).getTime() / 1000); this.setState({thread: reply, message: ""}); } handleSubmit() { let reply = this.state.reply; if(reply.text.length < 5) { this.setState({message: "Posts must be at least 5 characters long"}); return false; } if(reply.delete_password.length < 5) { this.setState({message: "Delete keys must be at least 5 characters long"}); return false; } reply.posted_on = Math.round((new Date()).getTime() / 1000); reply._id = Math.round((new Date()).getTime() / 1000); this.props.pushReply(this.props.replyingTo,this.props.root,reply); this.props.replyToggle(); } render() { return( <div className="text-center container-fluid"> <div className="red error">{this.state.message}</div> <div className="row"> <div className="col-md-2 col-left lil middle-text"> Reply </div> <div className="col-md-10 col-right"> <textarea className="width-100 smol lefty" onChange={this.handleChange} name={"text"} value={this.state.reply.text}/> </div> <div className="col-md-2 col-left lil middle-text"> Delete Key </div> <div className="col-md-6 col-right col-left"> <input className="width-100 smol lefty" onChange={this.handleChange} name={"delete_password"} value={this.state.reply.delete_password}/> </div> <div className="col-md-2 col-left col-right post"> <button className="btn btn-smol smol width-100" onClick={this.handleSubmit}> Post </button> </div> <div className="col-md-2 col-right post "> <button className="btn btn-smol smol width-100 cancel" onClick={this.props.replyToggle}> Cancel </button> </div> </div> </div> ); } }
fixtures/dom/src/components/fixtures/input-change-events/RadioClickFixture.js
jquense/react
import React from 'react'; import Fixture from '../../Fixture'; class RadioClickFixture extends React.Component { constructor(props, context) { super(props, context); this.state = { changeCount: 0, }; } handleChange = () => { this.setState(({changeCount}) => { return { changeCount: changeCount + 1, }; }); }; handleReset = () => { this.setState({ changeCount: 0, }); }; render() { const {changeCount} = this.state; const color = changeCount === 0 ? 'green' : 'red'; return ( <Fixture> <label> <input defaultChecked type="radio" onChange={this.handleChange} /> Test case radio input </label> {' '} <p style={{color}}> <code>onChange</code>{' calls: '}<strong>{changeCount}</strong> </p> <button onClick={this.handleReset}>Reset count</button> </Fixture> ); } } export default RadioClickFixture;
src/components/buttons/demos/FabDisabled.js
isogon/styled-mdl
import React from 'react' import { Button, Icon } from '../../../' export default () => ( <Button fab disabled> <Icon name="add" /> </Button> )
jenkins-design-language/src/js/components/material-ui/svg-icons/action/assignment-return.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionAssignmentReturn = (props) => ( <SvgIcon {...props}> <path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm4 12h-4v3l-5-5 5-5v3h4v4z"/> </SvgIcon> ); ActionAssignmentReturn.displayName = 'ActionAssignmentReturn'; ActionAssignmentReturn.muiName = 'SvgIcon'; export default ActionAssignmentReturn;
app/containers/RefundCalculator/index.js
Jasonlucas724/Digimortal
/* * * RefundCalculator * */ import React from 'react'; import Helmet from 'react-helmet'; import Responsive from 'react-responsive'; import {Link} from 'react-router'; import Menu from 'material-ui/svg-icons/navigation/Menu'; import TextField from 'material-ui/TextField'; import Person from 'material-ui/svg-icons/social/person'; import Description from 'material-ui/svg-icons/action/description'; import AccountBalance from 'material-ui/svg-icons/action/account-balance'; import ContentCopy from 'material-ui/svg-icons/content/content-copy'; import Assignment from 'material-ui/svg-icons/action/assignment'; import AttachMoney from 'material-ui/svg-icons/editor/attach-money'; import CheckCircle from 'material-ui/svg-icons/action/check-circle'; import Button from 'react-bootstrap/lib/Button'; import Toggle from 'material-ui/Toggle'; export default class RefundCalculator extends React.PureComponent { constructor(props) { super(props); this.state = { hover:0 } } handleHover = (id) => { this.setState({ hover:id }) } renderBoxes = () => { const iconOne={ width:"50px", height:"50px", background:"transparent", } const textFieldOne={ fontSize:"15px", color:"grey", fontFamily:"Roboto, sans serif", } const iconTwo={ width:"50px", height:"50px", background:"transparent", } const textFieldTwo={ fontSize:"15px", color:"grey", fontFamily:"Roboto, sans serif", } const iconThree={ width:"50px", height:"50px", background:"transparent", } const textFieldThree={ fontSize:"15px", color:"grey", fontFamily:"Roboto, sans serif", } const iconFour={ width:"50px", height:"50px", background:"transparent", } const textFieldFour={ fontSize:"15px", color:"grey", fontFamily:"Roboto, sans serif", } const iconFive={ width:"50px", height:"50px", background:"transparent", } const textFieldFive={ fontSize:"15px", color:"grey", fontFamily:"Roboto, sans serif", } const iconSix={ width:"50px", height:"50px", background:"transparent", } const textFieldSix={ fontSize:"15px", color:"grey", fontFamily:"Roboto, sans serif", } const iconSeven={ width:"50px", height:"50px", background:"transparent", } const textFieldSeven={ fontSize:"15px", color:"grey", fontFamily:"Roboto, sans serif", } const container={ display:"flex", width:"100%", maxWidth:"1000px", flexDirection:"row", justifyContent:"space-around" } const refundBox={ display:"flex", flexDirection:"column", justifyContent:"center", alignItems:"center", border:"2px solid grey", width:"100px", height:"100px", } const hoverStyle={ display:"flex", flexDirection:"column", justifyContent:"center", alignItems:"center", border:"2px solid grey", width:"100px", height:"100px", background:"#1F5899" } var refundBoxOne =refundBox; var refundBoxTwo =refundBox; var refundBoxThree =refundBox; var refundBoxFour =refundBox; var refundBoxFive =refundBox; var refundBoxSix =refundBox; var refundBoxSeven =refundBox; if(this.state.hover==1){refundBoxOne=hoverStyle;} if(this.state.hover==2){refundBoxTwo=hoverStyle;} if(this.state.hover==3){refundBoxThree=hoverStyle;} if(this.state.hover==4){refundBoxFour=hoverStyle;} if(this.state.hover==5){refundBoxFive=hoverStyle;} if(this.state.hover==6){refundBoxSix=hoverStyle;} if(this.state.hover==7){refundBoxSeven=hoverStyle;} return ( <div style={container}> <div style={refundBoxOne} onMouseEnter={() => this.handleHover(1)} onMouseLeave={() => this.handleHover(0)}> <Description style={iconOne}/> <p style={textFieldOne}>Basic Info</p> </div> <div style={refundBoxTwo} onMouseEnter={() => this.handleHover(2)}onMouseLeave={() => this.handleHover(0)}> <Person style={iconTwo}/> <p style={textFieldTwo}>Family</p> </div> <div style={refundBoxThree} onMouseEnter={() => this.handleHover(3)}onMouseLeave={() => this.handleHover(0)}> <AccountBalance style={iconThree}/> <p style={textFieldThree}>income</p> </div> <div style={refundBoxFour} onMouseEnter={() => this.handleHover(4)}onMouseLeave={() => this.handleHover(0)}> <ContentCopy style={iconFour}/> <p style={textFieldFour}>Deductions</p> </div> <div style={refundBoxFive} onMouseEnter={() => this.handleHover(5)}onMouseLeave={() => this.handleHover(0)}> <Assignment style={iconFive}/> <p style={textFieldFive}>Credits</p> </div> <div style={refundBoxSix} onMouseEnter={() => this.handleHover(6)}onMouseLeave={() => this.handleHover(0)}> <AttachMoney style={iconSix}/> <p style={textFieldSix}>Results</p> </div> <div style={refundBoxSeven} onMouseEnter={() => this.handleHover(7)}onMouseLeave={() => this.handleHover(0)}> <CheckCircle style={iconSeven}/> <p style={textFieldSeven}>Start</p> </div> <footer> </footer> </div> ) } render() { const navBar={ display:"flex", flexDirection:"row", width:"100%", justifyContent:"space-between", position:"fixed", top:"0", background:"white" } const logoStyle={ width:"350px", height:"100px", marginTop:"10px", background:"url(http://easiertaxes.com/wp-content/uploads/2013/07/taxslayer-logo-large.png)", backgroundSize:"cover", } const navLink={ textDecoration:"0", display:"flex", flexDirection:"column", padding:"15px", alignSelf:"center", color:"#000000", fontSize:"18px", fontFamily:"Roboto, sans serif" } const banner={ display:"flex", flexDirection:"row", width:"100%", height:"50px", background:"#d22938" } const videoContainer={ display:"flex", flexDirection:"column", width:"300px", height:"300px", background:"url(http://www.techlicious.com/images/computers/woman-laptop-cash-shutterstock-510px.jpg)", justifyContent:"center", margin:"20px", backgroundSize:"cover", } const main1={ display:"flex", fontSize:"30px", color:"black", flexDirection:"column", alignItems:"center" } const sectionHeader={ display:"flex", flexDirection:"row", justifyContent:"space-between", marginTop:"300px", } const textContainer={ display:"flex", flexDirection:"column", width:"480px", fontFamily:"Roboto, sans serif", margin:"20px" } const box3={ display:"flex", fontSize:"30px", color:"black", textAlign:"justify" } const TextField={ display:"flex", flexDirection:"column", justifyContent:"center", fontFamily:"Roboto, sans serif", color:"red" } const moneyIcon={ fontSize:"50px", color:"green", marginLeft:"145px" } const bannerStyle={ display:"flex", flexDirection:"row", marginTop:"50px" } const banner2={ width:"1000px", height:"500px", background:"url(https://cdn-az.taxslayer.com/content/images/refund_calc_image.jpg)", backgroundSize:"cover", flexStretch:"100px" } const toggleContainer={ display:"flex", flexDirection:"row", justifyContent:"space-between", width:"925px", } const toggleOne={ width:"120px", } return ( <div> <Helmet title="RefundCalculator" meta={[ { name: 'description', content: 'Description of RefundCalculator' }]}/> <div> <Helmet title="Support" meta={[ { name: 'description', content: 'Description of Support' }]}/> <div> <Responsive minDeviceWidth={1024}> <header> <div> <nav style={navBar}> <p style={logoStyle}></p> <Link to="/Products" style={navLink}>Products</Link> <Link to="/RefundCalculator" style={navLink}>Refund Calculator</Link> <Link to="/About" style={navLink}>About</Link> <Link to="/Support" style={navLink}>Support</Link> <Menu/> </nav> </div> </header> <main style={main1}> <div style={sectionHeader}> <div style={videoContainer}> </div> <div style={textContainer}>Estimate Your Tax Refund for Free. <h3 style={box3}>Estimate your 2016 federal tax refund with our easy and simple tax refund calculator. Choose your options, enter the requested information and the calculator will do the rest. Even better – it’s free!</h3> </div> <div style={TextField}>Estimated Refund Amount <div style={moneyIcon}>$0 </div> </div> </div> {this.renderBoxes()} <div style={toggleContainer}> <div style={toggleOne}> <Toggle /> </div> <div style={toggleOne}> <Toggle /> </div> <div style={toggleOne}> <Toggle /> </div> <div style={toggleOne}> <Toggle /> </div> <div style={toggleOne}> <Toggle /> </div> <div style={toggleOne}> <Toggle /> </div> <div style={toggleOne}> <Toggle /> </div> </div> <div style={bannerStyle}> <div style={banner2}></div> </div> </main> </Responsive> </div> </div> </div> ); } }
src/views/SignUpView/SignUpView.js
softage0/solid-online-services
import React from 'react' import SignUpForm from '../../forms/SignUpForm' export class SignUp extends React.Component { render () { return ( <SignUpForm /> ) } } export default SignUp
src/containers/articles/credits.js
b0ts/react-redux-sweetlightstudios-website
import React, { Component } from 'react'; import { articleMounting } from '../../actions/index.js'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { ResponsiveEmbed, Image, Grid, Row, Col } from 'react-bootstrap'; import Parser from 'html-react-parser'; import Reveal from 'react-reveal'; import '../../animate.css'; class Credits extends Component { componentWillMount() { this.props.articleMounting("credits"); }; render() { return ( <article className="credits"> <h1 className="credits-title">{this.props.siteConfig.credits.title}</h1> <div className="credits-vid"> <ResponsiveEmbed a16by9> <iframe title="slsvid" className="embed-responsive-item" src={this.props.siteConfig.credits.vid}> </iframe> </ResponsiveEmbed> </div> <Grid> {this.rollCredits()} </Grid> </article> ); }; rollCredits() { return this.props.siteConfig.credits.roll.map((credit, index) => { let image = (credit.image.includes("http")) ? credit.image : (this.props.siteConfig.imageCDN + credit.image); return ( <Row className="credit-row" key={credit.title} > <a href={credit.link}> <Col className="credit-column" sm={6}> <Reveal effect={"animated " + credit.leftAnimation} > <Image className="credit-image" src={image} alt={credit.alt} responsive/> </Reveal> </Col> <Col className="credit-column" sm={6}> <Reveal effect={"animated " + credit.rightAnimation} > <h2 className="credit-title" >{credit.title}</h2> <p className="credit-details" >{Parser(credit.details.join(''))}</p> </Reveal> </Col> </a> <hr className="credit-separator" /> </Row> ); }); }; }; const mapStateToProps = (state) => ({ siteConfig: state.siteConfig }); const mapDispatchToProps = (dispatch) => bindActionCreators({ articleMounting }, dispatch); export default connect(mapStateToProps, mapDispatchToProps) (Credits);
webapp/src/containers/search/multiTable.js
alliance-genome/agr
/*eslint-disable react/sort-prop-types */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createMemoryHistory, Link } from 'react-router'; import _ from 'underscore'; import style from './style.css'; import ResultsTable from './resultsTable'; import CategoryLabel from './categoryLabel'; import fetchData from '../../lib/fetchData'; import { SEARCH_API_ERROR_MESSAGE } from '../../constants'; import { receiveResponse, setError, setPending } from '../../actions/search'; import { selectQueryParams, selectGeneResults, selectGoResults, selectDiseaseResults, selectGeneTotal, selectGoTotal, selectDiseaseTotal, selectHomologyGroupTotal, } from '../../selectors/searchSelectors'; const BASE_SEARCH_URL = '/api/search'; const PAGE_SIZE = 5; const CATEGORIES = ['gene', 'go']; class MultiTableComponent extends Component { componentDidMount() { this.fetchAllData(); } // fetch data whenever URL changes within /search componentDidUpdate (prevProps) { if (prevProps.queryParams !== this.props.queryParams) { this.fetchAllData(); } } getUrlByCategory(category) { let size = PAGE_SIZE; let currentPage = 1; let _limit = size; let _offset = (currentPage - 1) * size; let qp = _.clone(this.props.queryParams); qp.limit = _limit; qp.offset = _offset; qp.category = category; let tempHistory = createMemoryHistory('/'); let searchUrl = tempHistory.createPath({ pathname: BASE_SEARCH_URL, query: qp }); return searchUrl; } fetchAllData() { let geneUrl = this.getUrlByCategory('gene'); let goUrl = this.getUrlByCategory('go'); let diseaseUrl = this.getUrlByCategory('disease'); this.props.dispatch(setPending(true)); fetchData(geneUrl) .then( (geneData) => { this.props.dispatch(receiveResponse(geneData, this.props.queryParams, 'gene')); }).then( fetchData(goUrl) .then( (goData) => { this.props.dispatch(receiveResponse(goData, this.props.queryParams, 'go')); })).then( fetchData(diseaseUrl) .then( (diseaseData) => { this.props.dispatch(receiveResponse(diseaseData, this.props.queryParams, 'disease')); })) .catch( (e) => { this.props.dispatch(setPending(false)); if (process.env.NODE_ENV === 'production') { this.props.dispatch(setError(SEARCH_API_ERROR_MESSAGE)); } else { throw(e); } }); } //there has to be a better way to do this... getTotalForCategory(category) { if (category == 'gene') { return this.props.geneTotal.toLocaleString(); } if (category == 'go') { return this.props.goTotal.toLocaleString(); } if (category == 'disease') { return this.props.diseaseTotal.toLocaleString(); } } //there also has to be a better way to do this... getResultsForCategory(category) { if (category == 'gene') { return this.props.geneResults; } if (category == 'go') { return this.props.goResults; } if (category == 'disease') { return this.props.diseaseResults; } } renderCategory(category) { let categoryHref = this.getUrlByCategory(category); return ( <div> <p> <Link to={categoryHref}> {this.getTotalForCategory(category)} <CategoryLabel category={category} /> </Link> </p> <ResultsTable activeCategory={category} entries={this.getResultsForCategory(category)} /> </div> ); } render() { return ( <div className={style.resultContainer}> {CATEGORIES.map((category) => this.renderCategory(category))} </div> ); } } MultiTableComponent.propTypes = { dispatch: React.PropTypes.func, queryParams: React.PropTypes.object, geneResults: React.PropTypes.array, goResults: React.PropTypes.array, diseaseResults: React.PropTypes.array, geneTotal: React.PropTypes.number, goTotal: React.PropTypes.number, diseaseTotal: React.PropTypes.number, homologyGroupTotal: React.PropTypes.number }; function mapStateToProps(state) { return { queryParams: selectQueryParams(state), geneResults: selectGeneResults(state), goResults: selectGoResults(state), diseaseResults: selectDiseaseResults(state), geneTotal: selectGeneTotal(state), goTotal: selectGoTotal(state), diseaseTotal: selectDiseaseTotal(state), homologyGroupTotal: selectHomologyGroupTotal(state), }; } export { MultiTableComponent as MultiTableComponent }; export default connect(mapStateToProps)(MultiTableComponent);
packages/wix-style-react/src/MarketingPageLayoutContent/MarketingPageLayoutContent.js
wix/wix-style-react
import React from 'react'; import PropTypes from 'prop-types'; import { st, classes } from './MarketingPageLayoutContent.st.css'; import { dataHooks, size } from './constants'; import Divider from '../Divider'; import Text, { SIZES as TEXT_SIZES } from '../Text'; import Heading, { APPEARANCES } from '../Heading'; import Box from '../Box'; import { isString } from '../utils/StringUtils'; const sizesMap = { overline: { [size.medium]: TEXT_SIZES.small, [size.large]: TEXT_SIZES.medium, }, title: { [size.medium]: APPEARANCES.H2, [size.large]: APPEARANCES.H1, }, subtitle: { [size.medium]: APPEARANCES.H4, [size.large]: APPEARANCES.H3, }, content: { [size.medium]: TEXT_SIZES.small, [size.large]: TEXT_SIZES.medium, }, }; /** This component is used in the MarketingPageLayout component. It includes all the content of the page. */ class MarketingPageLayoutContent extends React.PureComponent { render() { const { dataHook, className, size, overline, title, subtitle, content, actions, } = this.props; return ( <div data-hook={dataHook} className={st(classes.root, className)}> {overline && ( <div data-hook={dataHooks.overlineContainer}> <Box color="D20"> {isString(overline) ? ( <Text dataHook={dataHooks.overline} size={sizesMap.overline[size]} skin="standard" secondary > {overline} </Text> ) : ( overline )} </Box> <div className={classes.overlineDividerContainer}> <Divider /> </div> </div> )} {title && ( <Box dataHook={dataHooks.titleContainer}> {isString(title) ? ( <Heading dataHook={dataHooks.title} appearance={sizesMap.title[size]} > {title} </Heading> ) : ( title )} </Box> )} {subtitle && ( <Box dataHook={dataHooks.subtitleContainer} marginTop="SP2"> {isString(subtitle) ? ( <Heading dataHook={dataHooks.subtitle} appearance={sizesMap.subtitle[size]} > {subtitle} </Heading> ) : ( subtitle )} </Box> )} {content && ( <Box dataHook={dataHooks.contentContainer} marginTop="SP4" color="D10" > {isString(content) ? ( <Text dataHook={dataHooks.content} size={sizesMap.content[size]} skin="standard" > {content} </Text> ) : ( content )} </Box> )} {actions && ( <Box dataHook={dataHooks.actions} marginTop="SP7" children={actions} /> )} </div> ); } } MarketingPageLayoutContent.displayName = 'MarketingPageLayoutContent'; MarketingPageLayoutContent.propTypes = { /** Applied as data-hook HTML attribute that can be used in the tests */ dataHook: PropTypes.string, /** A css class to be applied to the component's root element */ className: PropTypes.string, /** Specifies the size of the marketing page layout content. The default value is 'large'. */ size: PropTypes.oneOf(['medium', 'large']), /** The overline content. */ overline: PropTypes.node, /** The page's title. */ title: PropTypes.node, /** The page's subtitle. */ subtitle: PropTypes.node, /** The page's content. */ content: PropTypes.node, /** The page's actions - area of buttons. */ actions: PropTypes.node, }; MarketingPageLayoutContent.defaultProps = { size: 'large', }; export default MarketingPageLayoutContent;
public/js/app/watchTools/components/Submit.js
fendy3002/QzQueryTools
import React from 'react' import lo from 'lodash' import sa from 'superagent'; var Elem = function({config, filter, request, execQuery}){ var onClick = () => { execQuery({ connection: filter.selectedConnection, query: filter.selectedQuery, params: JSON.stringify(request.params) }); }; return <div className="col-sm-12 text-right"> {filter.selectedQuery && <button type="button" className="btn btn-flat btn-primary" onClick={onClick}> Query </button> } </div>; }; export default Elem;
CompositeUi/src/views/component/DashboardWidget.js
kreta-io/kreta
/* * This file is part of the Kreta package. * * (c) Beñat Espiña <benatespina@gmail.com> * (c) Gorka Laucirica <gorka.lauzirika@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import './../../scss/components/_dashboard-widget.scss'; import React from 'react'; const DashboardWidget = props => <div className="dashboard-widget"> {props.children} </div>; export default DashboardWidget;
traveller/App/Components/CustomNavBar.js
Alabaster-Aardvarks/traveller
import React from 'react' import { View, Image, Animated, TouchableOpacity } from 'react-native' import { Images, Colors } from '../Themes' import Styles from './Styles/CustomNavBarStyle' import Icon from 'react-native-vector-icons/Ionicons' import { Actions as NavigationActions } from 'react-native-router-flux' export default class CustomNavBar extends React.Component { render () { return ( <Animated.View style={Styles.container}> <TouchableOpacity style={Styles.leftButton} onPress={NavigationActions.pop}> <Icon name='ios-arrow-back' size={34} color={Colors.snow} /> </TouchableOpacity> <Image style={Styles.logo} source={Images.clearLogo} /> <View style={Styles.rightButton} /> </Animated.View> ) } }
app/jsx/grading/dataRow.js
djbender/canvas-lms
/* * Copyright (C) 2014 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import PropTypes from 'prop-types' import I18n from 'i18n!gradingdataRow' import numberHelper from '../shared/helpers/numberHelper' const {bool, func, number} = PropTypes class DataRow extends React.Component { static propTypes = { onRowMinScoreChange: func.isRequired, uniqueId: number.isRequired, round: func.isRequired, editing: bool.isRequired } state = {showBottomBorder: false} componentWillReceiveProps() { this.setState({showBottomBorder: false}) } getRowData = () => { const rowData = {name: this.props.row[0], minScore: this.props.row[1], maxScore: null} rowData.maxScore = this.props.uniqueId === 0 ? 100 : this.props.siblingRow[1] return rowData } hideBottomBorder = () => { this.setState({showBottomBorder: false}) } showBottomBorder = () => { this.setState({showBottomBorder: true}) } triggerRowNameChange = event => { this.props.onRowNameChange(this.props.uniqueId, event.target.value) } triggerRowMinScoreBlur = () => { if (this.state.minScoreInput == null) return const inputVal = numberHelper.parse(this.state.minScoreInput) if (!isNaN(inputVal) && inputVal >= 0 && inputVal <= 100) { this.props.onRowMinScoreChange(this.props.uniqueId, String(inputVal)) } this.setState({minScoreInput: null}) } triggerRowMinScoreChange = event => { this.setState({minScoreInput: event.target.value}) } triggerDeleteRow = event => { event.preventDefault() return this.props.onDeleteRow(this.props.uniqueId) } triggerInsertRow = event => { event.preventDefault() return this.props.onInsertRow(this.props.uniqueId) } renderInsertRowButton = () => ( <button className="Button Button--icon-action insert_row_button" onMouseEnter={this.showBottomBorder} onFocus={this.showBottomBorder} onBlur={this.hideBottomBorder} onMouseLeave={this.hideBottomBorder} onClick={this.triggerInsertRow} type="button" > <span className="screenreader-only"> {I18n.t('Insert row below %{name}', {name: this.getRowData().name})} </span> <i className="icon-add" /> </button> ) renderMaxScore = () => { const maxScore = this.props.round(this.getRowData().maxScore) return (maxScore === 100 ? '' : '< ') + I18n.n(maxScore) } renderMinScore = () => { let minScore = this.getRowData().minScore if (!this.props.editing) { minScore = this.props.round(minScore) } else if (this.state.minScoreInput != null) { return this.state.minScoreInput } return I18n.n(minScore) } renderDeleteRowButton = () => { if (this.props.onlyDataRowRemaining) return null return ( <button ref="deleteButton" className="Button Button--icon-action delete_row_button" onClick={this.triggerDeleteRow} type="button" > <span className="screenreader-only"> {I18n.t('Remove row %{name}', {name: this.getRowData().name})} </span> <i className="icon-end" /> </button> ) } renderViewMode = () => ( <tr className="grading_standard_row react_grading_standard_row" ref="viewContainer"> <td className="insert_row_icon_container" /> <td className="row_name_container"> <div className="name" ref="name"> {this.getRowData().name} </div> </td> <td className="row_cell max_score_cell" aria-label={I18n.t('Upper limit of range')}> <div> <span className="max_score" ref="maxScore" title="Upper limit of range"> {`${this.renderMaxScore()}%`} </span> </div> </td> <td className="row_cell"> <div> <span className="range_to" ref="minScore"> {I18n.t('to %{minScore}%', {minScore: this.renderMinScore()})} </span> <span className="min_score" /> </div> </td> <td className="row_cell last_row_cell" /> </tr> ) renderEditMode = () => ( <tr className={ this.state.showBottomBorder ? 'grading_standard_row react_grading_standard_row border_below' : 'grading_standard_row react_grading_standard_row' } ref="editContainer" > <td className="insert_row_icon_container">{this.renderInsertRowButton()}</td> <td className="row_name_container"> <div> <input type="text" ref="nameInput" onChange={this.triggerRowNameChange} className="standard_name" title={I18n.t('Range name')} aria-label={I18n.t('Range name')} name={`grading_standard[standard_data][scheme_${this.props.uniqueId}[name]`} value={this.getRowData().name} /> </div> </td> <td className="row_cell max_score_cell edit_max_score"> <span className="edit_max_score"> {`${this.renderMaxScore()}%`} <span className="screenreader-only">{I18n.t('Upper limit of range')}</span> </span> </td> <td className="row_cell"> <div> <span className="range_to" aria-hidden="true"> {I18n.t('to ')} </span> <input type="text" className="standard_value" ref={input => { this.minScoreInput = input }} onChange={this.triggerRowMinScoreChange} onBlur={this.triggerRowMinScoreBlur} title={I18n.t('Lower limit of range')} aria-label={I18n.t('Lower limit of range')} name={`grading_standard[standard_data][scheme_${this.props.uniqueId}][value]`} value={this.renderMinScore()} /> <span aria-hidden="true"> % </span> </div> </td> <td className="row_cell last_row_cell">{this.renderDeleteRowButton()}</td> </tr> ) render() { return this.props.editing ? this.renderEditMode() : this.renderViewMode() } } export default DataRow
addons/knobs/src/components/types/Number.js
jribeiro/storybook
import PropTypes from 'prop-types'; import React from 'react'; const styles = { display: 'table-cell', boxSizing: 'border-box', verticalAlign: 'middle', height: '25px', width: '100%', outline: 'none', border: '1px solid #f7f4f4', borderRadius: 2, fontSize: 11, padding: '5px', color: '#444', }; class NumberType extends React.Component { constructor(props) { super(props); this.renderNormal = this.renderNormal.bind(this); this.renderRange = this.renderRange.bind(this); } renderNormal() { const { knob, onChange } = this.props; return ( <input id={knob.name} ref={c => { this.input = c; }} style={styles} value={knob.value} type="number" onChange={() => onChange(parseFloat(this.input.value))} /> ); } renderRange() { const { knob, onChange } = this.props; return ( <input id={knob.name} ref={c => { this.input = c; }} style={styles} value={knob.value} type="range" min={knob.min} max={knob.max} step={knob.step} onChange={() => onChange(parseFloat(this.input.value))} /> ); } render() { const { knob } = this.props; return knob.range ? this.renderRange() : this.renderNormal(); } } NumberType.defaultProps = { knob: {}, onChange: value => value, }; NumberType.propTypes = { knob: PropTypes.shape({ name: PropTypes.string, value: PropTypes.number, }), onChange: PropTypes.func, }; NumberType.serialize = value => String(value); NumberType.deserialize = value => parseFloat(value); export default NumberType;
docs/src/examples/elements/List/ContentVariations/index.js
Semantic-Org/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/src/components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/src/components/ComponentDoc/ExampleSection' const ListContentVariations = () => ( <ExampleSection title='Content Variations'> <ComponentExample title='Vertically Aligned' description='An element inside a list can be vertically aligned' examplePath='elements/List/ContentVariations/ListExampleVerticallyAligned' /> <ComponentExample title='Floated' description='A list, or an element inside a list can be floated left or right' examplePath='elements/List/ContentVariations/ListExampleFloated' /> <ComponentExample examplePath='elements/List/ContentVariations/ListExampleFloatedHorizontal' /> </ExampleSection> ) export default ListContentVariations
fixtures/react_native_windows_current/src/EmptyHost.js
callstack-io/haul
import React from 'react'; import { View, Text, StyleSheet } from 'react-native'; export default function EmptyRootComponent() { return ( <View style={styles.container}> <Text style={styles.text}>Host is empty</Text> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#f2f2f2', }, text: { fontSize: 28, textAlign: 'center', color: '#282828' } });
src/components/DropList/DropList.css.js
helpscout/blue
import React from 'react' import styled from 'styled-components' import { getColor } from '../../styles/utilities/color' import Icon from '../Icon' export const DropListWrapperUI = styled('div')` box-sizing: border-box; width: ${({ menuWidth }) => menuWidth}; padding: 0; background-color: white; border: 1px solid ${getColor('grey.600')}; border-radius: 4px; box-shadow: 0px 1px 7px rgba(0, 0, 0, 0.08); font-family: var(--HSDSGlobalFontFamily); font-size: 13px; color: ${getColor('grey.600')}; * { box-sizing: border-box; } ${props => (props.menuCSS ? props.menuCSS : '')}; ` export const MenuListUI = styled('ul')` width: 100%; max-height: 200px; overflow-y: auto; margin: 0; padding: 5px 0 5px 0; list-style: none; &.MenuList-Combobox { padding: 0 0 5px 0; } &:focus { outline: 0; } ` export const InputSearchHolderUI = styled('div')` width: calc(100% - 8px); margin: 4px 4px 5px 4px; display: ${({ show }) => (show ? 'block' : 'none')}; input { width: 100%; height: 38px; padding: 0 15px; font-family: var(--HSDSGlobalFontFamily); font-size: 13px; color: ${getColor('charcoal.600')}; box-shadow: inset 0 0 0 1px ${getColor('grey.600')}; border: 0; border-radius: 3px; &:focus { outline: 0; box-shadow: 0 0 0 2px ${getColor('blue.500')}; } } ` export const ListItemUI = styled('li')` display: flex; justify-content: space-between; align-items: center; height: 36px; margin: 0 5px 2px; padding: 0 10px 0 15px; border-radius: 3px; line-height: 36px; color: ${getColor('charcoal.600')}; background-color: transparent; font-weight: ${props => props.selected && props.withMultipleSelection ? '500' : '400'}; -moz-osx-font-smoothing: ${({ selected }) => selected ? 'auto' : 'grayscale'}; -webkit-font-smoothing: ${({ selected }) => selected ? 'auto' : 'antialiased'}; transition: color ease-in-out 0.1s; cursor: pointer; &:last-child { margin-bottom: 0; } &.is-selected, &.is-highlighted.is-selected { color: white; background-color: ${getColor('blue.600')}; } &.is-highlighted { color: ${getColor('charcoal.800')}; background-color: ${getColor('blue.100')}; } &.with-multiple-selection { &.is-highlighted.is-selected { color: ${getColor('blue.600')}; background-color: ${getColor('blue.100')}; } &.is-selected { color: ${getColor('blue.600')}; background-color: white; } &.is-disabled.is-selected, &.is-highlighted.is-disabled.is-selected { color: ${getColor('charcoal.400')}; background-color: white; } &.is-highlighted { color: ${getColor('charcoal.800')}; background-color: ${getColor('blue.100')}; } } &.is-disabled, &.is-highlighted.is-disabled, &.with-multiple-selection.is-highlighted.is-disabled, &.with-multiple-selection.is-disabled { color: ${getColor('charcoal.200')}; background-color: transparent; cursor: default; } &.is-type-inert, &.is-highlighted.is-type-inert, &.with-multiple-selection.is-highlighted.is-type-inert { background-color: transparent; cursor: default; } ` export const ListItemTextUI = styled('span')` display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; .with-multiple-selection & { max-width: calc(100% - 30px); } ` export const EmptyListUI = styled('div')` height: 36px; margin: 0 5px; padding: 9px 15px 0; font-style: italic; ` const SelectedBadgeUI = styled('div')` width: 24px; height: 24px; padding: 3px; border-radius: 50%; color: ${getColor('blue.500')}; background-color: transparent; opacity: 0; transition: opacity ease-in-out 0.2s, color ease-in-out 0.2s, background-color ease-in-out 0.2s; .is-selected &, .DropListItem.is-selected:hover & { opacity: 1; color: white; background-color: ${getColor('blue.500')}; } .is-disabled &, .DropListItem.is-disabled:hover & { opacity: 1; color: white; background-color: ${getColor('grey.600')}; } .DropListItem:hover & { opacity: 1; background-color: white; } ` export const SelectedBadge = ({ isSelected }) => { return ( <SelectedBadgeUI className="SelectedBadge"> <Icon name="checkmark" size="18" /> </SelectedBadgeUI> ) } export const DividerUI = styled('div')` width: calc(100% - 10px); height: 1px; margin: 9px 5px; background-color: ${getColor('grey.500')}; ` export const GroupLabelUI = styled('div')` height: 36px; margin: 0 5px; padding: 0 15px; line-height: 36px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.7px; color: ${getColor('charcoal.200')}; &:first-child { margin-top: 5px; } ` export const A11yTogglerUI = styled('button')` display: none; `
src/client/course/VenturerCourses.js
jmicmoore/merit-badge-university
import _ from 'lodash'; import React from 'react'; import {connect} from 'react-redux'; import {Link} from 'react-router-dom' import CheckBox from '../common/components/CheckBox'; import { Modal, Button } from 'react-bootstrap'; import VenturerCourse from './VenturerCourse'; import {getCourses, deleteCourse} from './courseActions'; import {COURSE_TYPE} from './constants'; const createRow = (row, rowIndex, deleteCallback) => { return ( <div key={`row_${rowIndex}`} className='row'> { row.map(course => { return ( <div key={course.venturingClass} className="col-sm-3 col-xs-12"> <VenturerCourse course={course} deleteCallback={deleteCallback}/> </div> ) }) } </div> ); }; const create2DArray = (numCols, list) => { const destArray = []; let row = 0; for(let sourceIndex=0; sourceIndex < list.length;){ destArray[row] = []; for(let col=0; col < numCols && sourceIndex < list.length; col++){ destArray[row][col] = list[sourceIndex++]; } row++; } return destArray; }; class VenturingCourses extends React.Component { constructor(){ super(); this.state = { selectedCourse: null, showDeleteConfirm: false, myCoursesOnly: false }; this.closeDeleteConfirm = this.closeDeleteConfirm.bind(this); this.openDeleteConfirm = this.openDeleteConfirm.bind(this); this.handleDeleteCourse = this.handleDeleteCourse.bind(this); this.handleMyCoursesOnlyChange = this.handleMyCoursesOnlyChange.bind(this); }; componentDidMount() { getCourses(); }; openDeleteConfirm(course){ this.setState({ selectedCourse: course, showDeleteConfirm: true }); }; closeDeleteConfirm(){ this.setState({ selectedCourse: null, showDeleteConfirm: false }); }; handleDeleteCourse(){ deleteCourse(this.state.selectedCourse._id); this.closeDeleteConfirm(); }; handleMyCoursesOnlyChange(){ this.setState({myCoursesOnly: !this.state.myCoursesOnly}); } render() { const venturerCourses = _.filter(this.props.courses, course => course.courseType === COURSE_TYPE.Venturing); const filteredCourses = this.state.myCoursesOnly ? _.filter(venturerCourses, (course) => course.teachers.includes('Jerry Moore')) : venturerCourses; const courseGrid = create2DArray(4, filteredCourses); const courseName = this.state.selectedCourse ? this.state.selectedCourse.meritBadge : ''; return ( <div className="container-fluid"> <div className="row"> <div className="col-sm-2 col-xs-12"> <h1>Courses</h1> </div> <div className="col-sm-2 col-xs-12"> <Link to={`/admin/edit-venturer-course`}> <button id="addNewCourse" type="button" className="btn btn-success btn-lg btn-block" aria-label="Left Align"> Add New </button> </Link> </div> <div className="col-sm-offset-1 col-sm-2 col-xs-12"> <CheckBox propertyName='myCoursesOnly' propertyValue={this.state.myCoursesOnly} displayName='Show My Courses Only' changeHandler={this.handleMyCoursesOnlyChange}/> </div> </div> { courseGrid.map((courseRow, index) => createRow(courseRow, index, this.openDeleteConfirm)) } <Modal show={this.state.showDeleteConfirm} onHide={this.closeDeleteConfirm} container={this} aria-labelledby="contained-modal-title" > <Modal.Header closeButton> <Modal.Title id="contained-modal-title">Delete Course</Modal.Title> </Modal.Header> <Modal.Body> Are you sure you want to delete <strong>{courseName}</strong>? </Modal.Body> <Modal.Footer> <Button onClick={this.handleDeleteCourse}>Yes, Delete this course</Button> <Button onClick={this.closeDeleteConfirm}>Cancel</Button> </Modal.Footer> </Modal> </div> ); }; }; const mapStateToProps = ({course}) => { return course; }; export default connect(mapStateToProps)(VenturingCourses);
src/components/Cell.js
LukeGeneva/react-sweeper
import React from 'react'; import PropTypes from 'prop-types'; import './Cell.css'; const Cell = ({value, swept, onClick}) => { const style = { color: colorForValue(value), backgroundColor: value === 'X' && swept ? 'red' : 'white' }; return ( <div className="Cell" onClick={onClick} style={style}> {swept ? value : '\u00a0'} </div> ); } function colorForValue(value) { const colors = { '1': 'red', '2': 'blue' }; return colors[value]; } Cell.propTypes = { value: PropTypes.string.isRequired, swept: PropTypes.bool.isRequired }; export default Cell;
src/components/Spinner.js
pcardune/pyret-ide
import React from 'react'; import Radium from 'radium'; export class Spinner extends React.Component { render() { return ( <img role="presentation" style={this.props.style} src="https://code.pyret.org/img/pyret-spin.gif" /> ); } } Spinner.propTypes = { style: React.PropTypes.object, }; export default Radium(Spinner);
components/ui/CustomSelect.js
resource-watch/resource-watch
import React from 'react'; import PropTypes from 'prop-types'; import SliderSelect from './SliderSelect'; import SearchSelect from './SearchSelect'; function CustomSelect(props) { const { search, ...newProps } = props; return search ? <SearchSelect {...newProps} /> : <SliderSelect {...newProps} />; } CustomSelect.propTypes = { search: PropTypes.bool, }; export default CustomSelect;
src/scripts/components/PLForm.js
chgu82837/react-flux-prac
import React from 'react'; var _ = require('underscore'); var AppActions = require('../actions/AppActions.js'); var AppStore = require('../stores/AppStore.js'); const PLForm = React.createClass({ getInitialState() { return {'email': null, 'name': null, 'text': null, 'index': null}; }, //////////////////////// cancel() { AppActions.changeTarget(null); }, change(event) { // this.state[event.target.id] = event.target.value; var newState = {}; newState[event.target.id] = event.target.value; this.setState(newState); }, click() { console.log(this.state); if(this.state.index === null) AppActions.addItem(this.state); else AppActions.editItemAt(this.state.index,this.state); var r = _.reduce( _.map( this.state, function(ele,k){ return `${k}: ${ele}` } ), function(r,ele){ return r + ele + ", "; }, "" ); // console.log(r); this.props.submit(r); this.setState({ 'email': null, 'name': null, 'text': null, 'index': null }); }, //////////////////////// targetChanged() { var index = AppStore.getTarget(); var newState; if(index !== null){ newState = AppStore.getItem(index); newState.index = index; } else{ newState = {'email': null, 'name': null, 'text': null, 'index': null}; } this.setState(newState); }, componentWillMount() { AppStore.addChangeTargetListener(this.targetChanged); }, componentWillUnmount() { AppStore.removeChangeTargetListener(this.targetChanged); }, //////////////////////// render() { var sumbitAct = this.state.index === null ? "Add Item" : "Edit"; return <div> <div className='form-group'> <label htmlFor='email'>Email</label> <input type="text" id='email' name='email' className='form-control' onChange={this.change} value={this.state.email} /> </div> <div className='form-group'> <label htmlFor='name'>Name</label> <input type="text" id='name' name='name' className='form-control' onChange={this.change} value={this.state.name} /> </div> <div className='form-group'> <label htmlFor='text'>Text</label> <input type="text" id='text' name='text' className='form-control' onChange={this.change} value={this.state.text} /> </div> <div className='form-group'> <button onClick={this.click} className='btn btn-success'> { this.state.index === null ? "Add Item" : "Edit" } </button> { this.state.index === null ? "" : ( <button className="btn btn-warning pull-right" onClick={this.cancel}>Cancel</button> ) } </div> </div>; } }); module.exports = PLForm;
js/components/loaders/Spinner.android.js
phamngoclinh/PetOnline_vs2
/* @flow */ import React from 'react'; import ProgressBarAndroid from 'react-native'; import NativeBaseComponent from 'native-base/Components/Base/NativeBaseComponent'; import computeProps from 'native-base/Utils/computeProps'; export default class SpinnerNB extends NativeBaseComponent { prepareRootProps() { const type = { height: 40, }; const defaultProps = { style: type, }; return computeProps(this.props, defaultProps); } render() { const getColor = () => { if (this.props.color) { return this.props.color; } else if (this.props.inverse) { return this.getTheme().inverseSpinnerColor; } return this.getTheme().defaultSpinnerColor; }; return ( <ProgressBarAndroid {...this.prepareRootProps()} styleAttr={this.props.size ? this.props.size : 'Large'} color={getColor()} /> ); } }
templates/src/components/App/App.js
ekatzenstein/create-react-app-fullstack
import React, { Component } from 'react'; import classnames from 'classnames'; import { Link } from 'react-router-dom'; import logo from './logo.svg'; import './style.css'; class App extends Component { render() { const { className, ...props } = this.props; return ( <div className={classnames('App', className)} {...props}> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React - Fullstack!</h2> </div> <p className="App-intro"> To get started, edit <code>src/components/App/App.js</code> and save to reload. </p> <Link to='about'><button>Test React Router</button></Link> <br /> <br /> <button onClick={this.props.actions.expressTest}>Test if Express is working</button> <br /> <br /> <button onClick={this.props.actions.dbTest}>Test if Express and Sequelize are working</button> <div style={{ padding: '30px' }}>{this.props.results}</div> </div> ); } } export default App;
src/user/screens/profile.screen.js
dyesseyumba/git-point
/* eslint-disable no-shadow */ import React, { Component } from 'react'; import styled from 'styled-components'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { ActivityIndicator, Dimensions, View, RefreshControl, } from 'react-native'; import { ListItem } from 'react-native-elements'; import ActionSheet from 'react-native-actionsheet'; import { ViewContainer, UserProfile, SectionList, ParallaxScroll, UserListItem, EntityInfo, } from 'components'; import { emojifyText, translate, openURLInView } from 'utils'; import { colors, fonts } from 'config'; import { getUserInfo, getStarCount, getIsFollowing, getIsFollower, changeFollowStatus, } from '../user.action'; const mapStateToProps = state => ({ auth: state.auth.user, user: state.user.user, orgs: state.user.orgs, starCount: state.user.starCount, locale: state.auth.locale, isFollowing: state.user.isFollowing, isFollower: state.user.isFollower, isPendingUser: state.user.isPendingUser, isPendingOrgs: state.user.isPendingOrgs, isPendingStarCount: state.user.isPendingStarCount, isPendingCheckFollowing: state.user.isPendingCheckFollowing, isPendingCheckFollower: state.user.isPendingCheckFollower, }); const mapDispatchToProps = dispatch => bindActionCreators( { getUserInfo, getStarCount, getIsFollowing, getIsFollower, changeFollowStatus, }, dispatch ); const BioListItem = styled(ListItem).attrs({ containerStyle: { borderBottomColor: colors.greyLight, borderBottomWidth: 1, }, titleStyle: { color: colors.greyDark, ...fonts.fontPrimary, }, })``; class Profile extends Component { props: { getUserInfo: Function, getStarCount: Function, getIsFollowing: Function, getIsFollower: Function, changeFollowStatus: Function, auth: Object, user: Object, orgs: Array, starCount: string, locale: string, isFollowing: boolean, isFollower: boolean, isPendingUser: boolean, isPendingOrgs: boolean, isPendingStarCount: boolean, isPendingCheckFollowing: boolean, isPendingCheckFollower: boolean, navigation: Object, }; state: { refreshing: boolean, }; constructor(props) { super(props); this.state = { refreshing: false, }; } componentDidMount() { this.getUserInfo(); } getUserInfo = () => { this.setState({ refreshing: true }); const user = this.props.navigation.state.params.user; const auth = this.props.auth; Promise.all([ this.props.getUserInfo(user.login), this.props.getStarCount(user.login), this.props.getIsFollowing(user.login, auth.login), this.props.getIsFollower(user.login, auth.login), ]).then(() => { this.setState({ refreshing: false }); }); }; showMenuActionSheet = () => { this.ActionSheet.show(); }; handlePress = index => { const { user, isFollowing, changeFollowStatus } = this.props; if (index === 0) { changeFollowStatus(user.login, isFollowing); } else if (index === 1) { openURLInView(user.html_url); } }; render() { const { user, orgs, starCount, locale, isFollowing, isFollower, isPendingUser, isPendingOrgs, isPendingStarCount, isPendingCheckFollowing, isPendingCheckFollower, navigation, } = this.props; const { refreshing } = this.state; const initialUser = navigation.state.params.user; const isPending = isPendingUser || isPendingOrgs || isPendingStarCount || isPendingCheckFollowing || isPendingCheckFollower; const userActions = [ isFollowing ? translate('user.profile.unfollow', locale) : translate('user.profile.follow', locale), translate('common.openInBrowser', locale), ]; return ( <ViewContainer> <ParallaxScroll renderContent={() => ( <UserProfile type="user" initialUser={initialUser} starCount={!isPending ? starCount : ''} isFollowing={!isPending ? isFollowing : false} isFollower={!isPending ? isFollower : false} user={!isPending ? user : {}} locale={locale} navigation={navigation} /> )} refreshControl={ <RefreshControl refreshing={refreshing || isPending} onRefresh={this.getUserInfo} /> } stickyTitle={user.login} showMenu={ !isPendingUser && !isPendingCheckFollowing && initialUser.login === user.login } menuAction={() => this.showMenuActionSheet()} navigateBack navigation={navigation} > {isPending && ( <ActivityIndicator animating={isPending} style={{ height: Dimensions.get('window').height / 3 }} size="large" /> )} {!isPending && initialUser.login === user.login && ( <View> {!!user.bio && user.bio !== '' && ( <SectionList title={translate('common.bio', locale)}> <BioListItem titleNumberOfLines={0} title={emojifyText(user.bio)} hideChevron /> </SectionList> )} <EntityInfo entity={user} orgs={orgs} navigation={navigation} locale={locale} /> <SectionList title={translate('common.orgs', locale)} noItems={orgs.length === 0} noItemsMessage={translate('common.noOrgsMessage', locale)} > {orgs.map(item => ( <UserListItem key={item.id} user={item} navigation={navigation} /> ))} </SectionList> </View> )} </ParallaxScroll> <ActionSheet ref={o => { this.ActionSheet = o; }} title={translate('user.profile.userActions', locale)} options={[...userActions, translate('common.cancel', locale)]} cancelButtonIndex={2} onPress={this.handlePress} /> </ViewContainer> ); } } export const ProfileScreen = connect(mapStateToProps, mapDispatchToProps)( Profile );
src/js/components/NewPost.js
Lurk/blog
import React from 'react'; import {input, editorRoot, submitButton} from '../styles/adminPostForm'; import {Editor, EditorState} from 'draft-js'; import {addPost} from '../libs/Posts'; export default class NewPost extends React.Component { constructor(props) { super(props); this.state = { editorState: EditorState.createEmpty(), title:'' }; this.onChangeText = (editorState) => this.setState({editorState}); this.onChangeTitle = (e) => this.setState({title: e.target.value}); this.focus = ()=> this.refs.editor.focus(); this.onSubmit = this.onSubmit.bind(this); } onSubmit(e){ e.preventDefault(); const {editorState, title} = this.state; let contentState = editorState.getCurrentContent(); addPost(title, contentState.getPlainText()); return false; } render() { const {editorState} = this.state; let className = 'RichEditor-editor'; var contentState = editorState.getCurrentContent(); if (!contentState.hasText()) { if (contentState.getBlockMap().first().getType() !== 'unstyled') { className += ' RichEditor-hidePlaceholder'; } } return ( <div> <form onSubmit={this.onSubmit}> <input style={input} value={this.state.title} placeholder="Post title" type="text" onChange={this.onChangeTitle} /> <div className={className} style={editorRoot} onСlick={this.focus}> <Editor placeholder='Tell your story...' ref='editor' editorState={editorState} onChange={this.onChangeText} spellCheck={true} /> </div> <button style={submitButton} type="submit">Submit</button> </form> </div> ); } }
src/app/shared/components/Spacer.js
docgecko/react-alt-firebase-starter
/*! React Alt Firebase Starter */ import React from 'react'; export default class Spacer extends React.Component { render() { return ( <div className='spacer'></div> ); } };
src/svg-icons/notification/airline-seat-recline-extra.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatReclineExtra = (props) => ( <SvgIcon {...props}> <path d="M5.35 5.64c-.9-.64-1.12-1.88-.49-2.79.63-.9 1.88-1.12 2.79-.49.9.64 1.12 1.88.49 2.79-.64.9-1.88 1.12-2.79.49zM16 19H8.93c-1.48 0-2.74-1.08-2.96-2.54L4 7H2l1.99 9.76C4.37 19.2 6.47 21 8.94 21H16v-2zm.23-4h-4.88l-1.03-4.1c1.58.89 3.28 1.54 5.15 1.22V9.99c-1.63.31-3.44-.27-4.69-1.25L9.14 7.47c-.23-.18-.49-.3-.76-.38-.32-.09-.66-.12-.99-.06h-.02c-1.23.22-2.05 1.39-1.84 2.61l1.35 5.92C7.16 16.98 8.39 18 9.83 18h6.85l3.82 3 1.5-1.5-5.77-4.5z"/> </SvgIcon> ); NotificationAirlineSeatReclineExtra = pure(NotificationAirlineSeatReclineExtra); NotificationAirlineSeatReclineExtra.displayName = 'NotificationAirlineSeatReclineExtra'; NotificationAirlineSeatReclineExtra.muiName = 'SvgIcon'; export default NotificationAirlineSeatReclineExtra;
plugins/Wallet/js/components/recoverydialog.js
NebulousLabs/Sia-UI
import PropTypes from 'prop-types' import React from 'react' const RecoveryDialog = ({ recovering, actions }) => { const handleRecoverClick = e => { e.preventDefault() actions.recoverSeed(e.target.seed.value) } const handleCancelClick = e => { e.preventDefault() actions.hideSeedRecoveryDialog() } if (recovering) { return ( <div className='modal'> <div className='recovery-status'> <i className='fa fa-circle-o-notch fa-spin fa-4x' aria-hidden='true' /> <h3> Recovering seed, this may take a long time... </h3> </div> </div> ) } return ( <div className='modal'> <form className='recovery-form' onSubmit={handleRecoverClick}> <h3> Enter a seed to recover funds from. </h3> <p> The entire blockchain will be scanned for outputs belonging to the seed. This takes a while. </p> <p> After the scan completes, these outputs will be sent to your wallet. </p> <input type='text' name='seed' autoFocus /> <div className='recovery-form-buttons'> <button type='submit'>Recover</button> <button onClick={handleCancelClick}>Cancel</button> </div> </form> </div> ) } RecoveryDialog.propTypes = { recovering: PropTypes.bool.isRequired } export default RecoveryDialog
src/components/Tabs/Tabs.js
phklochkov/tabbable-editor
import React from 'react' import {Wrapper} from './Wrapper' import {Tab} from './Tab' import {AddTab} from './AddTab' const Tabs = ({ tabs, handleAdd, handleSelect, handleRemove, handleDrop }) => { return ( <Wrapper> {tabs.items && tabs.items.map( (i) => <Tab key={i.id} item={i} handleSelect={handleSelect} handleDrop={handleDrop} handleRemove={handleRemove} /> )} <AddTab handleAdd={handleAdd} /> </Wrapper> ) } export { Tabs }
js/components/loaders/ProgressBar.android.js
marcpechaitis/ForestWatch
import React, { Component } from 'react'; import { ProgressBarAndroid } from 'react-native'; export default class SpinnerNB extends Component { render() { return ( <ProgressBarAndroid {...this.props} styleAttr="Horizontal" indeterminate={false} progress={this.props.progress ? this.props.progress / 100 : 0.5} color={this.props.color ? this.props.color : '#FFF'} /> ); } }
public/components/agents/fim/inventory/lib/empty-field-handler.js
wazuh/wazuh-kibana-app
/* * Wazuh app - Integrity monitoring components * Copyright (C) 2015-2022 Wazuh, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Find more information about this on the LICENSE file. */ import { EuiCode, EuiIcon, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import React from 'react'; /* This function can be used to render possibly empty fields. It takes a render function suitable for an EuiTable and returns another. */ export const emptyFieldHandler = (renderFn = (value, record) => value) => { return (value, record) => { if (value === '' || value === undefined) { return ( <span style={{display:"flex", minWidth:"0"}}> <EuiIcon type="iInCircle" /> <EuiCode className="wz-ellipsis" style={{whiteSpace:"nowrap"}}>Empty field</EuiCode> </span> ); } else { return renderFn(value, record); } }; };
react-okta-idp/src/App.js
hw-hello-world/okta-signin-widget
import React, { Component } from 'react'; class App extends Component { render() { return ( <div className="content"> {this.props.children} </div> ); } } export default App;
src/funponents/Graph.js
rspica/Sugr
//connect all this to SUBMIT button/page import React from 'react'; import { render } from 'react-dom'; import { Chart } from 'react-google-charts'; import './App.css'; import './Main.js'; export default class App extends React.Component { constructor(props) { super(props); this.state = { // Sets all the stuff that shows up on the screen, s.a. style, axis titles, etc. options: { title: 'Sugar Consumed', hAxis: { title: 'Day' }, vAxis: { title: 'gm of sugar consumed daily', minValue: 0, maxValue: 30 }, colors: ['#FF8A80', '#90CAF9', '#afafaf'], // this sets the types of the three rows, sugar consumed to bar and female and male allowance to a line seriesType: 'line', series: { 0: { type: 'bars' } } }, data: [ ['Day', 'Sugar Consumed', 'Female Allowance', 'Male Allowance'], ['Sun', 25, 24, 36], ['Mon', 16, 24, 36], ['Tues', 9, 24, 36], ['Wed', 8, 24, 36], ['Thurs', 7, 24, 36], ['Fri', 27, 24, 36], ['Sat', 35, 24, 36] ] }; } render() { return ( <div className={'sugar-chart-container'}> <Chart chartType="ComboChart" data={this.state.data} options={this.state.options} width="300px" height="300px" legend_toggle /> </div> ); } }
ressources/index.js
thierryc/Sketch-Find-And-Replace
import React from 'react' import ReactDOM from 'react-dom' import App from './components/App' let dark = true window.settings = {} window.updateData = function(json) { if (typeof window.SetSettings == 'function') { window.SetSettings(json) } else { setTimeout(() => window.updateData(json), 100) } } ReactDOM.render(<App dark settings={window.settings}/>, document.getElementById('root'))
packages/stockflux-launcher/src/toolbar/ToolBar.js
owennw/OpenFinD3FC
import cx from 'classnames'; import React from 'react'; import Components from 'stockflux-components'; import './ToolBar.css'; export default ({ tools, style }) => { return ( <div className={style}> {tools .filter(tool => tool.visible) .map((tool, index) => ( <Components.Buttons.Round key={index} onClick={() => tool.onClick()} disabled={!!tool.disabled} className={cx({ [tool.className]: tool.className })} > {tool.label} {tool.description} </Components.Buttons.Round> ))} </div> ); };
docs/src/components/example-step.js
adamrneary/nuclear-js
import React from 'react' export default React.createClass({ render() { var className = 'example-step'; let push = this.props.push if (push === 'right') { className += ' example-step__push-right' } return <div className={className}> {this.props.children} </div> } })
src/conversations/ConversationList.js
saketkumar95/zulip-mobile
/* @flow */ import React from 'react'; import { FlatList, StyleSheet } from 'react-native'; import { Label } from '../common'; import ConversationUser from './ConversationUser'; import ConversationGroup from './ConversationGroup'; const styles = StyleSheet.create({ list: { flex: 1, flexDirection: 'column', }, groupHeader: { fontWeight: 'bold', paddingLeft: 8, fontSize: 18, }, emptySlate: { flex: 1, textAlign: 'center', fontSize: 20, } }); export default class ConversationList extends React.PureComponent { props: { conversations: string[], realm: string, users: any[], onNarrow: (email: string) => void, } render() { const { conversations } = this.props; if (!conversations.length) { return ( <Label style={styles.emptySlate} text="No recent conversations" /> ); } return ( <FlatList style={styles.list} initialNumToRender={20} data={conversations} keyExtractor={item => item.recipients} renderItem={({ item }) => ( item.recipients.indexOf(',') === -1 ? // if single recipient <ConversationUser email={item.recipients} unreadCount={item.unread} {...this.props} /> : <ConversationGroup email={item.recipients} unreadCount={item.unread} {...this.props} /> )} /> ); } }
demo/static/js/src/components/home.js
OmegaDroid/django-jsx
import React from 'react'; import Nav from './nav' export default class Home extends React.Component { constructor (props) { super(props); this.state = props; } render () { return ( <div> <h1>Home</h1> <p>This is the home view</p> <Nav handleClick={this.state.handleClick} /> </div> ) } }
src/auth.js
LucasYuNju/leanote-desktop-ng
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import Login from './containers/Login'; import configureStore from './store/configureStore'; const { store, persistor } = configureStore(); ReactDOM.render( <Provider store={store}> <Login persistor={persistor} /> </Provider>, document.getElementById('root') ); require('electron').webFrame.setZoomLevelLimits(1, 1);
demo/components/buttongroup/ButtonGroupDemo.js
f0zze/rosemary-ui
import DemoWithSnippet from '../../../demo/layout/DemoWithSnippet'; import {ButtonGroup} from '../../../src'; import Button from '../../../src/components/button/Button'; import React from 'react'; export default class ButtonGroupDemo extends React.Component { render() { return ( <DemoWithSnippet> <ButtonGroup> <Button className="btn--grouped">Hello</Button> <Button className="btn--grouped">Hello 2</Button> </ButtonGroup> </DemoWithSnippet> ); } }
src/svg-icons/editor/border-style.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderStyle = (props) => ( <SvgIcon {...props}> <path d="M15 21h2v-2h-2v2zm4 0h2v-2h-2v2zM7 21h2v-2H7v2zm4 0h2v-2h-2v2zm8-4h2v-2h-2v2zm0-4h2v-2h-2v2zM3 3v18h2V5h16V3H3zm16 6h2V7h-2v2z"/> </SvgIcon> ); EditorBorderStyle = pure(EditorBorderStyle); EditorBorderStyle.displayName = 'EditorBorderStyle'; EditorBorderStyle.muiName = 'SvgIcon'; export default EditorBorderStyle;
app/scripts/routes.js
AbrahamAlcaina/sandbox
import React from 'react'; import { Route, DefaultRoute, NotFoundRoute } from 'react-router'; import App from './pages/app.jsx'; import Home from './pages/home.jsx'; import Product from './pages/product.jsx'; import NotFound from './pages/notFound.jsx'; const routes = ( <Route name="app" path="/" handler={ App }> <Route name="product" handler={ Product } /> <Route name="home" handler={ Home } /> <DefaultRoute handler={ Home } /> <NotFoundRoute handler={ NotFound } /> </Route> ); module.exports = routes;
src/index.js
Terit/mlb-scoreboard
import React from 'react'; import ReactDOM from 'react-dom'; // import routes from './routes'; import './styles/styles.scss'; import App from './components/App.js'; ReactDOM.render(<App />, document.getElementById('app'));
examples/components/DoughnutExample.js
ionutmilica/react-chartjs-components
import React from 'react'; import { DoughnutChart } from '../../src' class BarExample extends React.Component { render() { const data = { labels: [ "Red", "Blue", "Yellow" ], datasets: [ { data: [300, 50, 100], backgroundColor: [ "#FF6384", "#36A2EB", "#FFCE56" ], hoverBackgroundColor: [ "#FF6384", "#36A2EB", "#FFCE56" ] }] }; return ( <DoughnutChart data={data}/> ); } } export default BarExample;
client/node_modules/uu5g03/dist-node/bricks/pagination.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import {BaseMixin, ElementaryMixin, ColorSchemaMixin} from '../common/common.js'; import Glyphicon from './glyphicon.js'; import Link from './link.js'; import './pagination.less'; export const Pagination = React.createClass({ //@@viewOn:mixins mixins: [ BaseMixin, ElementaryMixin, ColorSchemaMixin ], //@@viewOff:mixins //@@viewOn:statics statics: { tagName: 'UU5.Bricks.Pagination', classNames: { main: 'uu5-bricks-pagination pagination', item: 'uu5-bricks-pagination-item', link: 'uu5-bricks-pagination-link', nav: 'uu5-bricks-pagination-nav', size: 'pagination-', active: 'uu5-bricks-pagination-active active', disabledItem: 'disabled' } }, //@@viewOff:statics //@@viewOn:propTypes propTypes: { items: React.PropTypes.array, activeIndex: React.PropTypes.number, range: React.PropTypes.number, prevGlyphicon: React.PropTypes.string, prevLabel: React.PropTypes.node, nextGlyphicon: React.PropTypes.string, nextLabel: React.PropTypes.node, firstGlyphicon: React.PropTypes.string, firstLabel: React.PropTypes.node, lastGlyphicon: React.PropTypes.string, lastLabel: React.PropTypes.node, size: React.PropTypes.oneOf(['sm', 'md', 'lg']), onChange: React.PropTypes.func, onChanged: React.PropTypes.func }, //@@viewOff:propTypes //@@viewOn:getDefaultProps getDefaultProps() { return { items: [1, 2, 3, 4, 5], activeIndex: 0, range: 5, prevGlyphicon: 'uu-glyphicon-arrow-left', prevLabel: null, nextGlyphicon: 'uu-glyphicon-arrow-right', nextLabel: null, firstGlyphicon: null, firstLabel: null, lastGlyphicon: null, lastLabel: null, size: 'md', onChange: null, onChanged: null }; }, //@@viewOff:getDefaultProps //@@viewOn:standardComponentLifeCycle getInitialState() { return { activeIndex: this.props.activeIndex }; }, //@@viewOff:standardComponentLifeCycle //@@viewOn:interface getItemsLength() { return this.props.items.length; }, getActiveIndex() { return this.state.activeIndex; }, setActiveIndex(activeIndex, setStateCallback) { if (activeIndex > -1 && this.getItemsLength() >= activeIndex) { this.setState({ activeIndex: activeIndex }, setStateCallback); } return this; }, increaseActiveIndex(setStateCallback) { var pagination = this; this.setState(function (state) { var newState = null; if (pagination.getItemsLength() - 1 > state.activeIndex) { newState = { activeIndex: state.activeIndex + 1 }; } return newState; }, setStateCallback); return this; }, decreaseActiveIndex(setStateCallback) { this.setState(function (state) { var newState = null; if (0 < state.activeIndex) { newState = { activeIndex: state.activeIndex - 1 }; } return newState; }, setStateCallback); return this; }, //@@viewOff:interface //@@viewOn:overridingMethods //@@viewOff:overridingMethods //@@viewOn:componentSpecificHelpers _getMainAttrs() { var mainAttrs = this.buildMainAttrs(); mainAttrs.className += ' ' + this.getClassName().size + this.props.size; return mainAttrs; }, _range(start, end, step) { step = step || 1; var rangeArray = [start]; while (start + step <= end) { rangeArray.push(start += step); } return rangeArray; }, _getRange() { var i = this.getActiveIndex(); var start = 0; var end = this.getItemsLength() - 1; var range = this.props.range; var step = Math.floor(range / 2.0); if (i <= start + step) { end = range - 1 < end ? range - 1 : end; } else if (i >= end - step) { start = end - range + 1 > 0 ? end - range + 1 : start; } else { start = i - step; end = i + step; } return this._range(start, end); }, _onChange(newActive, link, event) { if (typeof this.props.onChange === 'function') { this.props.onChange(this, newActive, event); } else { event.preventDefault(); var onChanged; if (typeof this.props.onChanged === 'function') { var pagination = this; onChanged = function () { pagination.props.onChanged(this, this.getActiveIndex(), newActive, event); }; } if (newActive === "prev") { this.decreaseActiveIndex(onChanged); } else if (newActive === "next") { this.increaseActiveIndex(onChanged); } else { this.setActiveIndex(newActive, onChanged); } } return this; }, _getItemValue(value) { var newValue = null; var label = this.props[value + 'Label']; var glyphicon = this.props[value + 'Glyphicon']; if (label) { // if array of nodes -> set keys newValue = Array.isArray(label) ? React.Children.toArray(label) : label; } else if (glyphicon) { newValue = <Glyphicon glyphicon={glyphicon} /> } return newValue; }, _createItem(i, value) { var liAttrs = { key: i, className: this.getClassName().item }; var linkAttrs = { className: this.getClassName().link, parent: this }; if (i === this.getActiveIndex()) { liAttrs.className += ' ' + this.getClassName().active; linkAttrs.href = ''; } else { linkAttrs.onClick = this._onChange.bind(null, i); } return ( <li {...liAttrs}> <Link {...linkAttrs}> {value} </Link> </li> ); }, _createNavItem(key, disabled, index) { var liAttrs = { key: key, className: this.getClassName().item + ' ' + this.getClassName().nav + ' ' + this.getClassName().nav + '-' + key }; var linkAttrs = { className: this.getClassName().link, parent: this }; if (disabled) { liAttrs.className += ' ' + this.getClassName().disabledItem; linkAttrs.href = ''; } else { linkAttrs.onClick = this._onChange.bind(null, index === undefined ? key : index); } return ( <li {...liAttrs}> <Link {...linkAttrs}> {this._getItemValue(key)} </Link> </li> ); }, _getItems() { var pagination = this; var range = this._getRange(); var items = range.map(function (i) { return pagination._createItem(i, pagination.props.items[i]); }); if (this.getItemsLength() > this.props.range) { var prevDisabled = this.getActiveIndex() === 0; var nextDisabled = this.getActiveIndex() === this.getItemsLength() - 1; items.unshift(this._createNavItem('prev', prevDisabled)); items.push(this._createNavItem('next', nextDisabled)); (this.props.firstGlyphicon || this.props.firstLabel) && items.unshift(this._createNavItem('first', prevDisabled, 0)); (this.props.lastGlyphicon || this.props.lastLabel) && items.push(this._createNavItem('last', nextDisabled, this.getItemsLength() - 1)); } return items; }, //@@viewOff:componentSpecificHelpers //@@viewOn:render render() { var mainAttrs = this._getMainAttrs(); return ( <ul {...mainAttrs}> {this._getItems()} {this.getDisabledCover()} </ul> ); } //@@viewOff:render }); export default Pagination;
src/client/ui/dialogView.js
tnRaro/FrozenWar
import React from 'react'; import classNames from 'classnames'; export default class DialogView extends React.Component { constructor(props) { super(props); } render() { let classes = classNames('view', 'dialog', { 'error': this.props.type === 'error', 'progress': this.props.type === 'progress', 'message': this.props.type === 'message' }); return <div className={classes}> <h1>{this.props.name}</h1> <p> {this.props.data} </p> </div>; } }
cheesecakes/plugins/content-manager/admin/src/components/SelectMany/SortableItem.js
strapi/strapi-examples
/** * * SortableItem * */ /* eslint-disable react/no-find-dom-node */ import React from 'react'; import { findDOMNode } from 'react-dom'; import { DragSource, DropTarget } from 'react-dnd'; import { getEmptyImage } from 'react-dnd-html5-backend'; import PropTypes from 'prop-types'; import { flow, get } from 'lodash'; import cn from 'classnames'; import SelectManyDraggedItem from 'components/SelectManyDraggedItem'; import ItemTypes from 'utils/ItemTypes'; import styles from './styles.scss'; const sortableItemSource = { beginDrag: props => { return { id: get(props, ['item', 'value', 'id' ]) || get(props, ['item', 'value', '_id'], ''), index: props.index, data: props.item, }; }, endDrag: props => { props.moveAttrEnd(); return {}; }, }; const sortableItemTarget = { hover: (props, monitor, component) => { const dragIndex = monitor.getItem().index; const hoverIndex = props.index; // Don't replace items with themselves if (dragIndex === hoverIndex) { return; } // Determine rectangle on screen const hoverBoundingRect = findDOMNode(component).getBoundingClientRect(); // Get vertical middle const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2; // Determine mouse position const clientOffset = monitor.getClientOffset(); // Get pixels to the top const hoverClientY = clientOffset.y - hoverBoundingRect.top; // Only perform the move when the mouse has crossed half of the items height // When dragging downwards, only move when the cursor is below 50% // When dragging upwards, only move when the cursor is above 50% // Dragging downwards if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) { return; } // Dragging upwards if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) { return; } // Time to actually perform the action props.moveAttr(dragIndex, hoverIndex, props.keys); // Note: we're mutating the monitor item here! // Generally it's better to avoid mutations, // but it's good here for the sake of performance // to avoid expensive index searches. monitor.getItem().index = hoverIndex; }, }; class SortableItem extends React.Component { componentDidMount() { // Use empty image as a drag preview so browsers don't draw it // and we can draw whatever we want on the custom drag layer instead. this.props.connectDragPreview(getEmptyImage(), { // IE fallback: specify that we'd rather screenshot the node // when it already knows it's being dragged so we can hide it with CSS. // Removginv the fallabck makes it handle variable height elements // captureDraggingState: true, }); } render() { const { connectDragSource, connectDropTarget, index, item, isDragging, isDraggingSibling, onClick, onRemove, } = this.props; const opacity = isDragging ? 0.2 : 1; return ( connectDragSource( connectDropTarget( <li className={cn(styles.sortableListItem, !isDraggingSibling && styles.sortableListItemHover)} style={{ opacity }} > <SelectManyDraggedItem index={index} item={item} onClick={onClick} onRemove={onRemove} /> </li> ), ) ); } } const withDropTarget = DropTarget(ItemTypes.SORTABLEITEM, sortableItemTarget, connect => ({ connectDropTarget: connect.dropTarget(), })); const withDragSource = DragSource(ItemTypes.SORTABLEITEM, sortableItemSource, (connect, monitor) => ({ connectDragPreview: connect.dragPreview(), connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), })); SortableItem.defaultProps = { isDraggingSibling: false, }; SortableItem.propTypes = { connectDragPreview: PropTypes.func.isRequired, connectDragSource: PropTypes.func.isRequired, connectDropTarget: PropTypes.func.isRequired, index: PropTypes.number.isRequired, isDragging: PropTypes.bool.isRequired, isDraggingSibling: PropTypes.bool, item: PropTypes.object.isRequired, onClick: PropTypes.func.isRequired, onRemove: PropTypes.func.isRequired, }; export default flow([withDropTarget, withDragSource])(SortableItem);
src/containers/Charts/reactVis/index.js
EncontrAR/backoffice
import React, { Component } from 'react'; import { Row, Col } from 'antd'; import { LineSeries, LineMark, AreaChartElevated, StackedHorizontalBarChart, ClusteredStackedBarChart, CustomScales, CircularGridLines, DynamicProgrammaticRightedgehints, DynamicCrosshairScatterplot, SimpleRadialChart, SimpleDonutChart, CustomRadius, SimpleTreeMap, DynamicTreeMap, BasicSunburst, AnimatedSunburst, CandleStick, ComplexChart, StreamGraph, } from './charts'; import * as configs from './config'; import PageHeader from '../../../components/utility/pageHeader'; import Box from '../../../components/utility/box'; import LayoutWrapper from '../../../components/utility/layoutWrapper'; import ContentHolder from '../../../components/utility/contentHolder'; import basicStyle from '../../../config/basicStyle'; import 'react-vis/dist/style.css'; export default class ReactVis extends Component { render() { const { rowStyle, colStyle, gutter } = basicStyle; return(<LayoutWrapper className="isoMapPage"> <PageHeader>React Vis</PageHeader> <Row style={rowStyle} gutter={gutter} justify="start"> <Col md={12} xs={24} style={colStyle}> <Box title={configs.LineSeries.title} > <ContentHolder> <LineSeries {...configs.LineSeries} /> </ContentHolder> </Box> </Col> <Col md={12} xs={24} style={colStyle}> <Box title={configs.LineMark.title} > <ContentHolder> <LineMark {...configs.LineMark} /> </ContentHolder> </Box> </Col> </Row> <Row style={rowStyle} gutter={gutter} justify="start"> <Col md={12} xs={24} style={colStyle}> <Box title={configs.AreaChartElevated.title} > <ContentHolder> <AreaChartElevated {...configs.AreaChartElevated} /> </ContentHolder> </Box> </Col> <Col md={12} xs={24} style={colStyle}> <Box title={configs.StackedHorizontalBarChart.title} > <ContentHolder> <StackedHorizontalBarChart {...configs.StackedHorizontalBarChart} /> </ContentHolder> </Box> </Col> </Row> <Row style={rowStyle} gutter={gutter} justify="start"> <Col md={12} xs={24} style={colStyle}> <Box title={configs.ClusteredStackedBarChart.title} > <ContentHolder> <ClusteredStackedBarChart {...configs.ClusteredStackedBarChart} /> </ContentHolder> </Box> </Col> <Col md={12} xs={24} style={colStyle}> <Box title={configs.CustomScales.title} > <ContentHolder> <CustomScales {...configs.CustomScales} /> </ContentHolder> </Box> </Col> </Row> <Row style={rowStyle} gutter={gutter} justify="start"> <Col md={12} xs={24} style={colStyle}> <Box title={configs.CircularGridLines.title} > <ContentHolder> <CircularGridLines {...configs.CircularGridLines} /> </ContentHolder> </Box> </Col> <Col md={12} xs={24} style={colStyle}> <Box title={configs.DynamicProgrammaticRightedgehints.title} > <ContentHolder> <DynamicProgrammaticRightedgehints {...configs.DynamicProgrammaticRightedgehints} /> </ContentHolder> </Box> </Col> </Row> <Row style={rowStyle} gutter={gutter} justify="start"> <Col md={12} xs={24} style={colStyle}> <Box title={configs.DynamicCrosshairScatterplot.title} > <ContentHolder> <DynamicCrosshairScatterplot {...configs.DynamicCrosshairScatterplot} /> </ContentHolder> </Box> </Col> <Col md={12} xs={24} style={colStyle}> <Box title={configs.SimpleRadialChart.title} > <ContentHolder> <SimpleRadialChart {...configs.SimpleRadialChart} /> </ContentHolder> </Box> </Col> </Row> <Row style={rowStyle} gutter={gutter} justify="start"> <Col md={12} xs={24} style={colStyle}> <Box title={configs.SimpleDonutChart.title} > <ContentHolder> <SimpleDonutChart {...configs.SimpleDonutChart} /> </ContentHolder> </Box> </Col> <Col md={12} xs={24} style={colStyle}> <Box title={configs.CustomRadius.title} > <ContentHolder> <CustomRadius {...configs.CustomRadius} /> </ContentHolder> </Box> </Col> </Row> <Row style={rowStyle} gutter={gutter} justify="start"> <Col md={12} xs={24} style={colStyle}> <Box title={configs.SimpleTreeMap.title} > <ContentHolder> <SimpleTreeMap {...configs.SimpleTreeMap} /> </ContentHolder> </Box> </Col> <Col md={12} xs={24} style={colStyle}> <Box title={configs.DynamicTreeMap.title} > <ContentHolder> <DynamicTreeMap {...configs.DynamicTreeMap} /> </ContentHolder> </Box> </Col> </Row> <Row style={rowStyle} gutter={gutter} justify="start"> <Col md={12} xs={24} style={colStyle}> <Box title={configs.BasicSunburst.title} > <ContentHolder> <BasicSunburst {...configs.BasicSunburst} /> </ContentHolder> </Box> </Col> <Col md={12} xs={24} style={colStyle}> <Box title={configs.AnimatedSunburst.title} > <ContentHolder> <AnimatedSunburst {...configs.AnimatedSunburst} /> </ContentHolder> </Box> </Col> </Row> <Row style={rowStyle} gutter={gutter} justify="start"> <Col md={12} xs={24} style={colStyle}> <Box title={configs.CandleStick.title} > <ContentHolder> <CandleStick {...configs.CandleStick} /> </ContentHolder> </Box> </Col> <Col md={12} xs={24} style={colStyle}> <Box title={configs.ComplexChart.title} > <ContentHolder> <ComplexChart {...configs.ComplexChart} /> </ContentHolder> </Box> </Col> </Row> <Row style={rowStyle} gutter={gutter} justify="start"> <Col span={24} style={colStyle}> <Box title={configs.StreamGraph.title} > <ContentHolder> <StreamGraph {...configs.StreamGraph} /> </ContentHolder> </Box> </Col> </Row> </LayoutWrapper>); } };
examples/universal/client/index.js
pedrottimark/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import configureStore from '../common/store/configureStore'; import App from '../common/containers/App'; const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const rootElement = document.getElementById('app'); React.render( <Provider store={store}> {() => <App/>} </Provider>, rootElement );
packages/mineral-ui-icons/src/IconUndo.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconUndo(props: IconProps) { const iconProps = { rtl: true, ...props }; return ( <Icon {...iconProps}> <g> <path d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z"/> </g> </Icon> ); } IconUndo.displayName = 'IconUndo'; IconUndo.category = 'content';
src/components/MapToShow.js
alexravs/midgar
import React from 'react'; import { Map, TileLayer } from 'react-leaflet'; import { GeoJson } from 'react-leaflet'; import LoadingSpinner from './LoadingSpinner'; import L from 'leaflet'; const leafletToken = 'pk.eyJ1IjoidmFuYWtlbm0iLCJhIjoiOWNvTG1DWSJ9.O4w4YdN9mbF76M5O6ImYqg'; const leafletProjectId = 'blsq.17ab55a1'; import '../../css/map.scss'; const style = { position:'absolute', width:'100%', height:'100%', }; const mainStyle = () => ({ color: 'rgba(39, 174, 96,1.0)', weight: 4, opacity: 1, fillOpacity: 0, }); function parseGeoJson(geojson) { if (typeof geojson !== 'string') return geojson; return JSON.parse(geojson); } const MapToShoW = ({isFetching, geojson, position, countryCode}) => { const latlng = geojson ? L.geoJson(geojson).getBounds() : [ [40.712, -74.227], [40.774, -74.125] ]; return ( <div> <Map bounds={latlng} zoom={7} center={position} doubleClickZoom={false} keyboard={false} scrollWheelZoom={false} zoomControl={false} attributionControl={false} > { geojson && <GeoJson key={`${Math.random()}`} clickable={false} data={parseGeoJson(geojson)} style={mainStyle()} /> } <TileLayer url={`https://api.tiles.mapbox.com/v4/${leafletProjectId}/{z}/{x}/{y}.png?access_token=${leafletToken}`} attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' /> </Map> </div> ); }; export default MapToShoW;
front/src/components/TaskDetails.js
cheminfo/database-aggregator
import React from 'react'; import TaskHistory from './TaskHistory'; import DatePicker from './DatePicker'; import { Polling } from './Polling'; import Error from './Error'; import DateTime from './DateTime'; export default function TaskDetails({ type, onDatesChange, startDate, endDate, loadingHistory, refreshHistory, fetchTime, history, historyError, name, triggerTask, resetDatabase, taskDataComponent: TaskData }) { return ( <> <h1 className="mb-4">{name}</h1> <div className="w-full"> <Polling interval={10000} url={`/scheduler/${type}/${name}`}> {({ data, error }) => { if (error) return <Error message={error} />; return ( <TaskData task={data} triggerTask={triggerTask} error={error} resetDatabase={resetDatabase} /> ); }} </Polling> <div className="w-full"> <div className="mb-4 mx-2"> <div className="text-l font-bold mb-3">Task history</div> <DatePicker onDatesChange={onDatesChange} startDate={startDate} endDate={endDate} /> <span className="m-4 ml-8 p-2 border-grey-darker border rounded cursor-pointer" onClick={refreshHistory} > Refresh </span> <DateTime description="last fetched" light date={fetchTime} /> </div> {historyError ? ( <Error message={historyError} /> ) : ( <TaskHistory history={history} includeType={type === 'source'} loading={loadingHistory} /> )} </div> </div> </> ); }
docs/src/app/components/pages/components/FlatButton/ExampleSimple.js
matthewoates/material-ui
import React from 'react'; import FlatButton from 'material-ui/FlatButton'; const FlatButtonExampleSimple = () => ( <div> <FlatButton label="Default" /> <FlatButton label="Primary" primary={true} /> <FlatButton label="Secondary" secondary={true} /> <FlatButton label="Disabled" disabled={true} /> </div> ); export default FlatButtonExampleSimple;
src/svg-icons/content/add-box.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentAddBox = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-2 10h-4v4h-2v-4H7v-2h4V7h2v4h4v2z"/> </SvgIcon> ); ContentAddBox = pure(ContentAddBox); ContentAddBox.displayName = 'ContentAddBox'; ContentAddBox.muiName = 'SvgIcon'; export default ContentAddBox;
src/components/CopyButton/CopyButton.js
dialogs/dialog-web-components
/* * Copyright 2019 dialog LLC <info@dlg.im> * @flow */ import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; import { Text } from '@dlghq/react-l10n'; import Clipboard from 'clipboard'; import Button from '../Button/Button'; type Props = { text: string, size?: 'small' | 'normal' | 'large', wide: ?boolean, id?: string, disabled: boolean, }; type State = { copied: ?boolean, }; class CopyButton extends Component<Props, State> { button: ?Node; clipboard: ?Clipboard; timeout: ?TimeoutID; constructor(props: Props) { super(props); this.state = { copied: null, }; } componentDidMount(): void { if (this.button) { const clipboard = new Clipboard(this.button, { /* * this method will be called * each time user press copy button */ text: () => { this.setState({ copied: null }); return this.props.text; }, }); clipboard.on('error', this.handleCopyError); clipboard.on('success', this.handleCopySuccess); this.clipboard = clipboard; } } componentWillReceiveProps(): void { // force clear copied state this.setState({ copied: null }); if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } } componentWillUnmount(): void { if (this.clipboard) { this.clipboard.destroy(); this.clipboard = null; } if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } } handleCopyError = (): void => { this.setState({ copied: false }); }; handleCopySuccess = (event?: $FlowIssue): void => { this.setState({ copied: true }); if (event) { event.clearSelection(); } this.timeout = setTimeout(() => this.setState({ copied: null }), 3000); }; setButton = (button: ?Button): void => { this.button = findDOMNode(button); }; render() { const { copied } = this.state; return ( <Button id={this.props.id} ref={this.setButton} wide={Boolean(this.props.wide)} disabled={this.props.disabled} size={this.props.size} theme={copied ? 'success' : 'primary'} > <Text id={`CopyButton.${copied ? 'copied' : 'copy'}`} /> </Button> ); } } export default CopyButton;
examples/IconSimple.js
react-materialize/react-materialize
import React from 'react'; import Icon from '../src/Icon'; export default <Icon>insert_chart</Icon>;
client/components/surveys/results/summary/ResultsSummary.js
AnatolyBelobrovik/itechartlabs
import React from 'react'; import PropTypes from 'prop-types'; import Question from './Question'; import TextQuestion from './TextQuestion'; const ResultsSummary = ({ answers, questions, totalAnswers, showIndividualResponse, hasMandatoryLabel }) => { const filterAnswers = (array, filter) => { return array.filter(item => item.questionId == filter.id); }; const renderGraphs = questions.map((question) => { let questionAnswers = filterAnswers(answers, question); switch (question.type) { case 'Single': case 'Multiple': case 'Star': case 'Range': return <Question key={question._id} number={question.number} question={question} questionAnswers={questionAnswers} hasMandatoryLabel={hasMandatoryLabel} totalAnswers={totalAnswers} />; case 'Text': case 'File': return <TextQuestion key={question._id} number={question.number} question={question} questionAnswers={questionAnswers} hasMandatoryLabel={hasMandatoryLabel} totalAnswers={totalAnswers} showIndividualResponse={showIndividualResponse} />; } }); return ( <div className="row"> <div className="col-md-12"> {renderGraphs} </div> </div> ); }; ResultsSummary.propTypes = { answers: PropTypes.array.isRequired, questions: PropTypes.array.isRequired, totalAnswers: PropTypes.number.isRequired, hasMandatoryLabel: PropTypes.bool.isRequired, showIndividualResponse: PropTypes.func.isRequired }; export default ResultsSummary;
src/svg-icons/hardware/scanner.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareScanner = (props) => ( <SvgIcon {...props}> <path d="M19.8 10.7L4.2 5l-.7 1.9L17.6 12H5c-1.1 0-2 .9-2 2v4c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-5.5c0-.8-.5-1.6-1.2-1.8zM7 17H5v-2h2v2zm12 0H9v-2h10v2z"/> </SvgIcon> ); HardwareScanner = pure(HardwareScanner); HardwareScanner.displayName = 'HardwareScanner'; HardwareScanner.muiName = 'SvgIcon'; export default HardwareScanner;
src/spinner/index.js
shinxi/euler-ui
import React from 'react' import ReactDOM from 'react-dom' import './spinner.css' import CircleSpinner from 'spin.js' const RingLoader = React.createClass({ render() { return (<div className="spinner__ring"> <div className="spinner__ring1"></div> <div className="spinner__ring2"></div> </div>) } }) const DotLoader = React.createClass({ render() { return (<div className="dotloader"> </div>) } }) const CircleLoader = React.createClass({ componentDidMount() { var opts = { lines: 12, // The number of lines to draw length: 10, // The length of each line width: 8, // The line thickness radius: 22, // The radius of the inner circle scale: 1, // Scales overall size of the spinner corners: 1, // Corner roundness (0..1) color: '#222', // #rgb or #rrggbb or array of colors opacity: 0.2, // Opacity of the lines rotate: 0, // The rotation offset direction: 1, // 1: clockwise, -1: counterclockwise speed: 1, // Rounds per second trail: 60, // Afterglow percentage fps: 20, // Frames per second when using setTimeout() as a fallback for CSS zIndex: 2e9, // The z-index (defaults to 2000000000) className: 'inner', // The CSS class to assign to the spinner top: '48%', // Top position relative to parent left: '50%', // Left position relative to parent shadow: false, // Whether to render a shadow hwaccel: false, // Whether to use hardware acceleration position: 'absolute' // Element positioning }; var target = ReactDOM.findDOMNode(this.refs.spin); new CircleSpinner(opts).spin(target); }, render() { return (<div ref="spin" className="circleloader"> </div>) } }) const Spinner = React.createClass({ getDefaultProps() { return { color: "#26A65B", size: "48px" }; }, hide() { ReactDOM.findDOMNode(this.refs.spinner).style.display = "none"; }, show() { ReactDOM.findDOMNode(this.refs.spinner).style.display = "block"; }, render() { var props = this.props; var type = props.type; var loader = (<CircleLoader />); if (type === 'ring') { loader = <RingLoader />; } else if (type === 'dot') { loader = <DotLoader />; } return ( <div ref="spinner" className="spinner"> <div className="spinner__mask"></div> { loader } </div> ); } }) let lastSpinner; const SpinnerCreator = { show(options = {}) { var target = options.at || document.body; lastSpinner = target.spinner; if (lastSpinner) { lastSpinner.show(); return lastSpinner; } var spinnerContianer = document.createElement('div'); target.appendChild(spinnerContianer); lastSpinner = ReactDOM.render(<Spinner {...options} />, spinnerContianer); target.spinner = lastSpinner; return lastSpinner; }, hide(spinner) { var spinnerToHide = spinner || lastSpinner; spinnerToHide.hide(); } } export default SpinnerCreator
src/components/BioGraphy.js
jainvabhi/PWD
import React from 'react'; const BioGraphy = () => { return ( <div className="mypost-list"> <div className="post-box"> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. </p> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. </p> </div> <div className="post-box"> <h4>General Report</h4> <div className="body p-l-0 p-r-0"> <ul className="list-unstyled"> <li> <div>Blood Pressure</div> <div className="progress"> <div className="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"> <span className="sr-only">40% Complete (success)</span> </div> </div> </li> <li> <div>Heart Beat</div> <div className="progress"> <div className="progress-bar progress-bar-info progress-bar-striped active" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"> <span className="sr-only">20% Complete</span> </div> </div> </li> <li> <div>Haemoglobin</div> <div className="progress"> <div className="progress-bar progress-bar-warning progress-bar-striped active" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"> <span className="sr-only">60% Complete (warning)</span> </div> </div> </li> <li> <div>Sugar</div> <div className="progress"> <div className="progress-bar progress-bar-danger progress-bar-striped active" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"> <span className="sr-only">80% Complete (danger)</span> </div> </div> </li> </ul> </div> </div> <h4>Education</h4> <ul className="dis"> <li>B.Com from Ski University</li> <li>In hac habitasse platea dictumst.</li> <li>In hac habitasse platea dictumst.</li> <li>Vivamus elementum semper nisi.</li> <li>Praesent ac sem eget est egestas volutpat.</li> </ul> <h4>Past Visit History</h4> <ul className="dis"> <li>Integer tincidunt.</li> <li>Praesent vestibulum dapibus nibh.</li> <li>Integer tincidunt.</li> <li>Praesent vestibulum dapibus nibh.</li> <li>Integer tincidunt.</li> <li>Praesent vestibulum dapibus nibh.</li> </ul> </div> ); }; export default BioGraphy;
src/components/note_item.js
asommer70/thehoick-notes-server
import React from 'react'; import { Link } from 'react-router' const NoteItem = ({note}) => { console.log('note:', note.createdAt.getDate() - 1); const created_at = `${note.createdAt.getMonth() + 1}-${note.createdAt.getDate() - 1}-${note.createdAt.getFullYear()}`; return ( <li> <div className="columns"> <div className="column is-8"> <div className="card"> <div className="card-content"> <div className="media"> <div className="media-content"> <p className="title is-5"> <Link to={`/notes/${note.id}`}>{note.get('title')}</Link> </p> </div> </div> <div className="content"> {note.get('text')} <br/> <br/> <p className="subtitle is-6">@{note.get('created_by')}</p> <small>{created_at}</small> </div> </div> </div> </div> </div> </li> ) } export default NoteItem;
src/svg-icons/content/add.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentAdd = (props) => ( <SvgIcon {...props}> <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/> </SvgIcon> ); ContentAdd = pure(ContentAdd); ContentAdd.displayName = 'ContentAdd'; ContentAdd.muiName = 'SvgIcon'; export default ContentAdd;
client/js/containers/Root.js
vladimirutenkov/universal-app
import React from 'react'; import { Router, RouterContext } from 'react-router'; import { Provider } from 'react-redux'; import routes from '../routes'; export const ServerRoot = props => ( <Provider store={props.store}> <RouterContext {...props.renderProps}/> </Provider> ); export default function Root(props) { return ( <Provider store={props.store}> <Router history={props.history} routes={routes}/> </Provider> ); }
src/js/components/icons/base/TableAdd.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}-table-add`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'table-add'); 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}><path fill="none" stroke="#000" strokeWidth="2" d="M8,5 L8,23 M16,5 L16,11 M1,11 L17,11 M1,5 L23,5 M1,17 L11,17 M17,23 L1,23 L1,1 L23,1 L23,17 M17,23 C20.3137085,23 23,20.3137085 23,17 C23,13.6862915 20.3137085,11 17,11 C13.6862915,11 11,13.6862915 11,17 C11,20.3137085 13.6862915,23 17,23 Z M17,14 L17,20 M17,14 L17,20 M14,17 L20,17"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'TableAdd'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
app/containers/NotFoundPage/index.js
kumarankit1234/trello-board
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
src/components/posts_index.js
endreujhelyi/React-Router-Redux-Form
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import { fetchPosts } from '../actions/index'; class PostsIndex extends Component { componentWillMount() { this.props.fetchPosts(); } renderPosts() { return this.props.posts.map(post => { return ( <li className="list-group-item" key={post.id}> <Link to={`posts/${post.id}`}> <span className="pull-xs-right">{post.categories}</span> <strong>{post.title}</strong> </Link> </li> ); }); } render() { return ( <div> <div className="text-xs-right"> <Link to="/posts/new" className="btn btn-primary"> Add a Post </Link> </div> <h3>Posts</h3> <ul className="list-group"> {this.renderPosts()} </ul> </div> ); } } const mapStateToProps = state => { return { posts: state.posts.all }; }; export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
examples/counter-example/src/Counter.js
jerrymao15/react-monocle
import React from 'react'; const Counter = ({ header, count, onDecrement, onIncrement, }) => ( <div> <h2>Counter {header}</h2> <p>Count: {count}</p> <button onClick={onDecrement}>-</button> <button onClick={onIncrement}>+</button> </div> ); Counter.propTypes = { header: React.PropTypes.number.isRequired, count: React.PropTypes.number.isRequired }; export default Counter;
src/parser/druid/guardian/modules/features/IronFurGoEProcs.js
sMteX/WoWAnalyzer
import React from 'react'; import { formatPercentage } from 'common/format'; import SpellIcon from 'common/SpellIcon'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import SPELLS from 'common/SPELLS'; import Analyzer from 'parser/core/Analyzer'; import GuardianOfElune from './GuardianOfElune'; class IronFurGoEProcs extends Analyzer { static dependencies = { guardianOfElune: GuardianOfElune, }; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.GUARDIAN_OF_ELUNE_TALENT.id); } statistic() { const nonGoEIronFur = this.guardianOfElune.nonGoEIronFur; const GoEIronFur = this.guardianOfElune.GoEIronFur; return ( <StatisticBox icon={<SpellIcon id={SPELLS.IRONFUR.id} />} value={`${formatPercentage(nonGoEIronFur / (nonGoEIronFur + GoEIronFur))}%`} label="Unbuffed Ironfur" tooltip={<>You cast <strong>{nonGoEIronFur + GoEIronFur}</strong> total {SPELLS.IRONFUR.name} and <strong>{GoEIronFur}</strong> were buffed by 2s.</>} /> ); } statisticOrder = STATISTIC_ORDER.CORE(9); } export default IronFurGoEProcs;
src/svg-icons/notification/vibration.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationVibration = (props) => ( <SvgIcon {...props}> <path d="M0 15h2V9H0v6zm3 2h2V7H3v10zm19-8v6h2V9h-2zm-3 8h2V7h-2v10zM16.5 3h-9C6.67 3 6 3.67 6 4.5v15c0 .83.67 1.5 1.5 1.5h9c.83 0 1.5-.67 1.5-1.5v-15c0-.83-.67-1.5-1.5-1.5zM16 19H8V5h8v14z"/> </SvgIcon> ); NotificationVibration = pure(NotificationVibration); NotificationVibration.displayName = 'NotificationVibration'; export default NotificationVibration;
src/svg-icons/editor/format-quote.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatQuote = (props) => ( <SvgIcon {...props}> <path d="M6 17h3l2-4V7H5v6h3zm8 0h3l2-4V7h-6v6h3z"/> </SvgIcon> ); EditorFormatQuote = pure(EditorFormatQuote); EditorFormatQuote.displayName = 'EditorFormatQuote'; EditorFormatQuote.muiName = 'SvgIcon'; export default EditorFormatQuote;
client/src/components/dashboard/messaging/conversation.js
ronniehedrick/scapeshift
import React, { Component } from 'react'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import * as actions from '../../../actions/messaging'; import MessageList from './message-list'; import ReplyMessage from './reply-message'; const socket = actions.socket; class Conversation extends Component { constructor(props) { super(props); const { params, fetchConversation } = this.props; // Fetch conversation thread (messages to/from user) fetchConversation(params.conversationId); socket.emit('enter conversation', params.conversationId); // Listen for refresh messages from socket server socket.on('refresh messages', (data) => { fetchConversation(params.conversationId); }); } componentWillUnmount() { socket.emit('leave conversation', this.props.params.conversationId); } renderInbox() { if (this.props.messages) { return ( <MessageList displayMessages={this.props.messages} /> ); } } render() { return ( <div> <div className="panel panel-default"> <div className="panel-body"> <h4 className="left">Conversation with {this.props.params.conversationId}</h4> <Link className="right" to="/dashboard/inbox">Back to Inbox</Link> <div className="clearfix" /> { this.renderInbox() } </div> </div> <ReplyMessage replyTo={this.props.params.conversationId} /> </div> ); } } function mapStateToProps(state) { return { messages: state.communication.messages, }; } export default connect(mapStateToProps, actions)(Conversation);
src/svg-icons/action/toc.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionToc = (props) => ( <SvgIcon {...props}> <path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/> </SvgIcon> ); ActionToc = pure(ActionToc); ActionToc.displayName = 'ActionToc'; ActionToc.muiName = 'SvgIcon'; export default ActionToc;