path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
src/components/chat-pane.js
johnamiahford/slack-clone
'use strict'; import React from 'react'; class ChatPane extends React.Component { render() { return ( <div className="ChatPane"> <div className="container"> <h2>Hey There!</h2> </div> </div> ); } } export default ChatPane;
src/components/TodoApp.js
bofa/react-education
import React from 'react'; // import todos from '../todos'; // import TodoApp = from './components/smart/TodoAppContainer'; // import IndexPage = from './components/smart/IndexPageContainer'; import { List } from 'immutable'; export default class TodoApp extends React.Component { render() { console.log('props', this.props) const { todos, addTodo, toggleTodo, removeTodo, reciveTodos, saveTodos } = this.props; return ( <div> <h1>Behond here there be TODOS!</h1> {this.props.children} </div> ); } componentDidMount() { const { reciveTodos } = this.props; reciveTodos(); } }
src/component/ToDoListWithFlux/TodoFooter.react.js
lyc-chengzi/reactProject
/** * Created by liuyc14 on 2016/9/26. */ import React from 'react'; import TodoAction from '../../flux/actions/TodoAction'; let ReactPropTypes = React.PropTypes; export default class TodoFooter extends React.Component{ constructor(props){ super(props); this._onClearCompletedClick = this._onClearCompletedClick.bind(this); } render() { var allTodos = this.props.allTodos; var total = Object.keys(allTodos).length; if (total === 0) { return null; } var completed = 0; for (var key in allTodos) { if (allTodos[key].complete) { completed++; } } var itemsLeft = total - completed; var itemsLeftPhrase = itemsLeft === 1 ? ' item ' : ' items '; itemsLeftPhrase += 'left'; // Undefined and thus not rendered if no completed items are left. var clearCompletedButton; if (completed) { clearCompletedButton = <button id="clear-completed" onClick={this._onClearCompletedClick}> 清理已完成事项 ({completed}) </button>; } return ( <footer id="footer"> <span id="todo-count"> <strong> {itemsLeft} </strong> {itemsLeftPhrase} </span> {clearCompletedButton} </footer> ); } /** * Event handler to delete all completed TODOs */ _onClearCompletedClick(){ TodoAction.removeCompleted(); } } TodoFooter.propTypes = { allTodos: ReactPropTypes.object.isRequired };
lib/components/notifications.js
ekmartin/hyperterm
import React from 'react'; import Component from '../component'; import {decorate} from '../utils/plugins'; import Notification_ from './notification'; const Notification = decorate(Notification_); export default class Notifications extends Component { template(css) { return (<div className={css('view')}> { this.props.customChildrenBefore } { this.props.fontShowing && <Notification key="font" backgroundColor="rgba(255, 255, 255, .2)" text={`${this.props.fontSize}px`} userDismissable={false} onDismiss={this.props.onDismissFont} dismissAfter={1000} /> } { this.props.resizeShowing && <Notification key="resize" backgroundColor="rgba(255, 255, 255, .2)" text={`${this.props.cols}x${this.props.rows}`} userDismissable={false} onDismiss={this.props.onDismissResize} dismissAfter={1000} /> } { this.props.messageShowing && <Notification key="message" backgroundColor="#FE354E" text={this.props.messageText} onDismiss={this.props.onDismissMessage} userDismissable={this.props.messageDismissable} userDismissColor="#AA2D3C" >{ this.props.messageURL ? [ this.props.messageText, ' (', <a key="link" style={{color: '#fff'}} onClick={ev => { window.require('electron').shell.openExternal(ev.target.href); ev.preventDefault(); }} href={this.props.messageURL} >more</a>, ')' ] : null } </Notification> } { this.props.updateShowing && <Notification key="update" backgroundColor="#7ED321" text={`Version ${this.props.updateVersion} ready`} onDismiss={this.props.onDismissUpdate} userDismissable > Version <b>{this.props.updateVersion}</b> ready. {this.props.updateNote && ` ${this.props.updateNote.trim().replace(/\.$/, '')}`} {' '} (<a style={{color: '#fff'}} onClick={ev => { window.require('electron').shell.openExternal(ev.target.href); ev.preventDefault(); }} href={`https://github.com/zeit/hyper/releases/tag/${this.props.updateVersion}`} >notes</a>). {' '} <a style={{ cursor: 'pointer', textDecoration: 'underline', fontWeight: 'bold' }} onClick={this.props.onUpdateInstall} > Restart </a>. { ' ' } </Notification> } { this.props.customChildren } </div>); } styles() { return { view: { position: 'fixed', bottom: '20px', right: '20px' } }; } }
tests/components/Header/Header.spec.js
nowavailable/TDAlloyUI
import React from 'react' import { Header } from 'components/Header/Header' import { IndexLink, Link } from 'react-router' import { shallow } from 'enzyme' describe('(Component) Header', () => { let _wrapper beforeEach(() => { _wrapper = shallow(<Header/>) }) it('Renders a welcome message', () => { const welcome = _wrapper.find('h1') expect(welcome).to.exist expect(welcome.text()).to.match(/React Redux Starter Kit/) }) describe('Navigation links...', () => { it('Should render an IndexLink to Home route', () => { expect(_wrapper.contains(<IndexLink to='/'/>)).to.equal.true }) it('Should render an Link to Counter route)', () => { expect(_wrapper.contains(<Link to='/counter'/>)).to.equal.true }) }) })
generators/app/templates/app/src/components/SOQHighlightable/SOQHighlightable.js
hasura/generator-hasura-web
import React from 'react'; import { connect } from 'react-redux'; import { toggleHighlight } from './Actions'; import SOQuestion from '../SOQuestion/SOQuestion'; class SOQHighlightable extends React.Component { static propTypes = { question: React.PropTypes.shape({ title: React.PropTypes.string.isRequired, link: React.PropTypes.string.isRequired }).isRequired, unique: React.PropTypes.string.isRequired, highlighted: React.PropTypes.bool, dispatch: React.PropTypes.func.isRequired }; render() { const { question, dispatch, unique, highlighted } = this.props; return ( <div style={ (highlighted) ? {backgroundColor: 'yellow'} : {} }> <SOQuestion question={question}/> <a onClick={ (e) => { e.preventDefault(); dispatch(toggleHighlight(unique)); } } href=""> Highlight</a> </div> ); } } const mapStateToProps = (state, ownProps) => { return { unique: ownProps.unique, highlighted: state.soqh.questions.indexOf(ownProps.unique) > -1 }; }; export default connect(mapStateToProps)(SOQHighlightable);
modules/Link.js
Jastrzebowski/react-router
import React from 'react'; var { object, string, func } = React.PropTypes; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } /** * <Link> components are used to create an <a> element that links to a route. * When that route is active, the link gets an "active" class name (or the * value of its `activeClassName` prop). * * For example, assuming you have the following route: * * <Route name="showPost" path="/posts/:postID" handler={Post}/> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along query string parameters * using the `query` prop. * * <Link to="/posts/123" query={{ show:true }}/> */ export var Link = React.createClass({ contextTypes: { router: object }, propTypes: { activeStyle: object, activeClassName: string, to: string.isRequired, query: object, state: object, onClick: func }, getDefaultProps() { return { className: '', activeClassName: 'active', style: {} }; }, handleClick(event) { var allowTransition = true; var clickResult; if (this.props.onClick) clickResult = this.props.onClick(event); if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; if (clickResult === false || event.defaultPrevented === true) allowTransition = false; event.preventDefault(); if (allowTransition) this.context.router.transitionTo(this.props.to, this.props.query, this.props.state); }, render() { var { router } = this.context; var { to, query } = this.props; var props = Object.assign({}, this.props, { href: router.makeHref(to, query), onClick: this.handleClick }); // ignore if rendered outside of the context of a router, simplifies unit testing if (router && router.isActive(to, query)) { if (props.activeClassName) props.className += props.className !== '' ? ` ${props.activeClassName}` : props.activeClassName; if (props.activeStyle) props.style = Object.assign({}, props.style, props.activeStyle); } return React.createElement('a', props); } }); export default Link;
src/svg-icons/av/videocam.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvVideocam = (props) => ( <SvgIcon {...props}> <path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"/> </SvgIcon> ); AvVideocam = pure(AvVideocam); AvVideocam.displayName = 'AvVideocam'; AvVideocam.muiName = 'SvgIcon'; export default AvVideocam;
js/views/CalendarPage.js
ecohealthalliance/GoodQuestion
import React from 'react'; import { Text, View, } from 'react-native'; import moment from 'moment'; import Styles from '../styles/Styles'; import Color from '../styles/Color'; import Calendar from '../components/Calendar/Calendar'; import CalendarEvent from '../components/Calendar/CalendarEvent'; import Loading from '../components/Loading'; import { loadCachedFormDataById } from '../api/Forms'; import { loadCachedTimeTriggers } from '../api/Triggers'; const CalendarPage = React.createClass({ propTypes: { navigator: React.PropTypes.object.isRequired, survey: React.PropTypes.object, }, getInitialState() { return { stage: 'loading', events: [], selectedEvent: null, }; }, componentDidMount() { loadCachedTimeTriggers({ surveyId: this.props.survey ? this.props.survey.id : false, excludeCompleted: true, excludeExpired: true, }, (err, response) => { if (err) { console.warn(err); this.setState({ stage: 'error'}); return; } const responseLength = response.length; const eventDates = []; const eventIndex = {}; for (let i = 0; i < responseLength; i++) { const date = moment(response[i].datetime).format('YYYY-MM-DD'); eventDates.push(date); if (!eventIndex[date]) { eventIndex[date] = []; } eventIndex[date].push({ datetime: response[i].datetime, title: response[i].title, triggerId: response[i].id, formId: response[i].formId, surveyId: response[i].surveyId, }); } this.eventIndex = eventIndex; this.setState({ events: eventDates, selectedEvent: this.getSelectedEvent(moment().format('YYYY-MM-DD')), }); setTimeout(() => { if (!this.cancelCallbacks) { this.setState({stage: 'ready'}); } }, 300); }); }, componentWillUnmount() { this.cancelCallbacks = true; }, /* Methods */ selectDate(date) { const eventDate = moment(date).format('YYYY-MM-DD'); this.setState({ selectedDate: date, selectedEvent: this.getSelectedEvent(eventDate), }); }, getSelectedEvent(eventDate) { if (this.eventIndex[eventDate]) { const event = this.eventIndex[eventDate][0]; return { type: 'datetime', title: moment(eventDate).format('MMMM Do YYYY'), description: event.title, availability: `Available: ${moment(event.datetime).format('LT')}`, formId: event.formId, }; } return null; }, /* Render */ renderSelectedEvents() { if (this.state.selectedEvent) { const event = this.state.selectedEvent; return ( <CalendarEvent id='1' type='datetime' title={event.title} description={event.description} availability={event.availability} questionCount={10} onPress={() => { const data = loadCachedFormDataById(event.formId); this.props.navigator.push({ path: 'form', title: data.survey.title, survey: data.survey, form: data.form, type: 'datetime', }); }} /> ); } return <Text style={Styles.calendar.eventWarningText}>No remaining events present on this selected date.</Text>; }, render() { if (this.state.stage === 'loading') { return <Loading/>; } else if (this.state.stage === 'error') { return <Text style={[Styles.type.h2, {color: Color.faded}]}>Error loading scheduled dates...</Text>; } return ( <View style={[Styles.container.defaultWhite, { flex: 1, overflow: 'hidden' }]}> <Calendar ref='_calendar' showControls titleFormat={'MMMM YYYY'} prevButtonText={'Prev'} nextButtonText={'Next'} onDateSelect={this.selectDate} onTouchPrev={() => console.log('Back TOUCH')} onTouchNext={() => console.log('Forward TOUCH')} onSwipePrev={() => console.log('Back SWIPE')} onSwipeNext={() => console.log('Forward SWIPE')} eventDates={this.state.events} customStyle={Styles.calendar} /> {this.renderSelectedEvents()} </View> ); }, }); module.exports = CalendarPage;
admin/client/App/shared/Popout/PopoutBody.js
jstockwin/keystone
/** * Render the body of a popout */ import React from 'react'; import blacklist from 'blacklist'; import classnames from 'classnames'; var PopoutBody = React.createClass({ displayName: 'PopoutBody', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, scrollable: React.PropTypes.bool, }, render () { const className = classnames('Popout__body', { 'Popout__scrollable-area': this.props.scrollable, }, this.props.className); const props = blacklist(this.props, 'className', 'scrollable'); return ( <div className={className} {...props} /> ); }, }); module.exports = PopoutBody;
src/public/components/tree/index.js
Lunik/tcloud
import React from 'react' import $ from 'jquery' import Path from 'path' import Branch from './branch' export default class Tree extends React.Component { constructor (props) { super(props) this.state = {} this.initState(props) } initState (props) { Object.assign(this.state, { mobile: window.innerWidth <= 620 }) } componentWillReceiveProps (props) { this.initState(props) } componentWillMount () { $(window).on('resize', (event) => this.handleWindowResize()) } componentWillUnmount () { $(window).off('resize', (event) => this.handleWindowResize()) } handleWindowResize () { this.setState({ mobile: window.innerWidth <= 620 }) } render () { let branches = this.props.path.split('/') let currentPath = '' var JSXBranches = branches.map((branch, key) => { currentPath = Path.join(currentPath, branch) return ( <Branch id={branch} key={key} url={`#${currentPath}`} text={branch}/> ) }) return ( !this.state.mobile && <div className="tree" style={style.div}> <Branch id='files' url="#" text="files"/> {JSXBranches} </div> ) } } Tree.defaultProps = { path: '' } const style = { div: { display: 'inline-block' } }
src/svg-icons/maps/local-drink.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalDrink = (props) => ( <SvgIcon {...props}> <path d="M3 2l2.01 18.23C5.13 21.23 5.97 22 7 22h10c1.03 0 1.87-.77 1.99-1.77L21 2H3zm9 17c-1.66 0-3-1.34-3-3 0-2 3-5.4 3-5.4s3 3.4 3 5.4c0 1.66-1.34 3-3 3zm6.33-11H5.67l-.44-4h13.53l-.43 4z"/> </SvgIcon> ); MapsLocalDrink = pure(MapsLocalDrink); MapsLocalDrink.displayName = 'MapsLocalDrink'; MapsLocalDrink.muiName = 'SvgIcon'; export default MapsLocalDrink;
Realization/frontend/czechidm-core/src/content/dashboards/LongRunningTaskDashboard.js
bcvsolutions/CzechIdMng
import React from 'react'; import { connect } from 'react-redux'; import * as Basic from '../../components/basic'; import { SecurityManager, LongRunningTaskManager } from '../../redux'; import RunningTasks from '../scheduler/RunningTasks'; const manager = new LongRunningTaskManager(); const uiKeyPrefix = 'long-running-taks-table-'; /** * Identity info with link to profile * * @author Radek Tomiška */ class LongRunningTaskDashboard extends Basic.AbstractContent { getContentKey() { return 'dashboard.longRunningTaskDashboard'; } render() { const { identity, _total } = this.props; // if (!SecurityManager.hasAnyAuthority(['SCHEDULER_READ'])) { return null; } // return ( <Basic.Div className={ _total ? '' : 'hidden' }> <Basic.ContentHeader icon="component:scheduled-task" text={ this.i18n('dashboard.longRunningTaskDashboard.header') }/> <Basic.Panel> <RunningTasks manager={ manager } uiKey={ `${ uiKeyPrefix }${ identity ? identity.id : 'dashboard' }` } creatorId={ identity ? identity.id : null } /> </Basic.Panel> </Basic.Div> ); } } function select(state, component) { const uiKey = `${ uiKeyPrefix }${ component.identity ? component.identity.id : 'dashboard' }`; const ui = state.data.ui[uiKey]; if (!ui) { return { i18nReady: state.config.get('i18nReady') }; } return { _total: ui.total, i18nReady: state.config.get('i18nReady') }; } export default connect(select)(LongRunningTaskDashboard);
frontend/src/components/partners/profile/modals/updateObservationSanction/updateSanctionObservationForm.js
unicef/un-partner-portal
import React from 'react'; import R from 'ramda'; import { reduxForm } from 'redux-form'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { Grid } from 'material-ui'; import GridColumn from '../../../../common/grid/gridColumn'; import TextFieldForm from '../../../../forms/textFieldForm'; import SelectForm from '../../../../forms/selectForm'; import { selectNormalizedFlagCategoryChoices, selectNormalizedFlagTypeChoices } from '../../../../../store'; import ArrayForm from '../../../../forms/arrayForm'; import RadioForm from '../../../../forms/radioForm'; const messages = { comments: 'Comments', categoryOfRisk: 'Category of risk', decision: 'Reason for decision', enterDetails: 'Enter additional details...', }; export const SANCATION_DECISION = { NOTMATCH: 'NM', CONFIRMED: 'CM', }; const radioFlag = [ { value: SANCATION_DECISION.NOTMATCH, label: 'Not a true Match', }, { value: SANCATION_DECISION.CONFIRMED, label: 'Confirmed Match', }, ]; const commentFormControlStyle = { padding: '12px 0', }; const Decision = () => () => ( <Grid container> <Grid item sm={12} xs={12}> <RadioForm fieldName="reason_radio" values={radioFlag} /> <TextFieldForm commentFormControlStyle={commentFormControlStyle} label={messages.decision} placeholder={messages.enterDetails} fieldName="validation_comment" /> </Grid> </Grid> ); const UpdateSanctionObservationForm = (props) => { const { categoryChoices, handleSubmit } = props; return ( <form onSubmit={handleSubmit}> <GridColumn> <SelectForm label={messages.categoryOfRisk} fieldName="category" readOnly values={categoryChoices} /> <TextFieldForm label={messages.comments} readOnly fieldName="comment" /> <ArrayForm limit={1} fieldName="flag_decision" disableDeleting initial outerField={Decision()} /> </GridColumn> </form > ); }; UpdateSanctionObservationForm.propTypes = { /** * callback for form submit */ handleSubmit: PropTypes.func.isRequired, categoryChoices: PropTypes.array, }; const formUpdateSanctionObservation = reduxForm({ form: 'updateSanctionObservationForm', })(UpdateSanctionObservationForm); const mapStateToProps = (state, ownProps) => { const observation = R.find(R.propEq('id', ownProps.id), state.partnerObservationsList.items); return { categoryChoices: selectNormalizedFlagCategoryChoices(state), flagTypes: selectNormalizedFlagTypeChoices(state), initialValues: { contact_person: observation.contactPerson, contact_phone: observation.contactPhone, contact_email: observation.contactEmail, attachment: observation.attachment, category: observation.category, comment: observation.comment, }, }; }; export default connect( mapStateToProps, null, )(formUpdateSanctionObservation);
src/routes/private/PanelTools/FilesManager/FilesManager.js
sk-iv/iva-app
import React from 'react'; import {graphql, compose} from 'react-apollo'; import IconButton from '../../../../components/IconButton' import {ChevronRight, Hierarchy, Facets, Hash, Export, TextInput, Magnifier, Plus, Filter, ChevronDown, ChevronLeft, Square, FileUpload, Times, Image, Book} from '../../../../components/SvgIcon'; import List, { ListItem, ListItemIcon, ListItemSecondaryActionStart, ListItemSecondaryAction, ListItemText } from '../../../../components/List' import Checkbox from '../../../../components/Checkbox'; import FILES_LIST from '../../../../queries/fetchFilesList'; import ADD_FILE from '../../../../mutations/AddFile'; import Snackbar from '../../../../components/Snackbar' import Button from '../../../../components/Button' import Avatar from '../../../../components/Avatar' import StateGlobal from '../../../../hoc/StateGlobal' import ActionsPopup from './ActionsPopup' @graphql(FILES_LIST, {name: 'FilesList'}) @graphql(ADD_FILE, {name: 'AddFileMutation'}) @StateGlobal class FilesManager extends React.Component { state = { fileData:[] }; handleToggle = value => () => { const { checked } = this.state; const currentIndex = checked.indexOf(value); const newChecked = [...checked]; if (currentIndex === -1) { newChecked.push(value); } else { newChecked.splice(currentIndex, 1); } this.setState({ checked: newChecked, }); }; render(){ const { stateGlobalQuery:{ openPopup, }, FilesList:{filesList, loading} } = this.props; let type = ['image', 'epub'].map(type=>{ return ('image/jpeg').match(new RegExp(type, "g")); }).filter(x => !!x)[0] console.log(type[0]); const { vertical, horizontal, open, fileData } = this.state; if (loading) {return <div>Loading ...</div>;} return( <React.Fragment> <div className="py-3"> <div className="nav"> <div className="nav-item"> <IconButton aria-label="Zoom" color="primary" to={{pathname:`/private/entity-edit`}}> <Magnifier/> </IconButton> </div> <div className="nav-item"> <input style={{display: 'none'}} id="icon-button-file" type="file" multiple onChange={({ target: { validity, files } })=> { if(validity.valid){ var formData = new FormData(); for (var x = 0; x < files.length; x++){ formData.append("files", files[x]); } // stream progress: https://github.com/SitePen/javascript-streams-blog-examples/blob/master/streaming-fetch/main.js // https://www.sitepen.com/blog/2017/10/02/a-guide-to-faster-web-app-io-and-data-operations-with-streams/ fetch('/uploads',{ method: 'POST', body:formData }).then(res =>{ if (res.status !== 200) { console.log('Looks like there was a problem. Status Code: ' + res.status); return; } // this.consume(res.body.getReader()) res.json().then(data =>{ console.log(data); this.setState({ fileData: data }); this.props.AddFileMutation({ variables: { fileData: data }, }).then(upload =>{ console.log(upload); }) }) }).catch((error) => { console.warn(error); }); } }} /> <label htmlFor="icon-button-file"> <IconButton aria-label="FileUpload" color="primary" component="span"> <FileUpload/> </IconButton> </label> </div> </div> </div> <div className="row"> <div className="col-12"> <List> {filesList.map((item , index)=>( <ListItem key={index}> <Avatar className="mr-3"> <Book /> </Avatar> <ListItemText primary={item.fileName} /> <ListItemSecondaryAction> <ActionsPopup open={openPopup == `file${item.id}`} item={{ slug:`file${item.id}`, catalogHidden:1, id:item.id, type: `file` }} /> </ListItemSecondaryAction> </ListItem> ))} </List> </div> </div> <Snackbar anchorOrigin={{ vertical, horizontal }} open={open} onClose={this.handleClose} SnackbarContentProps={{ 'aria-describedby': 'message-id', }} message={[ <span id="message-id" key={0}>Загрузка файлов</span>, <List key={1}> {fileData.map((file, index)=>( file.originalname ? ( <ListItem key={index}> {file.originalname} </ListItem> ) : ( <ListItem key={index}> {file.error} </ListItem> ) ))} </List> ]} action={[ <IconButton key="close" aria-label="Close" color="inherit" onClick={this.handleClose} > <Times /> </IconButton>, ]} /> </React.Fragment>) } } export default FilesManager;
packages/vulcan-core/lib/modules/containers/withRemove.js
bengott/Telescope
/* Generic mutation wrapper to remove a document from a collection. Sample mutation: mutation moviesRemove($documentId: String) { moviesEdit(documentId: $documentId) { ...MoviesRemoveFormFragment } } Arguments: - documentId: the id of the document to remove Child Props: - removeMutation(documentId) */ import React, { Component } from 'react'; import { graphql } from 'react-apollo'; import gql from 'graphql-tag'; export default function withRemove(options) { const { collection } = options, mutationName = collection.options.mutations.remove.name return graphql(gql` mutation ${mutationName}($documentId: String) { ${mutationName}(documentId: $documentId) { _id } } `, { alias: 'withRemove', props: ({ ownProps, mutate }) => ({ removeMutation: ({ documentId }) => { return mutate({ variables: { documentId } }); }, }), }); }
src/components/GuitarApp/parts/Fretguide/index.js
jesusGalan/fretboardApp
import React, { Component } from 'react'; import {TransparentDiv} from './styled' import {Row} from 'components/common/Template' class Fretguide extends Component { render() { let frets = [] let x = 0 for (x = 0; x < 12; x++) { frets.push(x) } return ( <Row> {frets.map(this.renderTransparentDivs.bind(this))} </Row> ); } renderTransparentDivs(x) { if (x === 0 || x === 3 || x === 5 || x === 7) { return( <TransparentDiv key={x} number={x.toString()}>{x}</TransparentDiv> ) } else { return( <TransparentDiv key={x} number={x.toString()}></TransparentDiv> ) } } } export default Fretguide;
test/spec/injectActions.spec.js
mickeyjsx/mickey
/* eslint-disable react/no-multi-comp */ import { expect } from 'chai' import React from 'react' import ReactDOM from 'react-dom' import PropTypes from 'prop-types' import TestUtils from 'react-dom/test-utils' import injectActions from '../../src/injectActions' describe('injectActions', () => { class Passthrough extends React.Component { // eslint-disable-line render() { return <div /> // eslint-disable-line } } class ProviderMock extends React.Component { getChildContext() { return { actions: this.props.actions } } render() { return React.Children.only(this.props.children) } } ProviderMock.childContextTypes = { actions: PropTypes.object.isRequired, } ProviderMock.propTypes = { actions: PropTypes.object.isRequired, // eslint-disable-line children: PropTypes.element.isRequired, } it('should receive the store in the context', () => { const actions = { foo: 1 } @injectActions class Container extends React.Component { render() { return <Passthrough {...this.props} /> } } const tree = TestUtils.renderIntoDocument( <ProviderMock actions={actions}> <Container pass="through" /> </ProviderMock>, ) const container = TestUtils.findRenderedComponentWithType(tree, Container) expect(container.context.actions).to.be.eql(actions) }) it('should pass actions and props to the given component', () => { const actions = { foo: 'bar', baz: 42, hello: 'world', } @injectActions class Container extends React.Component { render() { return <Passthrough {...this.props} /> } } const container = TestUtils.renderIntoDocument( <ProviderMock actions={actions}> <Container pass="through" baz={50} /> </ProviderMock>, ) const stub = TestUtils.findRenderedComponentWithType(container, Passthrough) expect(stub.props.actions).to.be.eql(actions) expect(stub.props.baz).to.equal(50) expect(stub.props.hello).to.be.undefined // eslint-disable-line expect(() => TestUtils.findRenderedComponentWithType(container, Container), ).to.not.throw() }) it('should throw an error if a component is not passed to injectActions', () => { const WrappedComponent = injectActions() const render = () => { ReactDOM.render(<WrappedComponent />, React.createElement('div')) } expect(render).to.throw() }) it('should throw when trying to access the wrapped instance if withRef is not specified', () => { const actions = {} class Container extends React.Component { // eslint-disable-line render() { return <Passthrough /> } } const Decorated = injectActions(Container) const tree = TestUtils.renderIntoDocument( <ProviderMock actions={actions}> <Decorated /> </ProviderMock>, ) const decorated = TestUtils.findRenderedComponentWithType(tree, Decorated) expect(() => decorated.getWrappedInstance()).to.throw( /To access the wrapped instance, you need to specify \{ withRef: true \} in the options argument of the injectActions\(\) call\./, ) }) it('should return the instance of the wrapped component for use in calling child methods', () => { const actions = {} const someData = { some: 'data', } class Container extends React.Component { someInstanceMethod() { // eslint-disable-line return someData } render() { return <Passthrough /> } } const Decorated = injectActions(Container, { withRef: true }) const tree = TestUtils.renderIntoDocument( <ProviderMock actions={actions}> <Decorated /> </ProviderMock>, ) const decorated = TestUtils.findRenderedComponentWithType(tree, Decorated) expect(() => decorated.someInstanceMethod()).to.throw() expect(decorated.getWrappedInstance().someInstanceMethod()).to.be.eql(someData) expect(decorated.wrappedInstance.someInstanceMethod()).to.be.eql(someData) }) })
src/svg-icons/maps/add-location.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsAddLocation = (props) => ( <SvgIcon {...props}> <path d="M12 2C8.14 2 5 5.14 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.86-3.14-7-7-7zm4 8h-3v3h-2v-3H8V8h3V5h2v3h3v2z"/> </SvgIcon> ); MapsAddLocation = pure(MapsAddLocation); MapsAddLocation.displayName = 'MapsAddLocation'; MapsAddLocation.muiName = 'SvgIcon'; export default MapsAddLocation;
src/components/Select.js
aastein/crypto-trader
import React, { Component } from 'react'; import FontAwesome from 'react-fontawesome'; class Select extends Component { constructor(props) { super(props); this.state = { expanded: false, }; } handleExpand = (event) => { event.preventDefault(); this.setState(prevState => ( { expanded: !prevState.expanded } )); } render() { return ( <div className={`dropdown ${this.props.className}`}> <div className="dropdown-toggle Select-control" role="menu" onClick={this.handleExpand} tabIndex={0}> <span className="Select-value-label">{this.props.value}</span> <span className="Select-arrow-zone"> <span className="Select-arrow" /> </span> </div> { this.state.expanded && <div className="dropdown-menu" aria-hidden> { this.props.options.map((o, i) => ( <div key={`${o.value}${i}`}className="dropdown-item Select-option"> <span className="item-label">{o.label}</span> <div className="item-options"> <input defaultChecked={o.active} className="item-checkbox" type="checkbox" onChange={(e) => { this.props.onCheck(o.value); }} /> <div className="item-drilldown" role="button" onClick={(e) => { this.props.handleDrilldown(o.value); }} tabIndex={0}> <FontAwesome name="chevron-right" /> </div> </div> </div> )) } </div> } </div> ); } } export default Select;
examples/huge-apps/app.js
djkirby/react-router
import React from 'react' import { render } from 'react-dom' import { Router, browserHistory } from 'react-router' import withExampleBasename from '../withExampleBasename' import './stubs/COURSES' const rootRoute = { childRoutes: [ { path: '/', component: require('./components/App'), childRoutes: [ require('./routes/Calendar'), require('./routes/Course'), require('./routes/Grades'), require('./routes/Messages'), require('./routes/Profile') ] } ] } render(( <Router history={withExampleBasename(browserHistory, __dirname)} routes={rootRoute} /> ), document.getElementById('example')) // I've unrolled the recursive directory loop that is happening above to get a // better idea of just what this huge-apps Router looks like, or just look at the // file system :) // // import { Route } from 'react-router' // import App from './components/App' // import Course from './routes/Course/components/Course' // import AnnouncementsSidebar from './routes/Course/routes/Announcements/components/Sidebar' // import Announcements from './routes/Course/routes/Announcements/components/Announcements' // import Announcement from './routes/Course/routes/Announcements/routes/Announcement/components/Announcement' // import AssignmentsSidebar from './routes/Course/routes/Assignments/components/Sidebar' // import Assignments from './routes/Course/routes/Assignments/components/Assignments' // import Assignment from './routes/Course/routes/Assignments/routes/Assignment/components/Assignment' // import CourseGrades from './routes/Course/routes/Grades/components/Grades' // import Calendar from './routes/Calendar/components/Calendar' // import Grades from './routes/Grades/components/Grades' // import Messages from './routes/Messages/components/Messages' // render( // <Router> // <Route path="/" component={App}> // <Route path="calendar" component={Calendar} /> // <Route path="course/:courseId" component={Course}> // <Route path="announcements" components={{ // sidebar: AnnouncementsSidebar, // main: Announcements // }}> // <Route path=":announcementId" component={Announcement} /> // </Route> // <Route path="assignments" components={{ // sidebar: AssignmentsSidebar, // main: Assignments // }}> // <Route path=":assignmentId" component={Assignment} /> // </Route> // <Route path="grades" component={CourseGrades} /> // </Route> // <Route path="grades" component={Grades} /> // <Route path="messages" component={Messages} /> // <Route path="profile" component={Calendar} /> // </Route> // </Router>, // document.getElementById('example') // )
examples/examples/FinancialChartExample.react.js
ericgio/r-d3
import * as d3 from 'd3'; import React from 'react'; import {Axis, Candlestick, Chart, OHLC} from '../../src'; import {getInnerHeight, getInnerWidth, translate} from '../../src/utils'; import ohlcData from '../data/ohlc.csv'; /* example-start */ /** * Adapted from http://bl.ocks.org/andredumas/27c4a333b0e0813e093d */ class FinancialChartExample extends React.Component { state = { type: 'candlestick', }; render() { const {type} = this.state; const height = 500; const width = 960; const margin = {top: 20, right: 20, bottom: 30, left: 50}; const innerHeight = getInnerHeight(height, margin); const innerWidth = getInnerWidth(width, margin); const keys = ohlcData.columns.slice(1); const parseDate = d3.timeParse('%d-%b-%y'); const data = []; ohlcData.slice(50, 200).forEach((d) => { const date = parseDate(d.Date); const n = {date}; keys.forEach((k) => n[k.toLowerCase()] = +d[k]); data.push(n); }); const x = d3.scaleTime() .domain(d3.extent(data, (d) => d.date)) .rangeRound([0, innerWidth]); const y = d3.scaleLinear() .domain([ d3.min(data, (d) => d3.min([d.close, d.high, d.low, d.open])) - 1, d3.max(data, (d) => d3.max([d.close, d.high, d.low, d.open])) + 1, ]) .rangeRound([innerHeight, 0]); const Component = type === 'candlestick' ? Candlestick : OHLC; return ( <div> <div style={{right: '10px', position: 'absolute', top: '10px'}}> {['Candlestick', 'OHLC'].map((t) => ( <label key={t} style={{marginRight: '10px'}}> <input checked={t.toLowerCase() === type} name="ohlc-example" onChange={this._handleChange} type="radio" value={t.toLowerCase()} /> {t} Chart </label> ))} </div> <Chart height={height} transform={translate(margin.left, margin.top)} width={width}> <Axis className="x-axis" orient="bottom" scale={x} transform={translate(0, innerHeight)} /> <Axis className="y-axis" orient="left" scale={y}> <text dy="0.71em" fill="#000" textAnchor="end" transform="rotate(-90)" y={6}> Price ($) </text> </Axis> {data.map((d) => ( <Component {...d} key={d.date.getTime()} width={3} x={x} y={y} /> ))} </Chart> </div> ); } _handleChange = (e) => { this.setState({type: e.target.value}); } } /* example-end */ export default FinancialChartExample;
src/components/applications/index.js
Menternship/client-web
// @flow import React from 'react'; import { Route } from 'react-router'; import ShowAll from './ShowAll'; export default [<Route path="applications" component={ShowAll} />];
app/javascript/mastodon/components/avatar.js
corzntin/mastodon
import React from 'react'; import PropTypes from 'prop-types'; export default class Avatar extends React.PureComponent { static propTypes = { src: PropTypes.string.isRequired, staticSrc: PropTypes.string, size: PropTypes.number.isRequired, style: PropTypes.object, animate: PropTypes.bool, inline: PropTypes.bool, }; static defaultProps = { animate: false, size: 20, inline: false, }; state = { hovering: false, }; handleMouseEnter = () => { if (this.props.animate) return; this.setState({ hovering: true }); } handleMouseLeave = () => { if (this.props.animate) return; this.setState({ hovering: false }); } render () { const { src, size, staticSrc, animate, inline } = this.props; const { hovering } = this.state; let className = 'account__avatar'; if (inline) { className = className + ' account__avatar-inline'; } const style = { ...this.props.style, width: `${size}px`, height: `${size}px`, backgroundSize: `${size}px ${size}px`, }; if (hovering || animate) { style.backgroundImage = `url(${src})`; } else { style.backgroundImage = `url(${staticSrc})`; } return ( <div className={className} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} style={style} /> ); } }
www/src/App.js
ctnitchie/ec2-dashboard
import React from 'react'; import {ec2Service, eventBus} from './services'; import InstanceInfo from './InstanceInfo'; import autobind from 'react-autobind'; import _ from 'lodash'; export default class App extends React.Component { constructor() { super(); this.state = { instances: [], unfilteredInstances: [], filterText: '', showRunning: true, showStopped: true, loadPending: true }; autobind(this); } async componentDidMount() { let instances; try { instances = await ec2Service.listInstances(); instances = instances.sort((a, b) => { let aName = a.tags.Name || a.id; let bName = b.tags.Name || b.id; return aName < bName ? -1 : 1; }); } catch (e) { alert('Error loading instances.'); console.log(e); } this.setState({unfilteredInstances: instances, instances: instances, loadPending: false}); } onFilterChanged(event) { this.filterInstances({filterText: event.target.value}); } filterInstances(newConfig) { let newState = Object.assign( _.pick(this.state, 'filterText', 'showRunning', 'showStopped'), newConfig ); let instances = this.state.unfilteredInstances; let test = newState.filterText.toLowerCase(); newState.instances = this.state.unfilteredInstances.filter((instance) => { if (!newState.showRunning && (instance.state === 'running' || instance.state === 'pending')) { return false; } if (!newState.showStopped && (instance.state === 'stopped' || instance.state === 'stopping')) { return false; } if (test) { let name = instance.tags.Name || instance.id; name += " " + instance.id; instance.securityGroups.forEach(grp => name += " " + grp); Object.values(instance.tags).forEach(v => name += " " + v); return name.toLowerCase().indexOf(test) !== -1; } return true; }); this.setState(newState); } expandAll(event) { eventBus.emit('expandAll'); event.preventDefault(); return false; } collapseAll(event) { eventBus.emit('collapseAll'); event.preventDefault(); return false; } toggleShowStopped() { this.filterInstances({showStopped: !this.state.showStopped}); } toggleShowRunning() { this.filterInstances({showRunning: !this.state.showRunning}); } render() { let instanceList; if (this.state.instances.length) { instanceList = []; this.state.instances.forEach(instance => { instanceList.push(<InstanceInfo key={instance.id} record={instance}/>); }); } else if (this.state.loadPending) { instanceList = <p className="col-sm-offset-3"><span className="spinner"/>&nbsp;Loading...</p>; } else { instanceList = <p className="col-sm-offset-3"><b>No instances found.</b></p>; } return ( <div className="container"> <div className="row"> <div className="col-xs-12"> <h1>EC2 Instance Status Dashboard</h1> <hr/> <div className="row"> <div className="col-xs-12 col-sm-6 col-sm-offset-3"> <div className="form-group"> <label htmlFor="filterInput">Search:</label> <input type="text" className="form-control" id="filterInput" value={this.state.filterText} onChange={this.onFilterChanged} disabled={this.state.loadPending}/> </div> <div className="text-center"> <label> <input type="checkbox" checked={this.state.showRunning} disabled={this.state.loadPending} onChange={this.toggleShowRunning}/> {' Include running instances'} </label> {' '} <label> <input type="checkbox" checked={this.state.showStopped} disabled={this.state.loadPending} onChange={this.toggleShowStopped}/> {' Include stopped instances'} </label> </div> </div> </div> <div className="row"> <div className="col-xs-12 col-sm-6 col-sm-offset-3 expandCollapseButtons"> <a href="#" onClick={this.expandAll}>Expand All</a> &nbsp;|&nbsp; <a href="#" onClick={this.collapseAll}>Collapse All</a> </div> </div> <div className="row"> {instanceList} </div> </div> </div> </div> ); } }
src/svg-icons/notification/sms.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSms = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM9 11H7V9h2v2zm4 0h-2V9h2v2zm4 0h-2V9h2v2z"/> </SvgIcon> ); NotificationSms = pure(NotificationSms); NotificationSms.displayName = 'NotificationSms'; NotificationSms.muiName = 'SvgIcon'; export default NotificationSms;
client/vehicle-finder-spa/src/containers/navbar.js
Del7a/vehicle-finder
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { logout } from '../actions/user'; import NavbarComponent from '../components/navbar'; import { bindActionCreators } from 'redux'; import { Redirect } from 'react-router' class Navbar extends Component { render(){ const isLoggedIn = this.props.user.isLoggedIn || localStorage.getItem("userIsLogged") === '1'; const admin = localStorage.getItem("userIsAdmin") === '1'; return( <NavbarComponent isLoggedIn={isLoggedIn} isAdmin={admin} logout={this.props.logout} handleSearch={this.handleSearch} > </NavbarComponent> )} } function mapStateToProps({user}) { console.log(user) return {user}; } function mapDispatchToProps(dispatch) { return bindActionCreators({logout}, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(Navbar);
src/master.js
m2wasabi/team_vote_milkcocoa
/** * Created by m2wasabi on 2016/07/19. */ import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { createStore } from 'redux' // components import masterApp from './reduces/masterApp'; import App from './components/master/App'; let store = createStore(masterApp); let View = App; /* const View = React.createClass({ render() { return ( <div> ごもくそば! </div> ) } }); */ render( <Provider store={store}> <View/> </Provider>, document.getElementById('content') );
node_modules/recompose/es/Recompose.js
firdiansyah/crud-req
import React, { Component } from 'react'; import shallowEqual from 'fbjs/lib/shallowEqual'; import hoistNonReactStatics from 'hoist-non-react-statics'; import { createChangeEmitter } from 'change-emitter'; import $$observable from 'symbol-observable'; var getDisplayName = function getDisplayName(Component$$1) { if (typeof Component$$1 === 'string') { return Component$$1; } if (!Component$$1) { return undefined; } return Component$$1.displayName || Component$$1.name || 'Component'; }; var wrapDisplayName = function wrapDisplayName(BaseComponent, hocName) { return hocName + '(' + getDisplayName(BaseComponent) + ')'; }; var createHelper = function createHelper(func, helperName) { var setDisplayName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var noArgs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; if (process.env.NODE_ENV !== 'production' && setDisplayName) { if (noArgs) { return function (BaseComponent) { var Component$$1 = func(BaseComponent); Component$$1.displayName = wrapDisplayName(BaseComponent, helperName); return Component$$1; }; } return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return function (BaseComponent) { var Component$$1 = func.apply(undefined, args)(BaseComponent); Component$$1.displayName = wrapDisplayName(BaseComponent, helperName); return Component$$1; }; }; } return func; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var objectWithoutProperties = function (obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; var createEagerElementUtil = function createEagerElementUtil(hasKey, isReferentiallyTransparent, type, props, children) { if (!hasKey && isReferentiallyTransparent) { if (children) { return type(_extends({}, props, { children: children })); } return type(props); } var Component$$1 = type; if (children) { return React.createElement( Component$$1, props, children ); } return React.createElement(Component$$1, props); }; var isClassComponent = function isClassComponent(Component$$1) { return Boolean(Component$$1 && Component$$1.prototype && typeof Component$$1.prototype.isReactComponent === 'object'); }; var isReferentiallyTransparentFunctionComponent = function isReferentiallyTransparentFunctionComponent(Component$$1) { return Boolean(typeof Component$$1 === 'function' && !isClassComponent(Component$$1) && !Component$$1.defaultProps && !Component$$1.contextTypes && (process.env.NODE_ENV === 'production' || !Component$$1.propTypes)); }; var createFactory = function createFactory(type) { var isReferentiallyTransparent = isReferentiallyTransparentFunctionComponent(type); return function (p, c) { return createEagerElementUtil(false, isReferentiallyTransparent, type, p, c); }; }; var mapProps = function mapProps(propsMapper) { return function (BaseComponent) { var factory = createFactory(BaseComponent); return function (props) { return factory(propsMapper(props)); }; }; }; var mapProps$1 = createHelper(mapProps, 'mapProps'); var withProps = function withProps(input) { return mapProps$1(function (props) { return _extends({}, props, typeof input === 'function' ? input(props) : input); }); }; var withProps$1 = createHelper(withProps, 'withProps'); var pick = function pick(obj, keys) { var result = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (obj.hasOwnProperty(key)) { result[key] = obj[key]; } } return result; }; var withPropsOnChange = function withPropsOnChange(shouldMapOrKeys, propsMapper) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var shouldMap = typeof shouldMapOrKeys === 'function' ? shouldMapOrKeys : function (props, nextProps) { return !shallowEqual(pick(props, shouldMapOrKeys), pick(nextProps, shouldMapOrKeys)); }; return function (_Component) { inherits(_class2, _Component); function _class2() { var _temp, _this, _ret; classCallCheck(this, _class2); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.computedProps = propsMapper(_this.props), _temp), possibleConstructorReturn(_this, _ret); } _class2.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (shouldMap(this.props, nextProps)) { this.computedProps = propsMapper(nextProps); } }; _class2.prototype.render = function render() { return factory(_extends({}, this.props, this.computedProps)); }; return _class2; }(Component); }; }; var withPropsOnChange$1 = createHelper(withPropsOnChange, 'withPropsOnChange'); var mapValues = function mapValues(obj, func) { var result = {}; /* eslint-disable no-restricted-syntax */ for (var key in obj) { if (obj.hasOwnProperty(key)) { result[key] = func(obj[key], key); } } /* eslint-enable no-restricted-syntax */ return result; }; var withHandlers = function withHandlers(handlers) { return function (BaseComponent) { var _class, _temp2, _initialiseProps; var factory = createFactory(BaseComponent); return _temp2 = _class = function (_Component) { inherits(_class, _Component); function _class() { var _temp, _this, _ret; classCallCheck(this, _class); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _initialiseProps.call(_this), _temp), possibleConstructorReturn(_this, _ret); } _class.prototype.componentWillReceiveProps = function componentWillReceiveProps() { this.cachedHandlers = {}; }; _class.prototype.render = function render() { return factory(_extends({}, this.props, this.handlers)); }; return _class; }(Component), _initialiseProps = function _initialiseProps() { var _this2 = this; this.cachedHandlers = {}; this.handlers = mapValues(typeof handlers === 'function' ? handlers(this.props) : handlers, function (createHandler, handlerName) { return function () { var cachedHandler = _this2.cachedHandlers[handlerName]; if (cachedHandler) { return cachedHandler.apply(undefined, arguments); } var handler = createHandler(_this2.props); _this2.cachedHandlers[handlerName] = handler; if (process.env.NODE_ENV !== 'production' && typeof handler !== 'function') { console.error( // eslint-disable-line no-console 'withHandlers(): Expected a map of higher-order functions. ' + 'Refer to the docs for more info.'); } return handler.apply(undefined, arguments); }; }); }, _temp2; }; }; var withHandlers$1 = createHelper(withHandlers, 'withHandlers'); var defaultProps = function defaultProps(props) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var DefaultProps = function DefaultProps(ownerProps) { return factory(ownerProps); }; DefaultProps.defaultProps = props; return DefaultProps; }; }; var defaultProps$1 = createHelper(defaultProps, 'defaultProps'); var omit = function omit(obj, keys) { var rest = objectWithoutProperties(obj, []); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (rest.hasOwnProperty(key)) { delete rest[key]; } } return rest; }; var renameProp = function renameProp(oldName, newName) { return mapProps$1(function (props) { var _babelHelpers$extends; return _extends({}, omit(props, [oldName]), (_babelHelpers$extends = {}, _babelHelpers$extends[newName] = props[oldName], _babelHelpers$extends)); }); }; var renameProp$1 = createHelper(renameProp, 'renameProp'); var keys = Object.keys; var mapKeys = function mapKeys(obj, func) { return keys(obj).reduce(function (result, key) { var val = obj[key]; /* eslint-disable no-param-reassign */ result[func(val, key)] = val; /* eslint-enable no-param-reassign */ return result; }, {}); }; var renameProps = function renameProps(nameMap) { return mapProps$1(function (props) { return _extends({}, omit(props, keys(nameMap)), mapKeys(pick(props, keys(nameMap)), function (_, oldName) { return nameMap[oldName]; })); }); }; var renameProps$1 = createHelper(renameProps, 'renameProps'); var flattenProp = function flattenProp(propName) { return function (BaseComponent) { var factory = createFactory(BaseComponent); return function (props) { return factory(_extends({}, props, props[propName])); }; }; }; var flattenProp$1 = createHelper(flattenProp, 'flattenProp'); var withState = function withState(stateName, stateUpdaterName, initialState) { return function (BaseComponent) { var factory = createFactory(BaseComponent); return function (_Component) { inherits(_class2, _Component); function _class2() { var _temp, _this, _ret; classCallCheck(this, _class2); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = { stateValue: typeof initialState === 'function' ? initialState(_this.props) : initialState }, _this.updateStateValue = function (updateFn, callback) { return _this.setState(function (_ref) { var stateValue = _ref.stateValue; return { stateValue: typeof updateFn === 'function' ? updateFn(stateValue) : updateFn }; }, callback); }, _temp), possibleConstructorReturn(_this, _ret); } _class2.prototype.render = function render() { var _babelHelpers$extends; return factory(_extends({}, this.props, (_babelHelpers$extends = {}, _babelHelpers$extends[stateName] = this.state.stateValue, _babelHelpers$extends[stateUpdaterName] = this.updateStateValue, _babelHelpers$extends))); }; return _class2; }(Component); }; }; var withState$1 = createHelper(withState, 'withState'); var withReducer = function withReducer(stateName, dispatchName, reducer, initialState) { return function (BaseComponent) { var factory = createFactory(BaseComponent); return function (_Component) { inherits(_class2, _Component); function _class2() { var _temp, _this, _ret; classCallCheck(this, _class2); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = { stateValue: _this.initializeStateValue() }, _this.dispatch = function (action) { return _this.setState(function (_ref) { var stateValue = _ref.stateValue; return { stateValue: reducer(stateValue, action) }; }); }, _temp), possibleConstructorReturn(_this, _ret); } _class2.prototype.initializeStateValue = function initializeStateValue() { if (initialState !== undefined) { return typeof initialState === 'function' ? initialState(this.props) : initialState; } return reducer(undefined, { type: '@@recompose/INIT' }); }; _class2.prototype.render = function render() { var _babelHelpers$extends; return factory(_extends({}, this.props, (_babelHelpers$extends = {}, _babelHelpers$extends[stateName] = this.state.stateValue, _babelHelpers$extends[dispatchName] = this.dispatch, _babelHelpers$extends))); }; return _class2; }(Component); }; }; var withReducer$1 = createHelper(withReducer, 'withReducer'); var identity = function identity(Component$$1) { return Component$$1; }; var branch = function branch(test, left) { var right = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : identity; return function (BaseComponent) { var leftFactory = void 0; var rightFactory = void 0; return function (props) { if (test(props)) { leftFactory = leftFactory || createFactory(left(BaseComponent)); return leftFactory(props); } rightFactory = rightFactory || createFactory(right(BaseComponent)); return rightFactory(props); }; }; }; var branch$1 = createHelper(branch, 'branch'); var renderComponent = function renderComponent(Component$$1) { return function (_) { var factory = createFactory(Component$$1); var RenderComponent = function RenderComponent(props) { return factory(props); }; if (process.env.NODE_ENV !== 'production') { RenderComponent.displayName = wrapDisplayName(Component$$1, 'renderComponent'); } return RenderComponent; }; }; var renderComponent$1 = createHelper(renderComponent, 'renderComponent', false); var Nothing = function (_Component) { inherits(Nothing, _Component); function Nothing() { classCallCheck(this, Nothing); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } Nothing.prototype.render = function render() { return null; }; return Nothing; }(Component); Nothing.displayName = 'Nothing'; var renderNothing = function renderNothing(_) { return Nothing; }; var renderNothing$1 = createHelper(renderNothing, 'renderNothing', false, true); var shouldUpdate = function shouldUpdate(test) { return function (BaseComponent) { var factory = createFactory(BaseComponent); return function (_Component) { inherits(_class, _Component); function _class() { classCallCheck(this, _class); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } _class.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { return test(this.props, nextProps); }; _class.prototype.render = function render() { return factory(this.props); }; return _class; }(Component); }; }; var shouldUpdate$1 = createHelper(shouldUpdate, 'shouldUpdate'); var pure = shouldUpdate$1(function (props, nextProps) { return !shallowEqual(props, nextProps); }); var pure$1 = createHelper(pure, 'pure', true, true); var onlyUpdateForKeys = function onlyUpdateForKeys(propKeys) { return shouldUpdate$1(function (props, nextProps) { return !shallowEqual(pick(nextProps, propKeys), pick(props, propKeys)); }); }; var onlyUpdateForKeys$1 = createHelper(onlyUpdateForKeys, 'onlyUpdateForKeys'); var onlyUpdateForPropTypes = function onlyUpdateForPropTypes(BaseComponent) { var propTypes = BaseComponent.propTypes; if (process.env.NODE_ENV !== 'production') { if (!propTypes) { /* eslint-disable */ console.error('A component without any `propTypes` was passed to ' + '`onlyUpdateForPropTypes()`. Check the implementation of the ' + ('component with display name "' + getDisplayName(BaseComponent) + '".')); /* eslint-enable */ } } var propKeys = Object.keys(propTypes || {}); var OnlyUpdateForPropTypes = onlyUpdateForKeys$1(propKeys)(BaseComponent); return OnlyUpdateForPropTypes; }; var onlyUpdateForPropTypes$1 = createHelper(onlyUpdateForPropTypes, 'onlyUpdateForPropTypes', true, true); var withContext = function withContext(childContextTypes, getChildContext) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var WithContext = function (_Component) { inherits(WithContext, _Component); function WithContext() { var _temp, _this, _ret; classCallCheck(this, WithContext); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.getChildContext = function () { return getChildContext(_this.props); }, _temp), possibleConstructorReturn(_this, _ret); } WithContext.prototype.render = function render() { return factory(this.props); }; return WithContext; }(Component); WithContext.childContextTypes = childContextTypes; return WithContext; }; }; var withContext$1 = createHelper(withContext, 'withContext'); var getContext = function getContext(contextTypes) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var GetContext = function GetContext(ownerProps, context) { return factory(_extends({}, ownerProps, context)); }; GetContext.contextTypes = contextTypes; return GetContext; }; }; var getContext$1 = createHelper(getContext, 'getContext'); var lifecycle = function lifecycle(spec) { return function (BaseComponent) { var factory = createFactory(BaseComponent); if (process.env.NODE_ENV !== 'production' && spec.hasOwnProperty('render')) { console.error('lifecycle() does not support the render method; its behavior is to ' + 'pass all props and state to the base component.'); } return function (_Component) { inherits(_class, _Component); function _class() { classCallCheck(this, _class); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var _this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))); Object.assign(_this, spec); return _this; } _class.prototype.render = function render() { return factory(_extends({}, this.props, this.state)); }; return _class; }(Component); }; }; var lifecycle$1 = createHelper(lifecycle, 'lifecycle'); var toClass = function toClass(baseComponent) { if (isClassComponent(baseComponent)) { return baseComponent; } var ToClass = function (_Component) { inherits(ToClass, _Component); function ToClass() { classCallCheck(this, ToClass); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } ToClass.prototype.render = function render() { if (typeof baseComponent === 'string') { return React.createElement(baseComponent, this.props); } return baseComponent(this.props, this.context); }; return ToClass; }(Component); ToClass.displayName = getDisplayName(baseComponent); ToClass.propTypes = baseComponent.propTypes; ToClass.contextTypes = baseComponent.contextTypes; ToClass.defaultProps = baseComponent.defaultProps; return ToClass; }; var setStatic = function setStatic(key, value) { return function (BaseComponent) { /* eslint-disable no-param-reassign */ BaseComponent[key] = value; /* eslint-enable no-param-reassign */ return BaseComponent; }; }; var setStatic$1 = createHelper(setStatic, 'setStatic', false); var setPropTypes = function setPropTypes(propTypes) { return setStatic$1('propTypes', propTypes); }; var setPropTypes$1 = createHelper(setPropTypes, 'setPropTypes', false); var setDisplayName = function setDisplayName(displayName) { return setStatic$1('displayName', displayName); }; var setDisplayName$1 = createHelper(setDisplayName, 'setDisplayName', false); function compose() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } return funcs.reduce(function (a, b) { return function () { return a(b.apply(undefined, arguments)); }; }); } var createEagerElement = function createEagerElement(type, props, children) { var isReferentiallyTransparent = isReferentiallyTransparentFunctionComponent(type); /* eslint-disable */ var hasKey = props && props.hasOwnProperty('key'); /* eslint-enable */ return createEagerElementUtil(hasKey, isReferentiallyTransparent, type, props, children); }; var createSink = function createSink(callback) { return function (_Component) { inherits(Sink, _Component); function Sink() { classCallCheck(this, Sink); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } Sink.prototype.componentWillMount = function componentWillMount() { callback(this.props); }; Sink.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { callback(nextProps); }; Sink.prototype.render = function render() { return null; }; return Sink; }(Component); }; var componentFromProp = function componentFromProp(propName) { var Component$$1 = function Component$$1(props) { return createEagerElement(props[propName], omit(props, [propName])); }; Component$$1.displayName = 'componentFromProp(' + propName + ')'; return Component$$1; }; var nest = function nest() { for (var _len = arguments.length, Components = Array(_len), _key = 0; _key < _len; _key++) { Components[_key] = arguments[_key]; } var factories = Components.map(createFactory); var Nest = function Nest(_ref) { var props = objectWithoutProperties(_ref, []), children = _ref.children; return factories.reduceRight(function (child, factory) { return factory(props, child); }, children); }; if (process.env.NODE_ENV !== 'production') { var displayNames = Components.map(getDisplayName); Nest.displayName = 'nest(' + displayNames.join(', ') + ')'; } return Nest; }; var hoistStatics = function hoistStatics(higherOrderComponent) { return function (BaseComponent) { var NewComponent = higherOrderComponent(BaseComponent); hoistNonReactStatics(NewComponent, BaseComponent); return NewComponent; }; }; var _config = { fromESObservable: null, toESObservable: null }; var configureObservable = function configureObservable(c) { _config = c; }; var config = { fromESObservable: function fromESObservable(observable) { return typeof _config.fromESObservable === 'function' ? _config.fromESObservable(observable) : observable; }, toESObservable: function toESObservable(stream) { return typeof _config.toESObservable === 'function' ? _config.toESObservable(stream) : stream; } }; var componentFromStreamWithConfig = function componentFromStreamWithConfig(config$$1) { return function (propsToVdom) { return function (_Component) { inherits(ComponentFromStream, _Component); function ComponentFromStream() { var _config$fromESObserva; var _temp, _this, _ret; classCallCheck(this, ComponentFromStream); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = { vdom: null }, _this.propsEmitter = createChangeEmitter(), _this.props$ = config$$1.fromESObservable((_config$fromESObserva = { subscribe: function subscribe(observer) { var unsubscribe = _this.propsEmitter.listen(function (props) { if (props) { observer.next(props); } else { observer.complete(); } }); return { unsubscribe: unsubscribe }; } }, _config$fromESObserva[$$observable] = function () { return this; }, _config$fromESObserva)), _this.vdom$ = config$$1.toESObservable(propsToVdom(_this.props$)), _temp), possibleConstructorReturn(_this, _ret); } // Stream of props // Stream of vdom ComponentFromStream.prototype.componentWillMount = function componentWillMount() { var _this2 = this; // Subscribe to child prop changes so we know when to re-render this.subscription = this.vdom$.subscribe({ next: function next(vdom) { _this2.setState({ vdom: vdom }); } }); this.propsEmitter.emit(this.props); }; ComponentFromStream.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { // Receive new props from the owner this.propsEmitter.emit(nextProps); }; ComponentFromStream.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) { return nextState.vdom !== this.state.vdom; }; ComponentFromStream.prototype.componentWillUnmount = function componentWillUnmount() { // Call without arguments to complete stream this.propsEmitter.emit(); // Clean-up subscription before un-mounting this.subscription.unsubscribe(); }; ComponentFromStream.prototype.render = function render() { return this.state.vdom; }; return ComponentFromStream; }(Component); }; }; var componentFromStream = componentFromStreamWithConfig(config); var identity$1 = function identity(t) { return t; }; var componentFromStream$2 = componentFromStreamWithConfig({ fromESObservable: identity$1, toESObservable: identity$1 }); var mapPropsStreamWithConfig = function mapPropsStreamWithConfig(config$$1) { return function (transform) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var fromESObservable = config$$1.fromESObservable, toESObservable = config$$1.toESObservable; return componentFromStream$2(function (props$) { var _ref; return _ref = { subscribe: function subscribe(observer) { var subscription = toESObservable(transform(fromESObservable(props$))).subscribe({ next: function next(childProps) { return observer.next(factory(childProps)); } }); return { unsubscribe: function unsubscribe() { return subscription.unsubscribe(); } }; } }, _ref[$$observable] = function () { return this; }, _ref; }); }; }; }; var mapPropsStream = mapPropsStreamWithConfig(config); var mapPropsStream$1 = createHelper(mapPropsStream, 'mapPropsStream'); var createEventHandlerWithConfig = function createEventHandlerWithConfig(config$$1) { return function () { var _config$fromESObserva; var emitter = createChangeEmitter(); var stream = config$$1.fromESObservable((_config$fromESObserva = { subscribe: function subscribe(observer) { var unsubscribe = emitter.listen(function (value) { return observer.next(value); }); return { unsubscribe: unsubscribe }; } }, _config$fromESObserva[$$observable] = function () { return this; }, _config$fromESObserva)); return { handler: emitter.emit, stream: stream }; }; }; var createEventHandler = createEventHandlerWithConfig(config); // Higher-order component helpers // Static property helpers // Composition function // Other utils // Observable helpers export { mapProps$1 as mapProps, withProps$1 as withProps, withPropsOnChange$1 as withPropsOnChange, withHandlers$1 as withHandlers, defaultProps$1 as defaultProps, renameProp$1 as renameProp, renameProps$1 as renameProps, flattenProp$1 as flattenProp, withState$1 as withState, withReducer$1 as withReducer, branch$1 as branch, renderComponent$1 as renderComponent, renderNothing$1 as renderNothing, shouldUpdate$1 as shouldUpdate, pure$1 as pure, onlyUpdateForKeys$1 as onlyUpdateForKeys, onlyUpdateForPropTypes$1 as onlyUpdateForPropTypes, withContext$1 as withContext, getContext$1 as getContext, lifecycle$1 as lifecycle, toClass, setStatic$1 as setStatic, setPropTypes$1 as setPropTypes, setDisplayName$1 as setDisplayName, compose, getDisplayName, wrapDisplayName, shallowEqual, isClassComponent, createEagerElement, createFactory as createEagerFactory, createSink, componentFromProp, nest, hoistStatics, componentFromStream, mapPropsStream$1 as mapPropsStream, createEventHandler, configureObservable as setObservableConfig };
client/modules/User/pages/UserSignUpPage.js
XuHaoJun/tiamat
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import { compose } from 'recompose'; import { hot } from 'react-hot-loader'; import Paper from '@material-ui/core/Paper'; import SignUpForm from '../components/SignUpForm'; import { replace } from 'react-router-redux'; import { setHeaderTitle } from '../../MyApp/MyAppActions'; import { getIsLoggedIn } from '../UserReducer'; const styles = { paper: { textAlign: 'center', verticalAlign: 'middle', width: 500, margin: 'auto', }, form: { padding: 15, }, signUpFormWithMedium: { display: 'flex', alignItems: 'center', justifyContent: 'center', }, }; class UserSignUpPage extends Component { static propTypes = { isLoggedIn: PropTypes.bool.isRequired, }; static getInitialAction() { return setHeaderTitle('註冊'); } componentWillMount() { this.props.dispatch(setHeaderTitle('註冊')); } componentDidMount() { this.goBackIfLoggedIn(); } componentDidUpdate() { this.goBackIfLoggedIn(); } goBackIfLoggedIn = () => { const { isLoggedIn } = this.props; if (isLoggedIn) { const from = this.props.location.query.from || '/'; this.props.dispatch(replace(from)); } }; renderDesktop = () => { return ( <Paper style={styles.paper}> <SignUpForm style={styles.form} /> </Paper> ); }; renderMobile = () => { return <SignUpForm style={styles.signUpFormWithMedium} />; }; render() { const meta = [ { name: 'description', content: '註冊', }, ]; const content = this.props.browser.lessThan.medium ? this.renderMobile() : this.renderDesktop(); return ( <React.Fragment> <Helmet title="註冊" meta={meta} /> <React.Fragment>{content}</React.Fragment> </React.Fragment> ); } } function mapStateToProps(state) { const { browser } = state; return { browser, isLoggedIn: getIsLoggedIn(state), }; } export default compose( hot(module), connect(mapStateToProps) )(UserSignUpPage);
src/components/ResultLoggerView.js
IUnknown68/karma-live-reporter
//============================================================================== import React, { Component } from 'react'; import attachListener from 'attachListener'; import autoScroll from 'autoScroll'; import { SPEC_COMPLETED, BROWSER_START } from 'messages'; //============================================================================== export default class ResultLoggerView extends Component { static listener = { [BROWSER_START]: function(browser) { if (browser.id === this.props.browser.id) { this.clear(); } }, [SPEC_COMPLETED]: function(browser, result) { if (browser.id === this.props.browser.id) { this.appendLog(result, true); } } }; //---------------------------------------------------------------------------- constructor(props) { super(props); autoScroll(this); attachListener(this); } //---------------------------------------------------------------------------- componentDidMount() { this.renderAllEntries(); } //---------------------------------------------------------------------------- shouldComponentUpdate(nextProps, nextState) { return false; } //---------------------------------------------------------------------------- clear() { let node = this.refs.root; while (node.firstChild) { node.removeChild(node.firstChild); } } //---------------------------------------------------------------------------- renderAllEntries() { this.currentSuite = []; this.props.entries.forEach(entry => { this.appendLog(entry, false); }); setTimeout(this.updateScroll, 10); } //---------------------------------------------------------------------------- appendLog(entry, update = false) { const entryNode = document.createElement('div'); const suite = entry.suite; let suiteChanged = false; for (let n = 0; n < suite.length; n++) { suiteChanged |= (this.currentSuite[n] !== suite[n]); if (suiteChanged) { const node = document.createElement('div'); node.style.marginLeft = `${n}em`; entryNode.appendChild(node) .appendChild(document.createTextNode(suite[n])); } } this.currentSuite = suite; this.appendLogEntry(entry, entryNode); this.refs.root.appendChild(entryNode); if (update) { this.updateScroll(); } } //---------------------------------------------------------------------------- appendLogEntry(entry, entryNode) { const node = document.createElement('div'); const className = (entry.skipped) ? 'skipped' : (entry.success) ? 'succeeded' : 'failed'; node.className = `description ${className}`; const indent = entry.suite.length; node.style.marginLeft = `${indent}em`; this.appendLogEntryIcon(className, node); node.appendChild(document.createTextNode(entry.description)); this.appendLogEntryLog(entry, node); entryNode.appendChild(node); } //---------------------------------------------------------------------------- appendLogEntryIcon(className, parentNode) { let iconClassName = 'glyphicon glyphicon-'; switch(className) { case 'skipped': iconClassName += 'minus'; break; case 'succeeded': iconClassName += 'ok'; break; case 'failed': iconClassName += 'remove'; break; } if (iconClassName) { parentNode.appendChild(document.createElement('span')) .className = iconClassName; } } //---------------------------------------------------------------------------- appendLogEntryLog(entry, parentNode) { if (!entry.log) { return; } entry.log.forEach(logEntry => { const el = document.createElement('div'); el.appendChild(document.createTextNode(logEntry)); parentNode.appendChild(el) .className = 'indent'; }); } //---------------------------------------------------------------------------- render() { return ( <div ref="root" className="logger results" /> ); } }
examples/js/column-filter/select-filter.js
powerhome/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; const qualityType = { 0: 'good', 1: 'Bad', 2: 'unknown' }; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, quality: i % 3 }); } } addProducts(5); function enumFormatter(cell, row, enumObject) { return enumObject[cell]; } export default class SelectFilter extends React.Component { render() { return ( <BootstrapTable data={ products }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='quality' filterFormatted dataFormat={ enumFormatter } formatExtraData={ qualityType } filter={ { type: 'SelectFilter', options: qualityType } }>Product Quality</TableHeaderColumn> </BootstrapTable> ); } }
apps/marketplace/components/Brief/Edit/AddSellerListItems.js
AusDTO/dto-digitalmarketplace-frontend
import React from 'react' import PropTypes from 'prop-types' const AddSellerListItems = props => { const { onSellerClick, sellers } = props return sellers.map(seller => ( <li key={seller.code}> <a href={`#${seller.code}`} onClick={e => { e.preventDefault() onSellerClick(seller.code, seller.name) }} > {seller.name} </a> </li> )) } AddSellerListItems.defaultProps = { onSellerClick: () => {}, sellers: [] } AddSellerListItems.propTypes = { onSellerClick: PropTypes.func.isRequired, sellers: PropTypes.arrayOf( PropTypes.shape({ code: PropTypes.number.isRequired, name: PropTypes.string.isRequired }) ).isRequired } export default AddSellerListItems
fields/types/azurefile/AzureFileColumn.js
ligson/keystone
import React from 'react'; var AzureFileColumn = React.createClass({ renderValue () { var value = this.props.data.fields[this.props.col.path]; if (!value) return; return <a href={value.url} target='_blank'>{value.url}</a>; }, render () { return ( <td className="ItemList__col"> <div className="ItemList__value ItemList__value--azure-file">{this.renderValue()}</div> </td> ); } }); module.exports = AzureFileColumn;
src/svg-icons/maps/directions-walk.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsDirectionsWalk = (props) => ( <SvgIcon {...props}> <path d="M13.5 5.5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zM9.8 8.9L7 23h2.1l1.8-8 2.1 2v6h2v-7.5l-2.1-2 .6-3C14.8 12 16.8 13 19 13v-2c-1.9 0-3.5-1-4.3-2.4l-1-1.6c-.4-.6-1-1-1.7-1-.3 0-.5.1-.8.1L6 8.3V13h2V9.6l1.8-.7"/> </SvgIcon> ); MapsDirectionsWalk = pure(MapsDirectionsWalk); MapsDirectionsWalk.displayName = 'MapsDirectionsWalk'; MapsDirectionsWalk.muiName = 'SvgIcon'; export default MapsDirectionsWalk;
example/src/components/SpacedSpan.js
ethanselzer/react-image-magnify
import React from 'react'; export default function SpacedSpan({ className, children }) { return ( <span className={className}> {' '}{children}{' '} </span> ); }
admin/client/App/screens/Home/index.js
brianjd/keystone
/** * The Home view is the view one sees at /keystone. It shows a list of all lists, * grouped by their section. */ import React from 'react'; import { Container, Spinner } from '../../elemental'; import { connect } from 'react-redux'; import Lists from './components/Lists'; import Section from './components/Section'; import AlertMessages from '../../shared/AlertMessages'; import { loadCounts, } from './actions'; var HomeView = React.createClass({ displayName: 'HomeView', getInitialState () { return { modalIsOpen: true, }; }, // When everything is rendered, start loading the item counts of the lists // from the API componentDidMount () { this.props.dispatch(loadCounts()); }, getSpinner () { if (this.props.counts && Object.keys(this.props.counts).length === 0 && (this.props.error || this.props.loading)) { return ( <Spinner /> ); } return null; }, render () { const spinner = this.getSpinner(); return ( <Container data-screen-id="home"> <div className="dashboard-header"> <div className="dashboard-heading">{Keystone.brand}</div> </div> <div className="dashboard-groups"> {(this.props.error) && ( <AlertMessages alerts={{ error: { error: "There is a problem with the network, we're trying to reconnect...", } }} /> )} {/* Render flat nav */} {Keystone.nav.flat ? ( <Lists counts={this.props.counts} lists={Keystone.lists} spinner={spinner} /> ) : ( <div> {/* Render nav with sections */} {Keystone.nav.sections.map((navSection) => { return ( <Section key={navSection.key} id={navSection.key} label={navSection.label}> <Lists counts={this.props.counts} lists={navSection.lists} spinner={spinner} /> </Section> ); })} {/* Render orphaned lists */} {Keystone.orphanedLists.length ? ( <Section label="Other" icon="octicon-database"> <Lists counts={this.props.counts} lists={Keystone.orphanedLists} spinner={spinner} /> </Section> ) : null} </div> )} </div> </Container> ); }, }); export { HomeView, }; export default connect((state) => ({ counts: state.home.counts, loading: state.home.loading, error: state.home.error, }))(HomeView);
index.android.js
Hey2Li/RNGD
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import Main from './app/main/GDMain' export default class RNGD extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> <Main/> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('RNGD', () => RNGD);
components/index_section_02.js
MonkingStand/MS-blog-site-v3.0
import React from 'react'; class IndexSection02 extends React.Component { render() { const css_tag_p = { marginBottom: 20, fontWeight : 300, textAlign : 'center' }; return ( <section id="main_content"> <p style = { css_tag_p }> code less,do more </p> </section> ); }; }; export default IndexSection02;
docs/src/app/components/pages/components/FlatButton/ExampleComplex.js
pomerantsev/material-ui
import React from 'react'; import FlatButton from 'material-ui/FlatButton'; import FontIcon from 'material-ui/FontIcon'; import ActionAndroid from 'material-ui/svg-icons/action/android'; const styles = { exampleImageInput: { cursor: 'pointer', position: 'absolute', top: 0, bottom: 0, right: 0, left: 0, width: '100%', opacity: 0, }, }; const FlatButtonExampleComplex = () => ( <div> <FlatButton label="Choose an Image" labelPosition="before"> <input type="file" style={styles.exampleImageInput} /> </FlatButton> <FlatButton label="Label before" labelPosition="before" primary={true} style={styles.button} icon={<ActionAndroid />} /> <FlatButton label="GitHub Link" href="https://github.com/callemall/material-ui" secondary={true} icon={<FontIcon className="muidocs-icon-custom-github" />} /> </div> ); export default FlatButtonExampleComplex;
src/js/tabscontrolled/index.js
HBM/md-components
import React from 'react' import PropTypes from 'prop-types' import classnames from 'classnames' class TabsControlled extends React.PureComponent { static propTypes = { tabs: PropTypes.array } static defaultProps = { tabs: [ 'germany', 'spain', 'sweden' ] } state = { direction: '' } componentWillReceiveProps (nextProps) { const direction = nextProps.index > this.props.index ? 'right' : 'left' this.setState({ direction }) } onClick = (event, index) => { event.preventDefault() this.props.onChange(index) } render () { const width = 100 / this.props.tabs.length const left = this.props.index * width const right = (this.props.tabs.length - this.props.index - 1) * width return ( <div className='mdc-TabsControlled'> {this.props.tabs.map((tab, index) => ( <a key={tab} onClick={event => this.onClick(event, index)} className={classnames('mdc-TabsControlled-item', { 'is-active': this.props.index === index })} href='' > {tab} </a> ))} {this.props.index === -1 ? null : ( <div className={`mdc-Tabs-InkBar transition-${this.state.direction}`} style={{ left: `${left}%`, right: `${right}%` }} /> )} </div> ) } } export default TabsControlled
src/js/components/icons/base/PlatformUnixware.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}-platform-unixware`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'platform-unixware'); 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 fillRule="evenodd" d="M11.1202881,4.92721589 L19.7127168,8.40180443 L19.7127168,4.92721589 L11.1202881,4.92721589 Z M5,4.92721589 L5,24 L8.13126023,24 L5.68766714,21.7034393 L15.7579991,10.8346606 L8.99134942,8.09586582 L10.2724516,4.92721589 L5,4.92721589 Z M9.27644581,24 L19.7127168,24 L19.7127168,12.6521027 L9.27644581,24 Z M17.6912987,2.17525891 C17.5552558,2.17525891 17.4922239,2.37433375 17.4922239,2.76212546 L17.9008578,2.76212546 C17.9008578,2.36397579 17.8379522,2.17525891 17.6912987,2.17525891 M14.9250301,3.47443696 C14.9250301,3.61073248 14.9986726,3.70483829 15.1032627,3.70483829 C15.1974948,3.70483829 15.2919796,3.62096412 15.3546326,3.46395269 L15.3546326,2.92976012 C15.0509677,3.1077401 14.9250301,3.28584639 14.9250301,3.47443696 M17.8694177,3.71547414 C18.0054606,3.71547414 18.1209139,3.64208424 18.2256303,3.50591503 L18.2256303,3.87261189 C18.0893347,3.99842315 17.9530392,4.05071819 17.7959014,4.05071819 C17.3875201,4.05071819 17.1360239,3.68402133 17.1360239,2.95062761 C17.1360239,2.26952893 17.3454567,1.85053703 17.7122799,1.85053703 C17.9324496,1.85053703 18.0577556,1.99706419 18.1417561,2.16481253 C18.2045354,2.26952893 18.2675673,2.53150939 18.2675673,3.03437546 L17.5027208,3.03437546 C17.5027208,3.47446222 17.6284057,3.71547414 17.8694177,3.71547414 L17.8694177,3.71547414 Z M17.0415392,2.3113397 C16.9889915,2.28026583 16.9474334,2.25904466 16.8844014,2.25904466 C16.6013261,2.25904466 16.4862518,2.92965907 16.4862518,3.1707973 L16.4862518,3.99842315 L16.1195549,3.99842315 L16.1195549,1.91331634 L16.4862518,1.91331634 L16.4862518,2.47934067 L16.496736,2.47934067 C16.6433895,1.97634828 16.7166531,1.88186353 16.8844014,1.88186353 C16.957665,1.88186353 17.0102127,1.89247411 17.072992,1.93428488 L17.0415392,2.3113397 Z M15.9309643,3.89358044 C15.7947951,4.00903374 15.7214052,4.05071819 15.6375311,4.05071819 C15.5119724,4.05071819 15.4177403,3.95635975 15.3756769,3.77812714 C15.239634,3.96684402 15.1033385,4.05071819 14.9671693,4.05071819 C14.7469996,4.05071819 14.5582827,3.80957995 14.5582827,3.52688358 C14.5582827,3.18115526 14.7783261,3.01340692 15.3547084,2.67803656 L15.3547084,2.47934067 C15.3547084,2.29037115 15.2920554,2.20674962 15.1347913,2.20674962 C14.9878852,2.20674962 14.8308738,2.30085543 14.6109567,2.55247794 L14.6109567,2.12300176 C14.8308738,1.92380061 14.9671693,1.85053703 15.1661178,1.85053703 C15.4387089,1.85053703 15.7214052,2.02864332 15.7214052,2.41630873 L15.7214052,3.60002084 C15.7214052,3.6945056 15.7423738,3.71547414 15.7843109,3.71547414 C15.8052794,3.71547414 15.8575744,3.68402133 15.9309643,3.61075775 L15.9309643,3.89358044 Z M13.6680039,4.04023392 L13.2382751,1.93428488 L13.2277908,1.93428488 L12.8191568,4.04023392 L12.5362078,4.04023392 L11.8763303,0.855036529 L12.2954486,0.855036529 L12.6621454,2.97159615 L12.6722507,2.97159615 L13.0914953,0.855036529 L13.3850549,0.855036529 L13.7936888,3.01340692 L14.1915858,0.855036529 L14.6213146,0.855036529 L13.9403423,4.04023392 L13.6680039,4.04023392 Z M11.4570858,3.99842315 L11.1428103,3.27538738 L10.8601139,3.99842315 L10.4720696,3.99842315 L10.9542197,2.92965907 L10.4720696,1.91331634 L10.8601139,1.91331634 L11.1428103,2.57344648 L11.4151487,1.91331634 L11.7924562,1.91331634 L11.3420115,2.92965907 L11.8448775,3.99842315 L11.4570858,3.99842315 Z M10.0846568,1.23234398 C9.95884555,1.23234398 9.86473974,1.13798554 9.86473974,1.02278487 C9.86473974,0.897099931 9.95884555,0.80274149 10.0846568,0.80274149 C10.1997312,0.80274149 10.2940896,0.897099931 10.2940896,1.02278487 C10.2940896,1.13798554 10.1997312,1.23234398 10.0846568,1.23234398 L10.0846568,1.23234398 Z M9.89606624,3.99842315 L10.2625105,3.99842315 L10.2625105,1.91319002 L9.89606624,1.91319002 L9.89606624,3.99842315 Z M9.53997997,3.99842315 L9.17315679,3.99842315 L9.17315679,2.49993026 C9.17315679,2.3220766 9.12060912,2.20674962 8.97395564,2.20674962 C8.85875497,2.20674962 8.7748808,2.29037115 8.69125927,2.45811949 L8.69125927,3.99842315 L8.32443609,3.99842315 L8.32443609,1.91331634 L8.69125927,1.91331634 L8.69125927,2.13335972 L8.70174354,2.13335972 C8.80633362,1.95525343 8.92178692,1.88186353 9.07867203,1.88186353 C9.34077882,1.88186353 9.53997997,2.08106468 9.53997997,2.49993026 L9.53997997,3.99842315 Z M7.92628642,3.19176585 C7.92628642,3.87261189 7.47571539,4.04023392 7.22447183,4.04023392 C6.83668011,4.04023392 6.52215197,3.72595841 6.52215197,3.22309234 L6.52215197,0.855036529 L6.93078592,0.855036529 L6.93078592,3.22309234 C6.93078592,3.48494649 7.02527067,3.6631791 7.22447183,3.6631791 C7.38160958,3.6631791 7.51765247,3.53749416 7.51765247,3.23357662 L7.51765247,0.855036529 L7.92628642,0.855036529 L7.92628642,3.19176585 Z M5.00003789,4.92722853 L19.7127547,4.92722853 L19.7127547,0 L5.00003789,0 L5.00003789,4.92722853 Z" opacity=".8"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'PlatformUnixware'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
lib/editor/components/editors/LogicalVariableForm.js
jirokun/survey-designer-js
/* eslint-env browser */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Panel, Button, Glyphicon, Form, Col, FormControl } from 'react-bootstrap'; import classNames from 'classnames'; import { List } from 'immutable'; import * as EditorActions from '../../actions'; class LogicalVariableForm extends Component { /** logicalVariableからstateを生成する */ static generateState(logicalVariable) { return { editMode: false, variableName: logicalVariable.getVariableName(), operands: logicalVariable.getOperands(), operators: logicalVariable.getOperators(), errorMessage: null, }; } constructor(props) { super(props); const { logicalVariable } = props; this.state = LogicalVariableForm.generateState(logicalVariable); } /** editModeの変更 */ handleSubmit(e) { e.preventDefault(); this.handleClickSave(); } /** editModeの変更 */ handleChangeEditMode(editMode) { this.setState({ editMode }); } /** LogicalVariableの変更 */ handleRemoveLogicalVariable() { const { page, logicalVariable, removeLogicalVariable } = this.props; removeLogicalVariable(page.getId(), logicalVariable.getId()); } /** LogicalVariableの変更 */ handleClickCancel() { const { logicalVariable } = this.props; this.setState(LogicalVariableForm.generateState(logicalVariable)); } /** LogicalVariableの変更 */ handleClickSave() { const { logicalVariable, page, changeLogicalVariable } = this.props; const variableName = this.state.variableName; if (!page.isUniqueLogicalVariableName(logicalVariable.getId(), variableName)) { this.setState({ errorMessage: 'ラベルが重複しています' }); return; } const invalidChars = [ { char: ' ', desc: '半角スペース' }, { char: '#', desc: '半角シャープ' }, { char: '{', desc: '半角左ブレース' }, { char: '}', desc: '半角右ブレース' }, ]; for (let i = 0; i < invalidChars.length; i++) { if (variableName.indexOf(invalidChars[i].char) !== -1) { this.setState({ errorMessage: `ラベルに使用できない文字が含まれています。<br />使用できない文字<br />${invalidChars.map(c => `'${c.char}':${c.desc}`).join('<br />')}` }); return; } } const newLogicalVariable = logicalVariable .set('variableName', this.state.variableName) .set('operands', this.state.operands) .set('operators', this.state.operators); changeLogicalVariable(page.getId(), newLogicalVariable.getId(), newLogicalVariable); this.setState({ editMode: false, errorMessage: null }); } /** 名前の変更 */ handleChangeName(variableName) { this.setState({ variableName }); } /** オペランドの追加*/ handleAddOperand(index) { const { operands, operators } = this.state; this.setState({ operands: operands.insert(index + 1, ''), operators: operators.insert(index, ''), }); } /** オペランドの削除 */ handleRemoveOperand(index) { const { operands, operators } = this.state; this.setState({ operands: operands.delete(index), operators: operators.delete(index - 1), }); } /** 式が変更されたときのハンドラ */ handleChangeExpression() { const operands = List(Array.prototype.slice.call(this.rootEl.getElementsByClassName('operand')).map(el => el.value)); const operators = List(Array.prototype.slice.call(this.rootEl.getElementsByClassName('operator')).map(el => el.value)); this.setState({ operands, operators, }); } /** 計算式部分を作成する */ createExpression(editMode, operand, operator, precedingOutputDefinitions, index) { const { logicalVariable } = this.props; const { operators } = this.state; const key = `LogicalVariableForm_${logicalVariable.getId()}_${index}`; return ( <div key={key} className="expression"> <FormControl className="operand" componentClass="select" disabled={!editMode} value={operand} onChange={() => this.handleChangeExpression()}> <option value="" /> {this.createOutputDefinitionOptions(precedingOutputDefinitions, index)} </FormControl> <Glyphicon className={classNames('clickable icon-button text-info', { invisible: !editMode })} glyph="plus-sign" onClick={() => this.handleAddOperand(index)} /> <Glyphicon className={classNames('clickable icon-button text-danger', { invisible: !editMode || index === 0 || operators.size === 1 })} glyph="remove-sign" onClick={() => this.handleRemoveOperand(index)} /> { operator !== undefined ? ( <FormControl className="operator" componentClass="select" disabled={!editMode} value={operator} onChange={() => this.handleChangeExpression()}> <option value="" /> <option value="+">+</option> <option value="-">−</option> </FormControl> ) : null } </div> ); } /** outputdefinitionのoptionを作成する */ createOutputDefinitionOptions(precedingOutputDefinitions, index) { const { logicalVariable } = this.props; return precedingOutputDefinitions.map((od, i) => { const key = `LogicalVariableForm_${logicalVariable.getId()}_${index}_${i}`; return <option key={key} value={od.getId()}>{od.getLabelWithOutputNo()}</option>; }); } /** パネルのヘッダーを作成する */ createPanelHeader(variableName) { const { survey, page } = this.props; const name = `${survey.calcPageNo(page.getId())}-L-${variableName}`; return ( <div> {name} <i className={classNames('fa fa-trash pull-right text-danger delete-button', { invisible: page.isEditDisabled() })} onClick={e => this.handleRemoveLogicalVariable(e)} /> </div> ); } render() { const { runtime, survey, page, logicalVariable } = this.props; const { editMode, variableName, operands, operators, errorMessage } = this.state; const precedingOutputDefinitions = survey.findPrecedingOutputDefinition(runtime.findCurrentNode(survey).getId(), true, false) .filter(od => od.getOutputType() === 'number') // numberのものに限る .filter(od => od.getName() !== logicalVariable.getId()); // 自分自身は除く return ( <div ref={(el) => { this.rootEl = el || this.rootEl; }}> <Panel header={this.createPanelHeader(variableName)}> <Form onSubmit={e => this.handleSubmit(e)}> <div> <Col md={3}>ラベル</Col> <Col md={9}>定義</Col> </div> <div> <Col md={3}> <FormControl type="text" value={variableName} disabled={!editMode} onChange={e => this.handleChangeName(e.target.value)} /> </Col> <Col md={9}> {operands.map((operand, i) => this.createExpression(editMode, operand, operators.get(i), precedingOutputDefinitions, i))} </Col> </div> <div> <Col md={12}> <Button disabled={page.isEditDisabled()} className={classNames('pull-right', { hidden: editMode })} bsStyle="default" onClick={() => this.handleChangeEditMode(true)}>編集</Button> <Button className={classNames('pull-right', { hidden: !editMode })} bsStyle="primary" onClick={() => this.handleClickSave(false)}>保存</Button> <Button className={classNames('pull-right', { hidden: !editMode })} onClick={() => this.handleClickCancel(false)}>キャンセル</Button> <span className="pull-right text-danger form-control-static" dangerouslySetInnerHTML={{ __html: errorMessage }} /> </Col> </div> </Form> </Panel> </div> ); } } const stateToProps = state => ({ survey: state.getSurvey(), runtime: state.getRuntime(), view: state.getViewSetting(), }); const actionsToProps = dispatch => ({ changeLogicalVariable: (pageId, logicalVariableId, logicalVariable) => dispatch(EditorActions.changeLogicalVariable(pageId, logicalVariableId, logicalVariable)), removeLogicalVariable: (pageId, logicalVariableId) => dispatch(EditorActions.removeLogicalVariable(pageId, logicalVariableId)), }); export default connect( stateToProps, actionsToProps, )(LogicalVariableForm);
src/components/GuestsTable/GuestsTable.js
joyvuu-dave/comeals-ui-react
// rendered by Guests import React from 'react' import classes from './GuestsTable.scss' // Schema import type { GuestsSchema } from '../../redux/modules/Guests' import type { ResidentsSchema } from '../../redux/modules/Residents' type Props = { ui: { veg_checkbox_disabled: boolean, remove_button_disabled: boolean }, actions: { remove: Function, toggleVeg: Function }, guests: GuestsSchema, residents: ResidentsSchema }; export class GuestsTable extends React.Component<void, Props, void> { constructor () { super() this.handleToggleVeg = this.handleToggleVeg.bind(this) this.handleGuestRemove = this.handleGuestRemove.bind(this) } handleToggleVeg (e) { this.props.actions.toggleVeg({cid: e.target.value}) } handleGuestRemove (e) { this.props.actions.remove({cid: e.target.value}) } renderHost (id) { return this.props.residents.find((resident) => { return resident.id === id }).name } renderCategory (val) { if (val === 1) { return 'Child' } else { return 'Adult' } } renderGuests () { return this.props.guests.map((g) => <tr key={g.cid} className={classes.guest}> <td>{this.renderHost(g.resident_id)}</td> <td>{this.renderCategory(g.multiplier)}</td> <td> <input value={g.cid} disabled={this.props.ui.veg_checkbox_disabled} type='checkbox' checked={g.vegetarian} onChange={this.handleToggleVeg} /> </td> <td> <button value={g.cid} disabled={this.props.ui.remove_button_disabled} type='button' onClick={this.handleGuestRemove}>- Guest</button> </td> </tr> ) } render () { return ( <table className={classes['guests-table']}> <thead> <tr> <th>Host</th> <th>Category</th> <th>Vegetarian</th> <th></th> </tr> </thead> <tbody> {this.renderGuests()} </tbody> </table> ) } } export default GuestsTable
packages/bonde-admin/src/storybook/forms/createForm.spec.js
ourcities/rebu-client
import React from 'react' import { expect } from 'chai' import { shallow } from 'enzyme' import { subscribe, createForm } from './createForm' describe('createForm API', () => { describe('subscribe', () => { const callToAction = 'CALL_TO_ACTION' const globalState = {} const globalOwnProps = { widget: { settings: { callToAction } } } const intl = Component => Component describe('should map initialValues in HOC props when', () => { let param const HOC = (configForm, mapStateToProps) => () => { param = mapStateToProps } it('is function', () => { const initialValues = (state, ownProps) => ({ ...ownProps.widget.settings }) subscribe(intl, HOC)({ initialValues }) expect(param(globalState, globalOwnProps)).to.deep.equal({ initialValues: globalOwnProps.widget.settings }) }) it('is object', () => { const initialValues = { ...globalOwnProps.widget.settings } subscribe(intl, HOC)({ initialValues }) expect(param()).to.deep.equal({ initialValues: globalOwnProps.widget.settings }) }) }) it('should map submit in HOC props', () => { let param const HOC = (configForm, mapStateToProps, mapActionsToProps) => () => { const dispatch = f => { param = f } mapActionsToProps(dispatch).submit() } const submit = () => 'submit' subscribe(intl, HOC)({ submit }) expect(param).to.equal('submit') }) it('should map form props like name, fields and validate', () => { let param const HOC = (configForm) => () => { param = configForm } const settings = { name: 'testForm', fields: ['name', 'email'], validate: () => 'validate' } subscribe(intl, HOC)(settings) expect(param.form).to.equal(settings.name) expect(param.fields).to.deep.equal(settings.fields) expect(param.validate()).to.equal('validate') }) describe('decorate component like FormProvider', () => { const HOC = () => Component => Component it('should decorate a form like default', () => { const Form = subscribe(intl, HOC)({}) expect(Form.displayName).to.equal('createForm(form)') }) it('should decorate configured component', () => { const CustomForm = () => <div /> const Form = subscribe(intl, HOC)({ component: CustomForm }) expect(Form.displayName).to.equal('createForm(CustomForm)') }) }) }) describe('createForm', () => { it('should connect with reduxForm and react-intl', () => { const mock = message => message const intl = { now: mock, formatMessage: mock, formatDate: mock, formatTime: mock, formatRelative: mock, formatNumber: mock, formatPlural: mock, formatHTMLMessage: mock } const Form = createForm({ name: 'testForm', fields: ['name'], submit: () => 'submit' }) const wrapper = shallow(<Form />, { context: { intl } }) // expect(wrapper.name()).to.equal('ReduxFormConnector(createForm(form))') expect(wrapper.name()).to.equal('ConnectedForm') }) }) })
app/components/ShopPage/ShopPage.js
tenhaus/bbwelding
import React from 'react'; import Radium from 'radium'; import _ from 'lodash'; import RetinaImage from 'react-retina-image'; import isRetina from 'is-retina'; import Style from './_ShopPage.style.js'; import Page from '../Page/Page'; import ContentfulEntryStore from '../../stores/ContentfulEntryStore'; import ShopListItemRenderer from '../ShopListItemRenderer/ShopListItemRenderer'; import AltActions from '../../actions/AltActions'; var Markdown = require( "markdown" ).markdown; class ShopPage extends React.Component { constructor() { super(); this.onChange = this.onChange.bind(this); this.onMouseOver = this.onMouseOver.bind(this); this.onMouseOut = this.onMouseOut.bind(this); this.renderMobileListItems = this.renderMobileListItems.bind(this); this.onMobileShopItemChanged = this.onMobileShopItemChanged.bind(this); this.state = { entryStore: ContentfulEntryStore.getState(), showSecondary: false }; } onMouseOver() { this.setState({showSecondary: true}); } onMouseOut() { this.setState({showSecondary: false}); } componentDidMount() { ContentfulEntryStore.listen(this.onChange); } componentWillUnmount() { ContentfulEntryStore.unlisten(this.onChange); } onChange(entryStore) { this.setState({ entryStore: entryStore }); } onMobileShopItemChanged(event) { var name = event.target.value; var item = _.findWhere(this.state.entryStore.shop, {fields: {name: name}}); AltActions.setSelectedShopItem(item); } renderListItems() { return _.map(this.state.entryStore.shop, item => { return <ShopListItemRenderer key={item.fields.name} item={item} />; }); } renderMobileListItems() { var self = this; var selectedShopItemName = self.state.entryStore.selectedShopItem.fields.name; return _.map(this.state.entryStore.shop, item => { let option = ( <option key={item.fields.name} value={item.fields.name}> {item.fields.name} </option> ); if(selectedShopItemName === item.fields.name) { option = ( <option selected key={item.fields.name} value={item.fields.name}> {item.fields.name} </option> ); } return option; }); } render() { let listItems = this.renderListItems(); let mobileListItems = this.renderMobileListItems(); let item = this.state.entryStore.selectedShopItem; let html = Markdown.toHTML(item.fields.name); let profileImage = null; if(item.fields.primaryImage) { profileImage = item.fields.primaryImage.fields.file.url; profileImage += '?w=600&fm=jpg&q=75'; } if(this.state.showSecondary && item.fields.secondaryImage) { profileImage = item.fields.secondaryImage.fields.file.url; profileImage += '?w=600&fm=jpg&q=75'; } return ( <Page title='Our Shop'> <div style={Style.topSection} key='top'> <p>Bluebeam, SDS/2, Fabsuite and P2 systems, Infosight Corp, Shop Data, and Peddinghaus equipment are all part of what makes our jobs run smoothly through the shop.</p> </div> <div style={Style.split} key='split'> <div className='shopItem' style={Style.profile} key='profile'> <select style={Style.mobileTeamList} key='mobile-nav' onChange={this.onMobileShopItemChanged}> {mobileListItems} </select> {/* Profile */} <div onMouseOver={this.onMouseOver} onMouseOut={this.onMouseOut}> <img src={profileImage} style={Style.profileImage} /> <div dangerouslySetInnerHTML={{__html:html}}></div> </div> </div> {/* Shop list */} <div className='team'> <ul style={Style.teamList}> {listItems} </ul> </div> </div> </Page> ); } } export default Radium(ShopPage);
imports/ui/pages/ResetPassword/ResetPassword.js
lazygalaxy/lazybat-seed-meteorjs
import React from 'react'; import PropTypes from 'prop-types'; import { Row, Col, Alert, FormGroup, ControlLabel, Button } from 'react-bootstrap'; import { Accounts } from 'meteor/accounts-base'; import { Bert } from 'meteor/themeteorchef:bert'; import validate from '../../../modules/validate'; class ResetPassword extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } componentDidMount() { const component = this; validate(component.form, { rules: { newPassword: { required: true, minlength: 6, }, repeatNewPassword: { required: true, minlength: 6, equalTo: '[name="newPassword"]', }, }, messages: { newPassword: { required: 'Enter a new password, please.', minlength: 'Use at least six characters, please.', }, repeatNewPassword: { required: 'Repeat your new password, please.', equalTo: 'Hmm, your passwords don\'t match. Try again?', }, }, submitHandler() { component.handleSubmit(); }, }); } handleSubmit() { const { match, history } = this.props; const token = match.params.token; Accounts.resetPassword(token, this.newPassword.value, (error) => { if (error) { Bert.alert(error.reason, 'danger'); } else { history.push('/documents'); } }); } render() { return (<div className="ResetPassword"> <Row> <Col xs={12} sm={6} md={4}> <h4 className="page-header">Reset Password</h4> <Alert bsStyle="info"> To reset your password, enter a new one below. You will be logged in with your new password. </Alert> <form ref={form => (this.form = form)} onSubmit={event => event.preventDefault()}> <FormGroup> <ControlLabel>New Password</ControlLabel> <input type="password" className="form-control" ref={newPassword => (this.newPassword = newPassword)} name="newPassword" placeholder="New Password" /> </FormGroup> <FormGroup> <ControlLabel>Repeat New Password</ControlLabel> <input type="password" className="form-control" ref={repeatNewPassword => (this.repeatNewPassword = repeatNewPassword)} name="repeatNewPassword" placeholder="Repeat New Password" /> </FormGroup> <Button type="submit" bsStyle="success">Reset Password &amp; Login</Button> </form> </Col> </Row> </div>); } } ResetPassword.propTypes = { match: PropTypes.object.isRequired, history: PropTypes.object.isRequired, }; export default ResetPassword;
app/src/GenericTable.js
CovertIII/hledger-node-server
import React from 'react'; import R from 'ramda'; const defaultArray = []; const thStyle = { 'textAlign': 'left', 'verticalAlign': 'bottom', 'padding': '8px 8px 8px 0px', 'borderBottomStyle': 'solid', 'borderBottomWidth': '2px', 'borderColor': 'inherit' }; const Header = ({header = defaultArray}) => ( <thead> <tr> { header.map( h => <th style={thStyle}>{ h }</th> ) } </tr> </thead> ); const tdStyle = { 'textAlign': 'left', 'verticalAlign': 'bottom', 'padding': '8px 8px 8px 0px', 'borderColor': 'inherit' }; const Body = ({data = defaultArray}) => ( <tbody> { data.map( (d = defaultArray) => ( <tr> { d.map( (h, i) => <td style={tdStyle}>{ h }</td> )} </tr> ))} </tbody> ) const tableStyle = { fontSize: '14px', lineHeight: '1.25', borderCollapse: 'separate', borderSpacing: '0px', width: '100%' }; export const GenericTable = ({data = defaultArray}) => ( <table style={tableStyle}> <Header header={R.head(data)}/> <Body data={R.tail(data)}/> </table> );
app/components/navigation/personality/PersonalityLinks.js
VasilyShelkov/Vasily
import React, { Component } from 'react'; import Letter from './Letter'; class PersonalityLinks extends Component { render() { var openCB='{'; var closedCB = '}'; var personalities = ['Developer,','Explorer, ','Early-Adopter, ','Anime-Lover'].map((personality, index) => { var personalityLetters = personality.split('').map((letter, index) => { return ( <Letter letter={letter} key={index}/> ); }); var noComma = personality.replace(',', ''); return ( <a key={index} href={`#profile/${noComma}`}> {personalityLetters} </a> ); }); return ( <div id="personalities" className="flow-text col-xs-10 center-align valign"> {openCB} {personalities} {closedCB} </div> ); } } export default PersonalityLinks;
app/javascript/mastodon/features/ui/components/tabs_bar.js
h3zjp/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { NavLink, withRouter } from 'react-router-dom'; import { FormattedMessage, injectIntl } from 'react-intl'; import { debounce } from 'lodash'; import { isUserTouching } from '../../../is_mobile'; import Icon from 'mastodon/components/icon'; import NotificationsCounterIcon from './notifications_counter_icon'; export const links = [ <NavLink className='tabs-bar__link' to='/timelines/home' data-preview-title-id='column.home' data-preview-icon='home' ><Icon id='home' fixedWidth /><FormattedMessage id='tabs_bar.home' defaultMessage='Home' /></NavLink>, <NavLink className='tabs-bar__link' to='/notifications' data-preview-title-id='column.notifications' data-preview-icon='bell' ><NotificationsCounterIcon /><FormattedMessage id='tabs_bar.notifications' defaultMessage='Notifications' /></NavLink>, <NavLink className='tabs-bar__link' exact to='/timelines/public' data-preview-title-id='column.public' data-preview-icon='globe' ><Icon id='globe' fixedWidth /><FormattedMessage id='tabs_bar.federated_timeline' defaultMessage='Federated' /></NavLink>, <NavLink className='tabs-bar__link optional' to='/search' data-preview-title-id='tabs_bar.search' data-preview-icon='bell' ><Icon id='search' fixedWidth /><FormattedMessage id='tabs_bar.search' defaultMessage='Search' /></NavLink>, <NavLink className='tabs-bar__link' style={{ flexGrow: '0', flexBasis: '30px' }} to='/getting-started' data-preview-title-id='getting_started.heading' data-preview-icon='bars' ><Icon id='bars' fixedWidth /></NavLink>, ]; export function getIndex (path) { return links.findIndex(link => link.props.to === path); } export function getLink (index) { return links[index].props.to; } export default @injectIntl @withRouter class TabsBar extends React.PureComponent { static propTypes = { intl: PropTypes.object.isRequired, history: PropTypes.object.isRequired, } setRef = ref => { this.node = ref; } handleClick = (e) => { // Only apply optimization for touch devices, which we assume are slower // We thus avoid the 250ms delay for non-touch devices and the lag for touch devices if (isUserTouching()) { e.preventDefault(); e.persist(); requestAnimationFrame(() => { const tabs = Array(...this.node.querySelectorAll('.tabs-bar__link')); const currentTab = tabs.find(tab => tab.classList.contains('active')); const nextTab = tabs.find(tab => tab.contains(e.target)); const { props: { to } } = links[Array(...this.node.childNodes).indexOf(nextTab)]; if (currentTab !== nextTab) { if (currentTab) { currentTab.classList.remove('active'); } const listener = debounce(() => { nextTab.removeEventListener('transitionend', listener); this.props.history.push(to); }, 50); nextTab.addEventListener('transitionend', listener); nextTab.classList.add('active'); } }); } } render () { const { intl: { formatMessage } } = this.props; return ( <div className='tabs-bar__wrapper'> <nav className='tabs-bar' ref={this.setRef}> {links.map(link => React.cloneElement(link, { key: link.props.to, onClick: this.handleClick, 'aria-label': formatMessage({ id: link.props['data-preview-title-id'] }) }))} </nav> <div id='tabs-bar__portal' /> </div> ); } }
service/client/src/index.js
lwoites/unq-cloudsystems
import Application from './Application'; import './index.css'; import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( <Application></Application>, document.getElementById('root') );
packages/material-ui-icons/src/VideogameAsset.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let VideogameAsset = props => <SvgIcon {...props}> <path d="M21 6H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-10 7H8v3H6v-3H3v-2h3V8h2v3h3v2zm4.5 2c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4-3c-.83 0-1.5-.67-1.5-1.5S18.67 9 19.5 9s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z" /> </SvgIcon>; VideogameAsset = pure(VideogameAsset); VideogameAsset.muiName = 'SvgIcon'; export default VideogameAsset;
docs/app/Examples/modules/Search/index.js
vageeshb/Semantic-UI-React
import React from 'react' import Types from './Types' import Variations from './Variations' const SearchExamples = () => ( <div> <Types /> <Variations /> </div> ) export default SearchExamples
app/components/Link/index.js
minhnhat09/scalable-react
/** * * Link * */ import React from 'react'; import styles from './styles.css'; function Link({link}) { return ( <div className={styles.link}> <div className={styles.votingContainer}> <div className={styles.votingCount}> {link.voteCount} </div> </div> <div className={styles.detailsContainer}> <div> <a href={link.url} className={styles.linkAnchor}>{link.url}</a> </div> <div className={styles.description}> {link.description} </div> </div> </div> ); } Link.propTypes = { link: React.PropTypes.shape({ description: React.PropTypes.string.isRequired, url: React.PropTypes.string.isRequired, id: React.PropTypes.string.isRequired, }), }; export default Link;
components/Input/stories.js
insane-ux/rebulma
// @flow import React from 'react' import { storiesOf } from '@kadira/storybook' import Label from 'components/Label' import Input from './' storiesOf('Input', module).add('all', () => ( <div className="box"> <Label>default</Label> <Input /> <Label>small</Label> <Input theme={{ input: 'is-small' }} /> <Label>loading</Label> <Input className="is-loading" /> <Label>read only</Label> <Input readOnly /> <Label>disabled</Label> <Input disabled /> <Label>with left icon</Label> <Input leftIcon="fa-pencil-square-o" theme={{ input: 'is-large' }} /> <Label>with right icon</Label> <Input rightIcon="fa-pencil-square-o" theme={{ input: 'is-small', leftIcon: 'is-small' }} /> <Label>with color</Label> <Input rightIcon="fa-pencil-square-o" theme={{ input: 'is-danger' }} /> <Label>with both icon</Label> <Input leftIcon="fa-pencil-square-o" rightIcon="fa-check" theme={{ leftIcon: 'is-small' }} /> </div> ))
tools/template/index/container/index.js
SteamerTeam/steamer-react
import React, { Component } from 'react'; import Connect from '../connect/connect'; import { } from 'page/common/constants/cgiPath'; import { } from '../constants/constants'; import './index.less'; class Wrapper extends Component { constructor(props, context) { super(props, context); this.state = {}; } componentDidMount() { } render() { return ( <div>hello world</div> ); } } export default Connect(Wrapper);
tp-react/src/App.js
detienne11/imie
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Test from './Test'; class App extends Component { constructor(props){ super(props); console.log("App : constructor"); console.log("App: props", props); } componentWillMount(){ console.log("App : componentWillMount"); } componentDidMount() { console.log("App : componentDidMount"); } render() { console.log("App : render"); return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2 style={{color: this.props.color}}>Salut to React</h2> </div> <p className="App-intro"> <Test /> </p> </div> ); } } export default App;
public/js/cat_source/es6/components/icons/Icon3Dots.js
matecat/MateCat
import React from 'react' const Icon3Dots = () => { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="5 5 32 32"> <g fill="#fff" fillRule="evenodd" transform="translate(9 9)"> <circle cx="12.5" cy="2.5" r="2.5" /> <circle cx="12.5" cy="21.5" r="2.5" /> <circle cx="12.5" cy="12.5" r="2.5" /> </g> </svg> ) } export default Icon3Dots
templates/rubix/rubix-bootstrap/src/Button.js
jeffthemaximum/Teachers-Dont-Pay-Jeff
import React from 'react'; import classNames from 'classnames'; import RButton from 'react-bootstrap/lib/Button'; var expectedTypes = ["success", "warning", "danger", "info", "default", "primary", "link"]; function isBtnOfType(type) { for (var i = 0; i < expectedTypes.length; i++) { if (expectedTypes[i] === type) { return true; } } return false; } export default class Button extends React.Component { static propTypes = { xs: React.PropTypes.bool, sm: React.PropTypes.bool, lg: React.PropTypes.bool, rounded: React.PropTypes.bool, onlyOnHover: React.PropTypes.bool, retainBackground: React.PropTypes.bool, inverse: React.PropTypes.bool, outlined: React.PropTypes.bool, }; render() { let props = {...this.props}; if (props.close) { console.error('Button "close" prop has been deprecated in Rubix v4.0.0'); } if (props.xs) { props.bsSize = 'xsmall'; delete props.xs; } if (props.sm) { props.bsSize = 'small'; delete props.sm; } if (props.lg) { props.bsSize = 'large'; delete props.lg; } if (props.hasOwnProperty('bsStyle') && typeof props.bsStyle === 'string') { var styles = props.bsStyle.split(/\s|\,/mgi).filter((a) => a); for (var i = 0; i < styles.length; i++) { if (isBtnOfType(styles[i])) { props.bsStyle = styles[i]; } else { props.className = classNames(props.className, 'btn-' + styles[i]); props.bsStyle = 'default'; } } } if (props.retainBackground) { props.className = classNames(props.className, 'btn-retainBg'); } if (props.rounded) { props.className = classNames(props.className, 'btn-rounded'); } if (props.onlyOnHover) { props.className = classNames(props.className, 'btn-onlyOnHover'); } if (props.inverse || props.retainBackground) { props.className = classNames(props.className, 'btn-inverse'); } if (props.outlined || props.onlyOnHover || props.inverse || props.retainBackground) { props.className = classNames(props.className, 'btn-outlined'); } delete props.retainBackground; delete props.rounded; delete props.onlyOnHover; delete props.inverse; delete props.outlined; return ( <RButton {...props} /> ); } }
src/routes/UIElement/search/index.js
cuijiaxu/react-front
import React from 'react' import { Search } from '../../../components' import { Table, Row, Col, Card } from 'antd' const SearchPage = () => <div className="content-inner"> <Row gutter={32}> <Col lg={8} md={12}> <Card title="默认"> <Search /> </Card> </Col> <Col lg={8} md={12}> <Card title="附带选择"> <Search {...{ select: true, selectOptions: [ { value: 'components', name: '组件' }, { value: 'page', name: '页面' }, ], selectProps: { defaultValue: 'components', }, }} /> </Card> </Col> <Col lg={8} md={12}> <Card title="大小"> <Search size="large" style={{ marginBottom: 16 }} /> <Search size="small" /> </Card> </Col> </Row> <h2 style={{ margin: '16px 0' }}>Props</h2> <Row> <Col lg={18} md={24}> <Table rowKey={(record, key) => key} pagination={false} bordered scroll={{ x: 800 }} columns={[ { title: '参数', dataIndex: 'props', }, { title: '说明', dataIndex: 'desciption', }, { title: '类型', dataIndex: 'type', }, { title: '默认值', dataIndex: 'default', }, ]} dataSource={[ { props: 'size', desciption: '设置Search大小,可选值为 【small】 【large】 或者不设', type: 'String', default: '-', }, { props: 'select', desciption: '设置是否有选择器', type: 'Boolean', default: 'false', }, { props: 'selectOptions', desciption: '选择器的选项,格式为[{name:"",value:""}]或者[{value:""}]', type: 'Array', default: '-', }, { props: 'selectProps', desciption: '选择器的属性,可参考antd的【Select】组件', type: 'Object', default: '-', }, { props: 'onSearch', desciption: '点击搜索按钮, 按Enter键或者点击清除时的回调', type: 'Function({keyword:string,field:string})', default: '-', }, ]} /> </Col> </Row> </div> export default SearchPage
app/react-icons/fa/maxcdn.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaMaxcdn extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m39.5 17.3l-3.7 17h-7.5l4-18.6q0.3-1.2-0.3-1.9-0.6-0.8-1.9-0.8h-3.8l-4.5 21.3h-7.5l4.6-21.3h-6.4l-4.5 21.3h-7.5l4.6-21.3-3.5-7.3h28.5q2.3 0 4.2 0.9t3.3 2.6q1.4 1.6 1.9 3.7t0 4.4z"/></g> </IconBase> ); } }
app/javascript/mastodon/components/intersection_observer_article.js
glitch-soc/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import scheduleIdleTask from '../features/ui/util/schedule_idle_task'; import getRectFromEntry from '../features/ui/util/get_rect_from_entry'; // Diff these props in the "unrendered" state const updateOnPropsForUnrendered = ['id', 'index', 'listLength', 'cachedHeight']; export default class IntersectionObserverArticle extends React.Component { static propTypes = { intersectionObserverWrapper: PropTypes.object.isRequired, id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), index: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), listLength: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), saveHeightKey: PropTypes.string, cachedHeight: PropTypes.number, onHeightChange: PropTypes.func, children: PropTypes.node, }; state = { isHidden: false, // set to true in requestIdleCallback to trigger un-render } shouldComponentUpdate (nextProps, nextState) { const isUnrendered = !this.state.isIntersecting && (this.state.isHidden || this.props.cachedHeight); const willBeUnrendered = !nextState.isIntersecting && (nextState.isHidden || nextProps.cachedHeight); if (!!isUnrendered !== !!willBeUnrendered) { // If we're going from rendered to unrendered (or vice versa) then update return true; } // If we are and remain hidden, diff based on props if (isUnrendered) { return !updateOnPropsForUnrendered.every(prop => nextProps[prop] === this.props[prop]); } // Else, assume the children have changed return true; } componentDidMount () { const { intersectionObserverWrapper, id } = this.props; intersectionObserverWrapper.observe( id, this.node, this.handleIntersection, ); this.componentMounted = true; } componentWillUnmount () { const { intersectionObserverWrapper, id } = this.props; intersectionObserverWrapper.unobserve(id, this.node); this.componentMounted = false; } handleIntersection = (entry) => { this.entry = entry; scheduleIdleTask(this.calculateHeight); this.setState(this.updateStateAfterIntersection); } updateStateAfterIntersection = (prevState) => { if (prevState.isIntersecting !== false && !this.entry.isIntersecting) { scheduleIdleTask(this.hideIfNotIntersecting); } return { isIntersecting: this.entry.isIntersecting, isHidden: false, }; } calculateHeight = () => { const { onHeightChange, saveHeightKey, id } = this.props; // save the height of the fully-rendered element (this is expensive // on Chrome, where we need to fall back to getBoundingClientRect) this.height = getRectFromEntry(this.entry).height; if (onHeightChange && saveHeightKey) { onHeightChange(saveHeightKey, id, this.height); } } hideIfNotIntersecting = () => { if (!this.componentMounted) { return; } // When the browser gets a chance, test if we're still not intersecting, // and if so, set our isHidden to true to trigger an unrender. The point of // this is to save DOM nodes and avoid using up too much memory. // See: https://github.com/mastodon/mastodon/issues/2900 this.setState((prevState) => ({ isHidden: !prevState.isIntersecting })); } handleRef = (node) => { this.node = node; } render () { const { children, id, index, listLength, cachedHeight } = this.props; const { isIntersecting, isHidden } = this.state; if (!isIntersecting && (isHidden || cachedHeight)) { return ( <article ref={this.handleRef} aria-posinset={index + 1} aria-setsize={listLength} style={{ height: `${this.height || cachedHeight}px`, opacity: 0, overflow: 'hidden' }} data-id={id} tabIndex='0' > {children && React.cloneElement(children, { hidden: true })} </article> ); } return ( <article ref={this.handleRef} aria-posinset={index + 1} aria-setsize={listLength} data-id={id} tabIndex='0'> {children && React.cloneElement(children, { hidden: false })} </article> ); } }
test/PageHeaderSpec.js
snadn/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import PageHeader from '../src/PageHeader'; describe('PageHeader', function () { it('Should output a div with content', function () { let instance = ReactTestUtils.renderIntoDocument( <PageHeader> <strong>Content</strong> </PageHeader> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong')); }); it('Should have a page-header class', function () { let instance = ReactTestUtils.renderIntoDocument( <PageHeader> Content </PageHeader> ); assert.ok(React.findDOMNode(instance).className.match(/\bpage-header\b/)); }); });
src/layouts/index.js
matchilling/com-matchilling
import React from 'react' import { Container } from 'react-responsive-grid' import Fullscreen from './../components/fullscreen/' import { rhythm, scale } from './../utils/typography' // Import typefaces import 'typeface-montserrat' import 'typeface-merriweather' import './prism.css' import './util.css' export default class Template extends React.Component { render() { const { location, children } = this.props, rootPath = typeof __PREFIX_PATHS__ !== `undefined` && __PREFIX_PATHS__ ? __PATH_PREFIX__ + `/` : `/` return ( <div> {location.pathname === rootPath && ( <div> <Fullscreen /> {children()} </div> )} {location.pathname !== rootPath && ( <div> <div style={{ borderWidth: `${rhythm(0.3)}`, borderTopStyle: `solid`, }} /> <Container style={{ maxWidth: rhythm(22), padding: `${rhythm(1.5)} ${rhythm(3 / 4)}`, }} > <h3 style={{ fontFamily: 'Montserrat, sans-serif', marginTop: 0, marginBottom: rhythm(-1), }} > <a style={{ boxShadow: 'none', color: 'inherit', marginRight: rhythm(0.2), textDecoration: 'none', }} href={'/'} > Home </a> {'/contact/' === location.pathname && ( <span> <span style={{ boxShadow: 'none', color: 'hsla(0,0%,0%,0.5)', marginRight: rhythm(0.2), textDecoration: 'none', }} > / </span> Contact </span> )} {'/project/' === location.pathname && ( <span> <span style={{ boxShadow: 'none', color: 'hsla(0,0%,0%,0.5)', marginRight: rhythm(0.2), textDecoration: 'none', }} > / </span> Project </span> )} {-1 === ['/contact/', '/project/', rootPath].indexOf( location.pathname, ) && ( <span> <span style={{ boxShadow: 'none', color: 'hsla(0,0%,0%,0.5)', marginRight: rhythm(0.2), textDecoration: 'none', }} > / </span> <a style={{ boxShadow: 'none', color: 'inherit', textDecoration: 'none', }} href={'/blog/'} > Blog </a> </span> )} </h3> {children()} </Container> </div> )} </div> ) } }
src/components/SideBarNavigation.js
tofuness/Toshocat
import React from 'react'; import { Link } from 'react-router'; const SideBarNavigation = () => { return ( <div className="sidebar-navigation"> <div className="sidebar-navigation-label"> Main </div> <div className="sidebar-navigation-link"> <Link to="/animelist" activeClassName="active"> <span className="icon-three-bars"></span>Anime list </Link> </div> <div className="sidebar-navigation-link"> <Link to="/mangalist" activeClassName="active"> <span className="icon-three-bars"></span>Manga list </Link> </div> <div className="sidebar-navigation-spacer"></div> <div className="sidebar-navigation-label"> Browse </div> <div className="sidebar-navigation-link"> <Link to="/calendar" activeClassName="active"> <span className="icon-calendar"></span>Calendar </Link> </div> <div className="sidebar-navigation-link hide"> <Link to="/chart" activeClassName="active"> <span className="icon-map"></span>Season Charts </Link> </div> <div className="sidebar-navigation-link"> <Link to="/search" activeClassName="active"> <span className="icon-search"></span>Search </Link> </div> <div className="sidebar-navigation-spacer"></div> <div className="sidebar-navigation-label"> System </div> <div className="sidebar-navigation-link"> <Link to="/settings" activeClassName="active"> <span className="icon-gear"></span>Settings </Link> </div> </div> ); }; export default SideBarNavigation;
src/js/components/plan/PlanFilesTab.js
knowncitizen/tripleo-ui
/** * Copyright 2017 Red Hat Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import ClassNames from 'classnames'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import React from 'react'; import { Set } from 'immutable'; import FileList from './FileList'; const PlanFilesTab = ({ active, ...rest }) => ( <div className={ClassNames({ 'tab-pane': true, active: active })}> <FileList {...rest} /> </div> ); PlanFilesTab.propTypes = { active: PropTypes.bool.isRequired, planFiles: ImmutablePropTypes.set.isRequired, selectedFiles: PropTypes.array.isRequired }; PlanFilesTab.defaultProps = { active: false, planFiles: Set() }; export default PlanFilesTab;
src/components/FAQ/List/List-story.js
Tarabyte/foodlr-web
import React from 'react' import { storiesOf } from '@kadira/storybook' import List from './List' const questions = [ { question: 'sdfsdf', answer: '<p>sdfsddsffd</p>', id: '54dbb245f08e85d01b3ef0ec' }, { question: 'fds', answer: '<p>sdfsdfsdffsfdsd</p>', id: '54dbaf16f08e85d01b3ef0eb' }, { question: 'sdfsd', answer: '<p>sdfsdfsd</p>', id: '54dbb45715240be82738d98e' }, { question: 'sdfsdf', answer: '<p>sdfsdfsdf</p>', id: '54dbb2f6f08e85d01b3ef0ed' } ] storiesOf('FAQ-List', module) .add('Empty', () => <List questions={[]} />) .add('With questions', () => <List questions={questions} />)
src/js/components/Dashboard.js
varmais/spteefu
import React from 'react'; import Header from './Header'; import Sidebar from './Sidebar'; import AlbumList from './AlbumList'; import ArtistStore from '../stores/ArtistStore'; import ArtistService from '../services/ArtistService'; import AlbumStore from '../stores/AlbumStore'; import AlbumService from '../services/AlbumService'; class Dashboard extends React.Component { constructor() { super(); this.state = { artists: this._getArtists(), albums: this._getAlbums() }; } componentDidMount() { if (!this.state.artists.length) { this._requestArtists(); } ArtistStore.addChangeListener(this._onChange.bind(this)); AlbumStore.addChangeListener(this._onChange.bind(this)); } componentWillUnmount() { ArtistStore.removeChangeListener(this._onChange.bind(this)); AlbumStore.removeChangeListener(this._onChange.bind(this)); } _onChange() { var artists = this._getArtists(); var albums = this._getAlbums(); this.setState({artists, albums}); } _requestArtists() { ArtistService.getArtists(); } _getArtists() { return ArtistStore.artists; } _getAlbums() { return AlbumStore.albums; } render() { return ( <div className="dashboard-container"> <Header /> <Sidebar artists={this.state.artists} /> <AlbumList albums={this.state.albums} /> </div> ); } } export default Dashboard;
app/containers/HomePage/index.js
rhenderson07/react-lightning-talk
/* * HomePage * * This is the first thing users see of our App, at the '/' 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 HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
src/index.js
azimitina/post-list-redux
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { BrowserRouter, Route, Switch } from 'react-router-dom' import promise from 'redux-promise' import reducers from './reducers' import PostsIndex from './components/posts_index' import PostsNew from './components/posts_new' import PostsShow from './components/posts_show' const createStoreWithMiddleware = applyMiddleware(promise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <BrowserRouter> <div> <Switch> <Route path="/posts/new" component={PostsNew} /> <Route path="/posts/:id" component={PostsShow} /> <Route path="/" component={PostsIndex} /> </Switch> </div> </BrowserRouter> </Provider> , document.querySelector('.container'));
src/components/base/NotFoundPage.js
GHImplementationTeam/FrontEnd
import React from 'react'; const NotFoundPage = () => ( <div> <div> 404 Page Not Found </div> </div> ); export default NotFoundPage;
docs/app/Examples/elements/Label/Types/LabelExampleImageColored.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Label } from 'semantic-ui-react' const LabelExampleImage = () => ( <div> <Label as='a' color='blue' image> <img src='http://semantic-ui.com/images/avatar/small/veronika.jpg' /> Veronika <Label.Detail>Friend</Label.Detail> </Label> <Label as='a' color='teal' image> <img src='http://semantic-ui.com/images/avatar/small/jenny.jpg' /> Veronika <Label.Detail>Friend</Label.Detail> </Label> <Label as='a' color='yellow' image> <img src='http://semantic-ui.com/images/avatar/small/christian.jpg' /> Helen <Label.Detail>Co-worker</Label.Detail> </Label> </div> ) export default LabelExampleImage
blueocean-material-icons/src/js/components/svg-icons/image/rotate-right.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageRotateRight = (props) => ( <SvgIcon {...props}> <path d="M15.55 5.55L11 1v3.07C7.06 4.56 4 7.92 4 12s3.05 7.44 7 7.93v-2.02c-2.84-.48-5-2.94-5-5.91s2.16-5.43 5-5.91V10l4.55-4.45zM19.93 11c-.17-1.39-.72-2.73-1.62-3.89l-1.42 1.42c.54.75.88 1.6 1.02 2.47h2.02zM13 17.9v2.02c1.39-.17 2.74-.71 3.9-1.61l-1.44-1.44c-.75.54-1.59.89-2.46 1.03zm3.89-2.42l1.42 1.41c.9-1.16 1.45-2.5 1.62-3.89h-2.02c-.14.87-.48 1.72-1.02 2.48z"/> </SvgIcon> ); ImageRotateRight.displayName = 'ImageRotateRight'; ImageRotateRight.muiName = 'SvgIcon'; export default ImageRotateRight;
app/components/FacetList/index.js
interra/data-generate
import React from 'react'; import PropTypes from 'prop-types'; import List from 'components/List'; import ListItem from 'components/ListItem'; import LoadingIndicator from 'components/LoadingIndicator'; import SearchListItem from 'containers/SearchListItem'; import H3 from './H3'; import LI from './LI'; import StyledA from './StyledA'; import FacetBlockDiv from './FacetBlockDiv'; function FacetBlocks({ title, items, facetKey, loading, click, selectedFacets }) { if (loading) { return <FacetBlockDiv><h4>{title}</h4><List component={LoadingIndicator} /></FacetBlockDiv>; } let content = (<ul></ul>); content = items[facetKey].map(function callback(facet, i) { const name = facet[0]; var value = "(" + facet[1] + ")"; let active = false; if (selectedFacets) { selectedFacets.forEach(function(facet) { if (facetKey == facet[0] && name == facet[1]) { active = 'active'; value = "" } }); } return <LI key={`facet-${i}`}><StyledA data-facet-type={facetKey} className={active} onClick={click} href={`#facet-${title}-${name}`}>{name} {value}</StyledA></LI> }); return <FacetBlockDiv><h4>{title}</h4><ul className="list-group" key="items">{content}</ul></FacetBlockDiv>; } function FacetList({ facets, loadingFacets, loadingFacetsResults, selectedFacets, facetsResults, facetClick }) { let content = (<div></div>); if (loadingFacets) { return <List component={LoadingIndicator} />; } if (facets !== false) { let items = []; for (var facet in facets) { items.push(facet); } content = items.map((item) => ( <FacetBlocks title={facets[item].label} key={item} facetKey={item} selectedFacets={selectedFacets} items={facetsResults} click={facetClick} loading={loadingFacetsResults} /> )); return <div key="facets">{content}</div>; } return null; } FacetList.propTypes = { facets: PropTypes.any, facetsLoading: PropTypes.any, }; export default FacetList;
src/client/spinner.js
alihalabyah/hacker-menu
import React from 'react' export default class Spinner extends React.Component { render () { return ( <div className='spinner'> Loading... </div> ) } }
src/BootstrapMixin.js
tannewt/react-bootstrap
import React from 'react'; import styleMaps from './styleMaps'; import CustomPropTypes from './utils/CustomPropTypes'; const BootstrapMixin = { propTypes: { /** * bootstrap className * @private */ bsClass: CustomPropTypes.keyOf(styleMaps.CLASSES), /** * Style variants * @type {("default"|"primary"|"success"|"info"|"warning"|"danger"|"link")} */ bsStyle: React.PropTypes.oneOf(styleMaps.STYLES), /** * Size variants * @type {("xsmall"|"small"|"medium"|"large"|"xs"|"sm"|"md"|"lg")} */ bsSize: CustomPropTypes.keyOf(styleMaps.SIZES) }, getBsClassSet() { let classes = {}; let bsClass = this.props.bsClass && styleMaps.CLASSES[this.props.bsClass]; if (bsClass) { classes[bsClass] = true; let prefix = bsClass + '-'; let bsSize = this.props.bsSize && styleMaps.SIZES[this.props.bsSize]; if (bsSize) { classes[prefix + bsSize] = true; } if (this.props.bsStyle) { if (styleMaps.STYLES.indexOf(this.props.bsStyle) >= 0) { classes[prefix + this.props.bsStyle] = true; } else { classes[this.props.bsStyle] = true; } } } return classes; }, prefixClass(subClass) { return styleMaps.CLASSES[this.props.bsClass] + '-' + subClass; } }; export default BootstrapMixin;
src/svg-icons/editor/border-style.js
igorbt/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;
src/Pages/LandingPage.js
ashwinath/personal-website-2.0
import React from 'react'; const LandingPage = () => ( <div id="landing" className="col-md-9 main-section center-vertical-parent"> <div id="landing-content" className="center-vertical"> <h1>I bring ideas to life with code.</h1> </div> </div> ); export default LandingPage;
frontend/blueprints/dumb/files/__root__/components/__name__/__name__.js
qurben/mopidy-jukebox
import React from 'react' type Props = { }; export class <%= pascalEntityName %> extends React.Component { props: Props; render () { return ( <div></div> ) } } export default <%= pascalEntityName %>
src/index.js
lucaslago/baratinho-frontend
import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { createStore, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import createLogger from 'redux-logger' import thunkMiddleware from 'redux-thunk' import App from './components/App' import Home from './scenes/Home' import rootReducer from './reducers' import { fetchPromotions } from './actions' const loggerMiddleware = createLogger() const store = createStore(rootReducer, applyMiddleware(thunkMiddleware, loggerMiddleware)) store.dispatch(fetchPromotions()) .then(() => console.log(store.getState())) render( <Provider store={store}> <App> <Home /> </App> </Provider> , document.getElementById('root') )
consoles/my-joy-instances/src/containers/navigation/breadcrumb.js
yldio/joyent-portal
import React from 'react'; import paramCase from 'param-case'; import get from 'lodash.get'; import { Link } from 'react-router-dom'; import { Margin } from 'styled-components-spacing'; import { Breadcrumb, BreadcrumbItem } from 'joyent-ui-toolkit'; export default ({ match }) => { const instance = get(match, 'params.instance'); const links = [ { name: 'Compute', pathname: '/' }, { name: 'Instances', pathname: '/instances' } ] .concat( instance && [ { name: paramCase(instance), pathname: `/instances/${instance}` } ] ) .filter(Boolean) .map(({ name, pathname }) => ( <BreadcrumbItem key={name} to={pathname} component={Link}> <Margin horizontal="1" vertical="3"> {name} </Margin> </BreadcrumbItem> )); return <Breadcrumb>{links}</Breadcrumb>; };
node_modules/react-router/es6/Link.js
rekyyang/ArtificalLiverCloud
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import warning from './routerWarning'; import { routerShape } from './PropTypes'; var _React$PropTypes = React.PropTypes; var bool = _React$PropTypes.bool; var object = _React$PropTypes.object; var string = _React$PropTypes.string; var func = _React$PropTypes.func; var oneOfType = _React$PropTypes.oneOfType; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } // TODO: De-duplicate against hasAnyProperties in createTransitionManager. function isEmptyObject(object) { for (var p in object) { if (Object.prototype.hasOwnProperty.call(object, p)) return false; }return true; } function createLocationDescriptor(to, _ref) { var query = _ref.query; var hash = _ref.hash; var state = _ref.state; if (query || hash || state) { return { pathname: to, query: query, hash: hash, state: state }; } return to; } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets the value of its * activeClassName prop. * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along location state and/or query string parameters * in the state/query props, respectively. * * <Link ... query={{ show: true }} state={{ the: 'state' }} /> */ var Link = React.createClass({ displayName: 'Link', contextTypes: { router: routerShape }, propTypes: { to: oneOfType([string, object]).isRequired, query: object, hash: string, state: object, activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, onClick: func }, getDefaultProps: function getDefaultProps() { return { onlyActiveOnIndex: false, style: {} }; }, handleClick: function handleClick(event) { var allowTransition = true; if (this.props.onClick) this.props.onClick(event); if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; if (event.defaultPrevented === true) allowTransition = false; // If target prop is set (e.g. to "_blank") let browser handle link. /* istanbul ignore if: untestable with Karma */ if (this.props.target) { if (!allowTransition) event.preventDefault(); return; } event.preventDefault(); if (allowTransition) { var _props = this.props; var to = _props.to; var query = _props.query; var hash = _props.hash; var state = _props.state; var _location = createLocationDescriptor(to, { query: query, hash: hash, state: state }); this.context.router.push(_location); } }, render: function render() { var _props2 = this.props; var to = _props2.to; var query = _props2.query; var hash = _props2.hash; var state = _props2.state; var activeClassName = _props2.activeClassName; var activeStyle = _props2.activeStyle; var onlyActiveOnIndex = _props2.onlyActiveOnIndex; var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']); process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : undefined; // Ignore if rendered outside the context of router, simplifies unit testing. var router = this.context.router; if (router) { var _location2 = createLocationDescriptor(to, { query: query, hash: hash, state: state }); props.href = router.createHref(_location2); if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) { if (router.isActive(_location2, onlyActiveOnIndex)) { if (activeClassName) { if (props.className) { props.className += ' ' + activeClassName; } else { props.className = activeClassName; } } if (activeStyle) props.style = _extends({}, props.style, activeStyle); } } } return React.createElement('a', _extends({}, props, { onClick: this.handleClick })); } }); export default Link;
yycomponent/locale-provider/LocaleProvider.js
77ircloud/yycomponent
import React from 'react'; import { LocaleProvider as _LocaleProvider } from 'antd'; class LocaleProvider extends React.Component{ constructor(props){ super(props); } render(){ return (<_LocaleProvider {...this.props}/>); } } export default LocaleProvider
src/routes/Login.js
Anteoy/lionreact
import React from 'react'; import { connect } from 'dva'; import styles from './Login.css'; // import PnoteIndex from '../components/login/Login'; function Login() { return ( <div className={styles.normal}> {/* extra={<PnoteIndex />}*/} test </div> ); } function mapStateToProps() { return {}; } export default connect(mapStateToProps)(Login);
src/svg-icons/communication/screen-share.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationScreenShare = (props) => ( <SvgIcon {...props}> <path d="M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.11-.9-2-2-2H4c-1.11 0-2 .89-2 2v10c0 1.1.89 2 2 2H0v2h24v-2h-4zm-7-3.53v-2.19c-2.78 0-4.61.85-6 2.72.56-2.67 2.11-5.33 6-5.87V7l4 3.73-4 3.74z"/> </SvgIcon> ); CommunicationScreenShare = pure(CommunicationScreenShare); CommunicationScreenShare.displayName = 'CommunicationScreenShare'; CommunicationScreenShare.muiName = 'SvgIcon'; export default CommunicationScreenShare;
src/components/NotFoundPage.js
Dynatos/personal-website
import React from 'react'; //import { Link } from 'react-router'; import { Link } from "react-router-dom"; import NavBar from './NavBar/NavBar'; const NotFoundPage = () => { return ( <div> <NavBar/> <h4> 404 Page Not Found </h4> <Link to="/"> Go back to homepage </Link> </div> ); }; export default NotFoundPage;
app/javascript/mastodon/components/loading_indicator.js
salvadorpla/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; const LoadingIndicator = () => ( <div className='loading-indicator'> <div className='loading-indicator__figure' /> <FormattedMessage id='loading_indicator.label' defaultMessage='Loading...' /> </div> ); export default LoadingIndicator;
src/components/views/delegateProfile/components/Sidebar.js
LiskHunt/LiskHunt
import React from 'react'; import Description from './Description'; import BannerWrap from './BannerWrap'; import HeaderCard from './HeaderCard'; const Sidebar = () => { return ( <div id="sidebar" className="column is-one-quarter"> <BannerWrap /> <HeaderCard /> <Description /> </div> ); }; export default Sidebar;
modules/client.js
Scarysize/browserify-code-split
import React from 'react'; import { match, Router } from 'react-router'; import { render } from 'react-dom'; import { createHistory } from 'history'; import routes from './routes/RootRoute'; const { pathname, search, hash } = window.location; const location = `${pathname}${search}${hash}`; // calling `match` is simply for side effects of // loading route/component code for the initial location match({ routes, location }, () => { render( <Router routes={routes} history={createHistory()} />, document.getElementById('app') ); });
src/utils/CustomPropTypes.js
IveWong/react-bootstrap
import React from 'react'; const ANONYMOUS = '<<anonymous>>'; const CustomPropTypes = { isRequiredForA11y(propType){ return function(props, propName, componentName){ if (props[propName] === null) { return new Error( 'The prop `' + propName + '` is required to make ' + componentName + ' accessible ' + 'for users using assistive technologies such as screen readers `' ); } return propType(props, propName, componentName); }; }, /** * Checks whether a prop provides a DOM element * * The element can be provided in two forms: * - Directly passed * - Or passed an object that has a `render` method * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ mountable: createMountableChecker(), /** * Checks whether a prop provides a type of element. * * The type of element can be provided in two forms: * - tag name (string) * - a return value of React.createClass(...) * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ elementType: createElementTypeChecker(), /** * Checks whether a prop matches a key of an associated object * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ keyOf: createKeyOfChecker, /** * Checks if only one of the listed properties is in use. An error is given * if multiple have a value * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ singlePropFrom: createSinglePropFromChecker, all }; function errMsg(props, propName, componentName, msgContinuation) { return `Invalid prop '${propName}' of value '${props[propName]}'` + ` supplied to '${componentName}'${msgContinuation}`; } /** * Create chain-able isRequired validator * * Largely copied directly from: * https://github.com/facebook/react/blob/0.11-stable/src/core/ReactPropTypes.js#L94 */ function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName) { componentName = componentName || ANONYMOUS; if (props[propName] == null) { if (isRequired) { return new Error( `Required prop '${propName}' was not specified in '${componentName}'.` ); } } else { return validate(props, propName, componentName); } } let chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createMountableChecker() { function validate(props, propName, componentName) { if (typeof props[propName] !== 'object' || typeof props[propName].render !== 'function' && props[propName].nodeType !== 1) { return new Error( errMsg(props, propName, componentName, ', expected a DOM element or an object that has a `render` method') ); } } return createChainableTypeChecker(validate); } function createKeyOfChecker(obj) { function validate(props, propName, componentName) { let propValue = props[propName]; if (!obj.hasOwnProperty(propValue)) { let valuesString = JSON.stringify(Object.keys(obj)); return new Error( errMsg(props, propName, componentName, `, expected one of ${valuesString}.`) ); } } return createChainableTypeChecker(validate); } function createSinglePropFromChecker(arrOfProps) { function validate(props, propName, componentName) { const usedPropCount = arrOfProps .map(listedProp => props[listedProp]) .reduce((acc, curr) => acc + (curr !== undefined ? 1 : 0), 0); if (usedPropCount > 1) { const [first, ...others] = arrOfProps; const message = `${others.join(', ')} and ${first}`; return new Error( `Invalid prop '${propName}', only one of the following ` + `may be provided: ${message}` ); } } return validate; } function all(propTypes) { if (propTypes === undefined) { throw new Error('No validations provided'); } if (!(propTypes instanceof Array)) { throw new Error('Invalid argument must be an array'); } if (propTypes.length === 0) { throw new Error('No validations provided'); } return function(props, propName, componentName) { for(let i = 0; i < propTypes.length; i++) { let result = propTypes[i](props, propName, componentName); if (result !== undefined && result !== null) { return result; } } }; } function createElementTypeChecker() { function validate(props, propName, componentName) { let errBeginning = errMsg(props, propName, componentName, '. Expected an Element `type`'); if (typeof props[propName] !== 'function') { if (React.isValidElement(props[propName])) { return new Error(errBeginning + ', not an actual Element'); } if (typeof props[propName] !== 'string') { return new Error(errBeginning + ' such as a tag name or return value of React.createClass(...)'); } } } return createChainableTypeChecker(validate); } export default CustomPropTypes;
blueocean-material-icons/src/js/components/svg-icons/av/games.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const AvGames = (props) => ( <SvgIcon {...props}> <path d="M15 7.5V2H9v5.5l3 3 3-3zM7.5 9H2v6h5.5l3-3-3-3zM9 16.5V22h6v-5.5l-3-3-3 3zM16.5 9l-3 3 3 3H22V9h-5.5z"/> </SvgIcon> ); AvGames.displayName = 'AvGames'; AvGames.muiName = 'SvgIcon'; export default AvGames;
plugins/Files/js/components/downloadlist.js
NebulousLabs/Sia-UI
import PropTypes from 'prop-types' import React from 'react' import TransferList from './transferlist.js' import { List } from 'immutable' const DownloadList = ({ downloads, onDownloadClick, onClearClick }) => ( <div className='downloads'> <h3> Downloads </h3> <TransferList transfers={downloads} onTransferClick={onDownloadClick} /> <button onClick={onClearClick} className='clear-downloads'> Clear Downloads </button> </div> ) DownloadList.propTypes = { downloads: PropTypes.instanceOf(List).isRequired, onDownloadClick: PropTypes.func, onClearClick: PropTypes.func } export default DownloadList
src/svg-icons/av/snooze.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSnooze = (props) => ( <SvgIcon {...props}> <path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm-3-9h3.63L9 15.2V17h6v-2h-3.63L15 10.8V9H9v2z"/> </SvgIcon> ); AvSnooze = pure(AvSnooze); AvSnooze.displayName = 'AvSnooze'; AvSnooze.muiName = 'SvgIcon'; export default AvSnooze;
examples/real-world/containers/DevTools.js
tappleby/redux
import React from 'react' import { createDevTools } from 'redux-devtools' import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-w"> <LogMonitor /> </DockMonitor> )
src/lib/components/D3/ScatterPlotUI.js
as-me/Adapter
import "d3chart"; import React from 'react'; class D3ScatterPlot extends React.Component { constructor(props) { super(props); this.sessionData = props.sessionData; this.hook = props.hook; this.state = this.sessionData.getSessionStateValue(); this.initialize = this.initialize.bind(this); this._setReactState = this._setReactState.bind(this); } initialize() { var _dataSourcePath = this.state.dataSourcePath; //since key wasnt mentioned here it creates index column and name index as key column name if (_dataSourcePath && _dataSourcePath.length > 0) { var config = { container: React.findDOMNode(this), margin: this.props.padding ? this.props.padding : {}, size: this.props.size ? this.props.size : {}, interactions: { onProbe: this.props.onProbe, onSelect: this.props.onSelect } } this.hook.chart = new d3Chart.Scatterplot(); this.hook.chart.create(config); var path = this.state.dataSourcePath; var rows = WeaveAPI.SessionManager.getObject(WeaveAPI.globalHashMap, path).data.getSessionState(); var data = { columns: { x: this.state.xAxis, y: this.state.yAxis }, records: rows }; console.log('d3', rows); this.hook.chart.renderChart(data); } else { console.warn("No data"); } } //tied with d3 creation componentDidMount() { this.initialize(); // make sure data update is called last , so that x and y axis property will be ready by then. WeaveAPI.SessionManager.getCallbackCollection(this.sessionData).addGroupedCallback(this, this._setReactState, true); } _setReactState() { if (!this.hook.chart) { this.initialize(); } this.setState(this.sessionData.getSessionStateValue()); } //tied with d3 update componentDidUpdate(prevProps, prevState) { if (this.hook.chart) { var path = this.state.dataSourcePath; var rows = WeaveAPI.SessionManager.getObject(WeaveAPI.globalHashMap, path).data.getSessionState(); var data = { columns: { x: this.state.xAxis, y: this.state.yAxis }, records: rows }; this.hook.chart.renderChart(data); } } //tied with d3 destruction componentWillUnmount() { WeaveAPI.SessionManager.getCallbackCollection(this.sessionData).removeCallback(this._setReactState); } render() { var _dataSourcePath = this.state.dataSourcePath; if (_dataSourcePath && _dataSourcePath.length > 0) { return <div className = 'Chart' > < /div>; } else { return <div className = 'Chart' > < h2 > { this.sessionData.dataSourceName } dont have data < /h2> < /div > ; } } } module.exports = D3ScatterPlot;
client/components/CodeEditor/index.js
Elektro1776/Project_3
import React, { Component } from 'react'; import LanguageDropdown from './Language_Dropdown'; import EditorField from './Code_Editor'; class CodeEditorParent extends Component { state = { currentLanguage: 'javascript' }; whatIsOurState(propVal) { this.setState({ currentLanguage: propVal }); } render() { return ( <div> <LanguageDropdown handleParentStateChange={this.whatIsOurState.bind(this)} /> <EditorField currentLanguageState={this.state.currentLanguage} /> </div> ); } } export default CodeEditorParent;
app/routes/notFound/index.js
wojciech-panek/study-group-6-redux
import React from 'react'; import { IndexRoute } from 'react-router'; import { NotFound } from './notFound.component'; export default ( <IndexRoute component={NotFound} /> );
src/components/examples/constructorFunc.js
Jguardado/ComponentBase
import React, { Component } from 'react'; /** * Class respresenting a Constructor Function * @constructor */ export default class Contructor extends Component { constructor(props) { super(props); /** intializing the state of the component */ this.state = { /** Anything assigned in the state object will be the intial values */ test: 'Created on initializaton', }; } render() { /** * @return The JSX represenation of a constructor functiom */ return ( <div className='center'> <legend className='headingtext'>Example Constructor</legend> {this.state.test} </div> ); } }
app/assets/javascripts/NewNodeWidget/Section/NodeTypeSelect.js
sozialhelden/wheelmap
import React from 'react'; import sortBy from 'lodash.sortby'; import Form from '../../common/Form'; import I18n from '../../common/I18n'; import { Category, NodeType } from '../../common/models'; import { immutableMapOf } from '../../common/propTypes'; const { func, instanceOf, string } = React.PropTypes; class NodeTypeSelect extends React.Component { static propTypes = { onChange: func, categories: immutableMapOf(instanceOf(Category)), nodeTypes: immutableMapOf(instanceOf(NodeType)), value: string }; onChange = event => { this.props.onChange(event.target.value); }; getOptions() { const { categories, nodeTypes } = this.props; const optGroups = categories.toArray().map(category => { const options = nodeTypes .filter(nodeType => nodeType.category === category.id) .toArray() .map(nodeType => ({ label: I18n.t(`poi.name.${category.identifier}.${nodeType.identifier}`), value: nodeType.identifier })); return { label: I18n.t(`poi.category.${category.identifier}`), options: sortBy(options, 'label') }; }); return sortBy(optGroups, 'label'); } render() { return ( <Form.Select options={this.getOptions()} onChange={this.onChange} value={this.props.value} /> ); } } export default NodeTypeSelect;
tp-3/sebareverso/src/components/pages/about/AboutPage.js
jpgonzalezquinteros/sovos-reactivo-2017
import React from 'react'; import Paper from 'material-ui/Paper'; import '../../app.scss'; import {Card, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card'; class AboutPage extends React.Component { constructor(props) { super(props); this.state = { expanded: false, }; } handleExpandChange = (expanded) => { this.setState({expanded: expanded}); }; render() { return ( <div> <Paper zDepth={2} className='paperStyle' > <Card expanded={this.state.expanded} onExpandChange={this.handleExpandChange}> <CardHeader title="Sebasti&aacute;n Reverso" subtitle="Sovos Reactivo" avatar="./profile.jpg" actAsExpander={true} showExpandableButton={true} /> <CardMedia expandable={true} overlay={<CardTitle title="Sebasti&aacute;n Reverso" subtitle="Sovos Reactivo" />} > <img src="./profile.jpg" alt="" /> </CardMedia> <CardTitle title="Tuculegio" subtitle="Proyecto Reactivo" expandable={true} /> <CardText expandable={true}> Este es el proyecto Tuculegio desarrollado por los Reactivos 2017 de Sovos! </CardText> </Card> </Paper> </div> ); } } export default AboutPage;