path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/views/Components/TestSet.js
pranked/cs2-web
import React from 'react'; import './TestSet.scss'; export default class TestSet extends React.Component { render() { const flatten = res => { let didPass = `glyphicon glyphicon-${res.passed === true ? 'ok' : 'removed'}`; return ( <tr key={res.name} > <td>{res.name}</td> <td>{res.output}</td> <td>{res.duration}ms</td> <td><span className={didPass}></span></td> </tr> ); }; const tables = item => { return ( <div key={item.parent}> <h4><i className="glyphicon glyphicon-copyright-mark text-muted" /> {item.parent}</h4> <table className="table" > <colgroup> <col className="col-xs-4" /> <col className="col-xs-8" /> <col className="col-xs-1" /> <col className="col-xs-1" /> </colgroup> <thead> <tr> <th>Name</th> <th>Output</th> <th></th> <th></th> </tr> </thead> <tbody id="table-body" > {item.results.map(flatten)} </tbody> </table> </div> ); }; return ( <div> <h3>Tests</h3> {this.props.items.map(tables)} </div> ); } } TestSet.propTypes = { items: React.PropTypes.any.isRequired }
src/svg-icons/av/replay.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvReplay = (props) => ( <SvgIcon {...props}> <path d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/> </SvgIcon> ); AvReplay = pure(AvReplay); AvReplay.displayName = 'AvReplay'; export default AvReplay;
node_modules/react-icons/go/arrow-up.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const GoArrowUp = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m20 7.5l-12.5 15h7.5v10h10v-10h7.5l-12.5-15z"/></g> </Icon> ) export default GoArrowUp
src/components/helpers/Loading.js
kennethaa/vanvikil-live
import React from 'react'; import Icon from 'react-fa'; export default function Loading() { return ( <div className="text-center"> <Icon spin name="spinner" size="5x" /> </div> ); }
src/modules/home/containers/HomeFeaturesContainer/HomeFeaturesContainer.js
cltk/cltk_frontend
import React from 'react'; import { compose } from 'react-apollo'; import homeFeaturesQuery from '../../graphql/queries/homeFeaturesQuery'; import HomeFeatures from '../../components/Home/sections/HomeFeatures'; class HomeFeaturesContainer extends React.Component { render() { let worksCount = 0; let textGroupsCount = 0; let collectionsCount = 0; if (this.props.homeFeaturesQuery) { worksCount = this.props.homeFeaturesQuery.worksCount; collectionsCount = this.props.homeFeaturesQuery.collectionsCount; textGroupsCount = this.props.homeFeaturesQuery.textGroupsCount; } return ( <HomeFeatures worksCount={worksCount} textGroupsCount={textGroupsCount} collectionsCount={collectionsCount} /> ); } } export default compose( homeFeaturesQuery )(HomeFeaturesContainer);
client/utils/relay.js
ncrmro/reango
import React from 'react' import { hasValidJwtToken } from 'modules/auth/jwtUtils' import Loading from '../components/Loading/Loading' import { QueryRenderer } from 'react-relay' import { ConnectionHandler, Environment, Network, RecordSource, Store } from 'relay-runtime' const source = new RecordSource() const store = new Store(source) function update(store, payload) { const record = store.get(payload.dataID) if (!record) { return } const serverViewer = record.getLinkedRecord(payload.fieldKey) record.setLinkedRecord(serverViewer, payload.handleKey) const root = store.getRoot() root.setLinkedRecord(serverViewer, payload.handleKey) } function handlerProvider(handle) { //https://github.com/facebook/relay/issues/1668#issuecomment-298828818 switch (handle) { // Augment (or remove from) this list: case 'connection': return ConnectionHandler case 'viewer': return { update } default: throw new Error(`handlerProvider: No handler provided for ${handle}`) } } // Define a function that fetches the results of an operation (query/mutation/etc) // and returns its results as a Promise: function fetchQuery(operation, variables/* , cacheConfig, uploadables*/) { // Caching and relay records merge here // console.log(operation, variables); // console.log(store._recordSource._records); const { token } = hasValidJwtToken() const authorization = token ? `Bearer ${token}` : '' return fetch('/graphql', { method: 'POST', credentials: 'same-origin', headers: { authorization, Accept: 'application/json', 'Content-Type': 'application/json' }, // Add authentication and other headers here body: JSON.stringify({ query: operation.text, // GraphQL text from input variables }) }).then(response => response.json()) } // Create a network layer from the fetch function const network = Network.create(fetchQuery) export const environment = new Environment({ handlerProvider, network, store }) function spreadVariables({ relay, router }, variables) { let nextVar = { // Variables passed withRelayContainer ...variables } if (router) { nextVar = { ...nextVar, // Any url params found in the url eg /questions?first=10 ...router.urlParams, // React router match params eg /question/1 = /question/:id ...router.match.params } } if (relay && relay.variables) { // Passing a relay variables object allows us to pass down variables from components higher up nextVar = { ...nextVar, ...relay.variables } } return nextVar } export function withRelayContainer(WrappedComponent, query, variables = {}) { return (passedProps) => <QueryRenderer environment={environment} query={query} variables={spreadVariables(passedProps, variables)} render={({ error, props }) => { if (props) { const viewerProps = { viewer: { ...passedProps.viewer, ...props.viewer } } return <WrappedComponent { ...passedProps} { ...props} { ...viewerProps} relay={{ ...passedProps.relay, environment }} /> } else if (error) { return <div> {error} </div> } else { return <Loading /> } } } /> } export default withRelayContainer
src/main/assets/components/SidePoster.js
kristenkotkas/moviediary
import React from 'react'; import '../static/css/App.css'; import FontAwesome from 'react-fontawesome'; export default class SidePoster extends React.Component { constructor(props) { super(props); this.state = { movieTitle: props.movieTitle, movieId: props.movieId, moviePosterPath: props.moviePosterPath }; } removeMovie() { this.props.removeMovie(this.state); } /* <FontAwesome className={'removeMovie'} name={'times'} onClick={this.removeMovie.bind(this)} /> */ render() { return ( <div className="box" style={{ position: 'absolute', transform: 'translate(' + this.props.xPos + 'px, ' + this.props.yPos + 'px)' }}> <img src={this.state.moviePosterPath} className={'sidePosterImg'} alt=""/> </div> ); } }
app/pages/servicePhotoPage.js
shiyunjie/scs
/** * Created by shiyunjie on 16/12/6. */ import React, { Component } from 'react'; import { StyleSheet, Text, View, Platform, TouchableOpacity, ScrollView, TextInput, ListView, Image, Dimensions, Alert, NativeAppEventEmitter, ActivityIndicator, NativeModules, BackAndroid, } from 'react-native'; import LoginPage from './loginPage' import constants from '../constants/constant'; import navigatorStyle from '../styles/navigatorStyle' //navigationBar样式 import Icon from 'react-native-vector-icons/Ionicons'; import AppEventListenerEnhance from 'react-native-smart-app-event-listener-enhance' import {getDeviceID,getToken,getPhone,getRealName} from '../lib/User' import XhrEnhance from '../lib/XhrEnhance' //http import Toast from 'react-native-smart-toast' import Button from 'react-native-smart-button' import ProgressView from '../components/modalProgress' import ModalDialog from '../components/modalDialog' import LoadingSpinnerOverlay from 'react-native-smart-loading-spinner-overlay' import { tabBarConfig } from '../constants/sharedConfig' import UploadPage from '../pages/uploadPage' //import ImageZoomModal from '../components/ImageZoomModal' import ShowPhotoView from '../components/showPhotoView' const photoList = []; class ServicePhoto extends Component { // 构造 constructor(props) { super(props); // 初始状态 this._dataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2, //sectionHeaderHasChanged: (s1, s2) => s1 !== s2, }); this.state = { showProgress: true,//显示加载 showReload: false,//显示加载更多 showDialog: false,//显示确认框 service_id: this.props.id,//服务单id photoList, } this.firstFetch = true; } componentWillMount() { NativeAppEventEmitter.emit('setNavigationBar.index', navigationBarRouteMapper) let currentRoute = this.props.navigator.navigationContext.currentRoute this.addAppEventListener( this.props.navigator.navigationContext.addListener('willfocus', (event) => { //console.log(`OrderDetail willfocus...`) //console.log(`currentRoute`, currentRoute) //console.log(`event.data.route`, event.data.route) if (currentRoute === event.data.route) { //console.log("OrderDetail willAppear") NativeAppEventEmitter.emit('setNavigationBar.index', navigationBarRouteMapper) } else { //console.log("OrderDetail willDisappear, other willAppear") } // }) ) this.addAppEventListener( NativeAppEventEmitter.addListener('PicturePicker.finish.saveIds', () => { if(this._modalLoadingSpinnerOverLay){ this._modalLoadingSpinnerOverLay.show() } this._fetch_finish() }) ) this.addAppEventListener( this.props.navigator.navigationContext.addListener('didfocus', (event) => { //console.log(`payPage didfocus...`) if (event && currentRoute === event.data.route) { //console.log("upload didAppear") if (this.firstFetch) { this._fetchData() this.firstFetch = false; } } else { //console.log("orderPage willDisappear, other willAppear") } }) ) this.addAppEventListener( BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid) ) } onBackAndroid = () => { const routers = this.props.navigator.getCurrentRoutes(); if (routers.length > 1) { Alert.alert('温馨提醒','确定不保存就退出吗?',[ {text:'确定',onPress:()=>this.props.navigator.pop()}, {text:'取消',onPress:()=>{}}, ]) return true; } } render() { return ( <View style={{flex:1}}> {this.state.showProgress || this.state.showReload ? <ProgressView showProgress={this.state.showProgress} showReload={this.state.showReload} /> : <View style={{flex:1,backgroundColor:'white'}}> <ScrollView style={styles.container} showsVerticalScrollIndicator={false}> <Text style={[styles.contentText,{paddingTop:5,paddingBottom:5,fontSize:12}]}>上传资料</Text> <ShowPhotoView style={{flex:1,backgroundColor:'white', paddingLeft:constants.MarginLeftRight,paddingRight:constants.MarginLeftRight,}} navigator={this.props.navigator} photoList={this.state.photoList} UploadPage={UploadPage} /> </ScrollView> <Button ref={ component => this.button2 = component } touchableType={Button.constants.touchableTypes.fadeContent} style={styles.button} textStyle={{fontSize: 17, color: 'white'}} loadingComponent={ <View style={{flexDirection: 'row', alignItems: 'center'}}> { //this._renderActivityIndicator() } <Text style={{fontSize: 17, color: 'white', fontWeight: 'bold', fontFamily: '.HelveticaNeueInterface-MediumP4',}}>委托中...</Text> </View> } onPress={ () => { if( this._modalLoadingSpinnerOverLay){ this._modalLoadingSpinnerOverLay.show() } this._fetch_finish() } }> 完成上传 </Button> </View> } <Toast ref={ component => this._toast = component } marginTop={64}> </Toast> <LoadingSpinnerOverlay ref={ component => this._modalLoadingSpinnerOverLay = component }/> </View> ); } async _fetchData() { //console.log(`fetchData_photoList`) try { let token = await getToken() let deviceID = await getDeviceID() let options = { method: 'post', url: constants.api.service, data: { iType: constants.iType.uploadImageList, id: this.state.service_id, deviceId: deviceID, token: token, } } options.data = await this.gZip(options) //console.log(`_fetchData options:`, options) let resultData = await this.fetch(options) let result = await this.gunZip(resultData) if (!result) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: '服务器打盹了,稍后再试试吧' }) return } result = JSON.parse(result) //console.log('gunZip:', result) if (!result) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: '服务器打盹了,稍后再试试吧' }) return } if (result.code && result.code == 10) { //console.log('token', result.result) let photoList = this.state.photoList photoList = photoList.concat(result.result) this.setState({ photoList:photoList }) } else { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: result.msg }) } } catch (error) { //console.log(error) if (this._toast) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: error }) } } finally { this.setState({ showProgress: false,//显示加载 showReload: false,//显示加载更多 }) //console.log(`SplashScreen.close(SplashScreen.animationType.scale, 850, 500)`) //SplashScreen.close(SplashScreen.animationType.scale, 850, 500) } } async _fetch_finish() { try { let token = await getToken() let deviceID = await getDeviceID() let fileIds = ''; for (let data of this.state.photoList) { fileIds += data.id + ',' } let options = { method: 'post', url: constants.api.service, data: { iType: constants.iType.uploadFinish, id: this.state.service_id, file_ids: fileIds, deviceId: deviceID, token: token, } } options.data = await this.gZip(options) let resultData = await this.fetch(options) let result = await this.gunZip(resultData) if (!result) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: '服务器打盹了,稍后再试试吧' }) return } result = JSON.parse(result) //console.log('gunZip:', result) if(this._modalLoadingSpinnerOverLay) { this._modalLoadingSpinnerOverLay.hide({duration: 0,}) } if(!result){ this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: '服务器打盹了,稍后再试试吧' }) return } if (result.code && result.code == 10) { //console.log('token', result.result) this.props.navigator.pop() } else { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: result.msg }) } } catch (error) { //console.log(error) if(this._toast) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: error }) } } finally { if(this._modalLoadingSpinnerOverLay) { this._modalLoadingSpinnerOverLay.hide({duration: 0,}) } //console.log(`SplashScreen.close(SplashScreen.animationType.scale, 850, 500)`) //SplashScreen.close(SplashScreen.animationType.scale, 850, 500) } } } const styles = StyleSheet.create({ container: { flex: 1, marginTop: Platform.OS == 'ios' ? 64 : 56, }, viewItem: { flex: 1, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center', paddingLeft: constants.MarginLeftRight, backgroundColor: 'white', paddingTop: 10, paddingBottom: 10, }, line: { //marginLeft: constants.MarginLeftRight, //marginRight: constants.MarginLeftRight, borderTopWidth: StyleSheet.hairlineWidth, borderLeftWidth: StyleSheet.hairlineWidth, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: constants.LineColor, }, labelText: { fontSize: 14, color: constants.LabelColor, }, contentText: { fontSize: 14, color: constants.PointColor, paddingLeft: constants.MarginLeftRight, }, button: { height: 40, backgroundColor: constants.UIActiveColor, borderWidth: StyleSheet.hairlineWidth, borderColor: constants.UIActiveColor, justifyContent: 'center', borderRadius: 30, margin:10 }, }); import {navigationBar} from '../components/NavigationBarRouteMapper' const navigationBarRouteMapper = { ...navigationBar, LeftButton: function (route, navigator, index, navState) { if (index === 0) { return null; } var previousRoute = navState.routeStack[ index - 1 ]; return ( <TouchableOpacity onPress={() => Alert.alert('温馨提醒','确定不保存就退出吗?',[ {text:'取消',onPress:()=>{}}, {text:'确定',onPress:()=>navigator.pop()} ])} style={navigatorStyle.navBarLeftButton}> <View style={navigatorStyle.navBarLeftButtonAndroid}> <Icon style={[navigatorStyle.navBarText, navigatorStyle.navBarTitleText,{fontSize: 30,}]} name={'ios-arrow-back'} size={constants.IconSize} color={'white'}/> </View> </TouchableOpacity> ); }, RightButton: function (route, navigator, index, navState) { return ( <TouchableOpacity onPress={() => { disabled=false NativeAppEventEmitter.emit('PicturePicker.finish.saveIds') }} style={navigatorStyle.navBarRightButton}> <Text style={[navigatorStyle.navBarText, navigatorStyle.navBarTitleText]}> 完成 </Text> </TouchableOpacity> ) }, }; export default AppEventListenerEnhance(XhrEnhance(ServicePhoto))
src/pages/ProfilePage.js
mDinner/musicansAssistant
import React from 'react'; import DocumentTitle from 'react-document-title'; import TextField from 'material-ui/lib/TextField'; import { UserComponent } from 'react-stormpath'; export default TextField; export default class ProfilePage extends UserComponent { onFormSubmit(e) { e.preventDefault(); } render() { var user = this.state.user; return ( <DocumentTitle title={`My Profile`}> <div className="container"> <div className="row"> <div className="col-xs-12"> <h3>My Profile</h3> <hr /> </div> </div> <div className="row"> <div className="col-xs-12"> <form className="form-horizontal" submit={this.onFormSubmit.bind(this)}> <div className="form-group"> <label htlmFor="spFirstName" className="col-xs-12 col-sm-4 control-label">First Name</label> <div className="col-xs-12 col-sm-4"> <input className="form-control" id="spFirstName" value={this.state.user.givenName} placeholder="First Name" disabled="true" /> </div> </div> <div className="form-group"> <label htlmFor="spLastName" className="col-xs-12 col-sm-4 control-label">Last Name</label> <div className="col-xs-12 col-sm-4"> <input className="form-control" id="spLastName" value={this.state.user.surname} placeholder="Last Name" disabled="true" /> </div> </div> <div> <TextField hintText="Hint Text" /><br/> <br/> <TextField hintText="The hint text can be as long as you want, it will wrap." /><br/> <TextField defaultValue="Default Value" /><br/> <TextField hintText="Hint Text" floatingLabelText="Floating Label Text" /><br/> <TextField hintText="Password Field" floatingLabelText="Password" type="password" /><br/> <TextField hintText="MultiLine with rows: 2 and rowsMax: 4" multiLine={true} rows={2} rowsMax={4} /><br/> <TextField hintText="Message Field" floatingLabelText="MultiLine and FloatingLabel" multiLine={true} rows={2} /> </div> <div className="form-group"> <div className="col-sm-offset-4 col-sm-4"> <button type="submit" className="btn btn-primary" disabled="true">Save (not supported yet)</button> </div> </div> </form> </div> </div> </div> </DocumentTitle> ); } }
src/_stories/index.js
guzmonne/conapps-charts
import React from 'react'; import { storiesOf, action, linkTo } from '@kadira/storybook'; import { withKnobs } from '@kadira/storybook-addon-knobs' // LineChart Stories import LineChartTimeScaleStory from './LineChartTimeScaleStory.js'; import LineChartLinearScaleStory from './LineChartLinearScaleStory.js'; // BarChart Stories import BarChartStory from './BarChartStory.js' import BarHistogramTimeScaleStory from './BarHistogramTimeScaleStory.js' import BarHistogramLinearScaleStory from './BarHistogramLinearScaleStory.js' import LineHistogramTimeScaleStory from './LineHistogramTimeScaleStory.js' const lineChartStories = storiesOf('LineChart', module) lineChartStories.addDecorator(withKnobs) lineChartStories .add('LineChart with linear scale', () => ( <LineChartLinearScaleStory /> )) .add('LineChart with time scale', () => ( <LineChartTimeScaleStory /> )) const barChartStories = storiesOf('BarChart', module) barChartStories.addDecorator(withKnobs) barChartStories .add('BarChart with band scale', () => ( <BarChartStory /> )) const histogramStories = storiesOf('Histogram', module) histogramStories.addDecorator(withKnobs) histogramStories .add('Bar histogram with time scale', () => ( <BarHistogramTimeScaleStory /> )) .add('Bar histogram with linear scale', () => ( <BarHistogramLinearScaleStory /> )) .add('Line histogram with time scale', () => ( <LineHistogramTimeScaleStory /> ))
packages/@lyra/components/src/snackbar/story.js
VegaPublish/vega-studio
import React from 'react' import Snackbar from 'part:@lyra/components/snackbar/default' import {storiesOf, action} from 'part:@lyra/storybook' import { withKnobs, select, text, number } from 'part:@lyra/storybook/addons/knobs' import Lyra from 'part:@lyra/storybook/addons/lyra' const getKinds = () => select('Kind', ['success', 'error', 'warning', 'info']) storiesOf('Snackbar') .addDecorator(withKnobs) .add('Snackbar', () => ( <Lyra part="part:@lyra/components/snackbar/default" propTables={[Snackbar]}> <Snackbar kind={getKinds()} timeout={number('timeout after (sec)', 500)}> {text('content', 'This is the content')} </Snackbar> </Lyra> )) .add('With action', () => { return ( <Lyra part="part:@lyra/components/snackbar/default" propTables={[Snackbar]} > <Snackbar kind={getKinds()} action={{ title: text('action title', 'OK, got it') }} onAction={action('onAction')} timeout={number('timeout (prop) im ms', 500)} > {text('children (prop)', 'This is the content')} </Snackbar> </Lyra> ) })
src/main/js/src/index.js
fernandojunior/spring-react-boilerplate
/* React, browser and server rendering functions. We need the * first import, even though it isn't explicitly referenced * in this file, in order to avoid runtime errors. */ import React from 'react'; import ReactDOM from 'react-dom'; // State management with redux import { Provider } from 'react-redux'; // Routing with react-router import { HashRouter } from 'react-router-dom'; import App from './components/app'; import createStore from './store'; // Client-side rendering. We rehydrate the Redux store and plugin it into the page render if (typeof window !== 'undefined') { const store = createStore(window.__INITIAL_STATE__); const app = ( <Provider store={store}> <HashRouter> <App /> </HashRouter> </Provider> ); ReactDOM.render(app, document.getElementById('root')); }
src/page/index/components/loading/index.js
SteamerTeam/steamer-react
import React, { Component } from 'react'; import pureRender from 'pure-render-decorator'; require('./index.less'); @pureRender export default class List extends Component { constructor(props, context) { super(props, context); this.state = { }; } componentWillMount() { } componentDidMount() { } render() { console.dev('render Loading'); var isShow = this.props.isShow || false; var loadingStyle = { display: (isShow) ? 'block' : 'none' }; var isEnd = this.props.isEnd || false; var loadingText = (isEnd) ? '已加载全部' : '正在加载中…'; return ( <div className="loading" style={loadingStyle}> <p>{loadingText}</p> </div> ); } }
examples/universal/client/index.js
andreieftimie/redux
import 'babel-core/polyfill'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import configureStore from '../common/store/configureStore'; import App from '../common/containers/App'; const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const rootElement = document.getElementById('app'); render( <Provider store={store}> <App/> </Provider>, rootElement );
src/routes/gameoflife/Gameoflife.js
zsu13579/whatsgoinontonight
import React from 'react'; import PropTypes from 'prop-types'; import { graphql, compose } from 'react-apollo'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Gameoflife.css'; import { connect } from 'react-redux'; import { setRuntimeVariable } from '../../actions/runtime'; class Btn extends React.Component{ constructor(...args) { super(...args); }; handleSize = function(){ let row=this.props.row; let col=this.props.col; this.props.handleSize(row,col); }; render(){ return <button onClick={this.handleSize.bind(this)}>{this.props.name}</button> } }; class Ge extends React.Component{ constructor(...args){ super(...args); let stage = this.props.stage; this.state = {stage:stage} }; componentWillReceiveProps = function(nextProps){ this.setState({stage:nextProps.stage}) }; handleClick = function(){ let stage=this.state.stage; let id="r"+this.props.row+"c"+this.props.col; if(stage=="empty"){ stage="newborn"; this.setState({stage:stage}); this.props.handleChange(id,stage); } }; render(){ let id="r"+this.props.row+"c"+this.props.col; return ( <span id={id} className={s[this.state.stage]} onClick={this.handleClick.bind(this)}></span> ) }; }; class Gameoflife extends React.Component{ constructor(...args){ super(...args); let board={}; let row=50; let col=70; let gen=0; let choice=['empty','newborn','adult']; for(let i=0;i<row;i++){ for(let j=0;j<col;j++){ let id="r"+i+"c"+j; let vr=Math.floor(Math.random()*3); board[id]=choice[vr]; }; }; this.state = {row:row,col:col,board:board,isPause:0,isClear:0,gen:gen,speed:300} }; setInterval = function() { this.intervals.push(setInterval.apply(null, arguments)); }; handleSize = function(row,col){ let board={}; for(let i=0;i<row;i++){ for(let j=0;j<col;j++){ let id="r"+i+"c"+j; board[id]="empty"; }; }; this.setState({row:row,col:col,board:board}); }; handleSpeed = function(e){ let speed=e.target.id; speed=parseInt(speed); this.setState({speed:speed}); this.handlePause(); this.timer=this.setInterval(this.generate.bind(this),speed); }; handleChange = function(id,stage){ let board=this.state.board; board[id]=stage; this.setState({board:board}); }; findLiveNeighbours = function(i,j){ let col=this.state.col; let row=this.state.row; let board=this.state.board; let id=""; let dcounter=0; if(board["r"+(i-1)+"c"+(j-1)]=="adult"){ dcounter++ }; if(board["r"+(i-1)+"c"+j]=="adult"){ dcounter++ }; if(board["r"+(i-1)+"c"+(j+1)]=="adult"){ dcounter++ }; if(board["r"+i+"c"+(j-1)]=="adult"){ dcounter++ }; if(board["r"+i+"c"+(j+1)]=="adult"){ dcounter++ }; if(board["r"+(i+1)+"c"+(j-1)]=="adult"){ dcounter++ }; if(board["r"+(i+1)+"c"+j]=="adult"){ dcounter++ }; if(board["r"+(i+1)+"c"+(j+1)]=="adult"){ dcounter++ }; return dcounter; }; generate = function(){ let col=this.state.col; let row=this.state.row; let board=this.state.board; let id=""; // for newborn let counter=0; // for die let dcounter=0; let dieIds=[]; let newbornIds=[]; let gen=this.state.gen; // set all newborn to adult for(let i=0;i<row;i++){ for(let j=0;j<col;j++){ id="r"+i+"c"+j; if(board[id]=="newborn"){ board[id]="adult"; } }; }; //find newborn newbornIds=[]; for(let i=0;i<row;i++){ for(let j=0;j<col;j++){ counter=0; id="r"+i+"c"+j; counter=this.findLiveNeighbours(i,j); if(board[id]=="empty" && counter==3){ newbornIds.push(id); } }; }; // find die box fewer than 2 neighbours; for(let i=0;i<row;i++){ for(let j=0;j<col;j++){ id="r"+i+"c"+j; dcounter=this.findLiveNeighbours(i,j); if(board[id]=="adult" && dcounter<2){ dieIds.push(id); } }; } // find die box more than 3 neighbours; for(let i=0;i<row;i++){ for(let j=0;j<col;j++){ id="r"+i+"c"+j; dcounter=this.findLiveNeighbours(i,j); if(board[id]=="adult" && dcounter>3){ dieIds.push(id); } }; }; //set dieIds to empty if(dieIds!=[]){ dieIds.forEach(function(value){ board[value]="empty"; }) } //set newborn id to newborn if(newbornIds!=[]){ newbornIds.forEach(function(value){ board[value]="newborn"; }) } gen++; this.setState({row:row,col:col,board:board,gen:gen}); }; componentDidMount = function(){ this.intervals = []; this.handleStart(); }; componentWillUnmount = function(){ if(this.intervals){ this.intervals.forEach(clearInterval); } }; handleClear = function(){ let row=this.state.row; let col=this.state.col; let board={}; for(let i=0;i<row;i++){ for(let j=0;j<col;j++){ let id="r"+i+"c"+j; board[id]="empty"; }; }; this.intervals.forEach(clearInterval); // this.componentWillUnmount(); this.setState({board:board,isClear:1,gen:0}); }; handlePause = function(){ this.intervals.forEach(clearInterval); // this.componentWillUnmount(); }; handleStart = function(){ let isPause=this.state.isPause; let isClear=this.state.isClear; let speed=this.state.speed; isPause=0; isClear=0; // this.setState({isPause:0,isClear:0}); // if(isPause==0 && isClear==0) this.timer=this.setInterval(this.generate.bind(this),speed); }; render(){ let geList=[]; let col=this.state.col; let row=this.state.row; let board=this.state.board; let id=""; let stage=""; for(let i=0;i<row;i++){ let rowList=[]; for(let j=0;j<col;j++){ id="r"+i+"c"+j; stage=board[id]; rowList.push(<Ge row={i} col={j} stage={stage} handleChange={this.handleChange.bind(this)} />); }; geList.push(<tr><td>{rowList}</td></tr>); }; return ( <div id={s.board}> <div className={s.topBar}> <button onClick={this.handleStart.bind(this)}>Start</button> <button onClick={this.handlePause.bind(this)}>Pause</button> <button onClick={this.handleClear.bind(this)}>Clear</button> <div className="gen">Generation:{this.state.gen}</div> </div> <table> <tbody> {geList} </tbody> </table> <Btn handleSize={this.handleSize.bind(this)} name="Size:50x30" row="30" col="50" /> <Btn handleSize={this.handleSize.bind(this)} name="Size:70x50" row="50" col="70" /> <Btn handleSize={this.handleSize.bind(this)} name="Size:100x80" row="80" col="100" /> <button onClick={this.handleSpeed.bind(this)} id="1500">Slow</button> <button onClick={this.handleSpeed.bind(this)} id="800">Medium</button> <button onClick={this.handleSpeed.bind(this)} id="300">Fast</button> </div> ) } }; function mapStateToProps(state) { if(state.user){ return { username: state.user.email, } } return {} } function mapDispatch(dispatch,ownProps) { return { setCity: (city) => { dispatch(setRuntimeVariable({ name: 'Roguelike', value: 'Playing', })); } } } export default compose( withStyles(s), connect(mapStateToProps,mapDispatch), )(Gameoflife);
src/components/common/svg-icons/hardware/developer-board.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareDeveloperBoard = (props) => ( <SvgIcon {...props}> <path d="M22 9V7h-2V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-2h2v-2h-2v-2h2v-2h-2V9h2zm-4 10H4V5h14v14zM6 13h5v4H6zm6-6h4v3h-4zM6 7h5v5H6zm6 4h4v6h-4z"/> </SvgIcon> ); HardwareDeveloperBoard = pure(HardwareDeveloperBoard); HardwareDeveloperBoard.displayName = 'HardwareDeveloperBoard'; HardwareDeveloperBoard.muiName = 'SvgIcon'; export default HardwareDeveloperBoard;
app/javascript/mastodon/features/compose/components/upload_progress.js
robotstart/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { Motion, spring } from 'react-motion'; import { FormattedMessage } from 'react-intl'; class UploadProgress extends React.PureComponent { render () { const { active, progress } = this.props; if (!active) { return null; } return ( <div className='upload-progress'> <div className='upload-progress__icon'> <i className='fa fa-upload' /> </div> <div className='upload-progress__message'> <FormattedMessage id='upload_progress.label' defaultMessage='Uploading...' /> <div className='upload-progress__backdrop'> <Motion defaultStyle={{ width: 0 }} style={{ width: spring(progress) }}> {({ width }) => <div className='upload-progress__tracker' style={{ width: `${width}%` }} /> } </Motion> </div> </div> </div> ); } } UploadProgress.propTypes = { active: PropTypes.bool, progress: PropTypes.number }; export default UploadProgress;
lavalab/html/node_modules/react-bootstrap/es/ModalDialog.js
LavaLabUSC/usclavalab.org
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import { bsClass, bsSizes, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; import { Size } from './utils/StyleConfig'; var propTypes = { /** * A css class to apply to the Modal dialog DOM node. */ dialogClassName: PropTypes.string }; var ModalDialog = function (_React$Component) { _inherits(ModalDialog, _React$Component); function ModalDialog() { _classCallCheck(this, ModalDialog); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ModalDialog.prototype.render = function render() { var _extends2; var _props = this.props, dialogClassName = _props.dialogClassName, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['dialogClassName', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var bsClassName = prefix(bsProps); var modalStyle = _extends({ display: 'block' }, style); var dialogClasses = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[bsClassName] = false, _extends2[prefix(bsProps, 'dialog')] = true, _extends2)); return React.createElement( 'div', _extends({}, elementProps, { tabIndex: '-1', role: 'dialog', style: modalStyle, className: classNames(className, bsClassName) }), React.createElement( 'div', { className: classNames(dialogClassName, dialogClasses) }, React.createElement( 'div', { className: prefix(bsProps, 'content'), role: 'document' }, children ) ) ); }; return ModalDialog; }(React.Component); ModalDialog.propTypes = propTypes; export default bsClass('modal', bsSizes([Size.LARGE, Size.SMALL], ModalDialog));
src/svg-icons/action/credit-card.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionCreditCard = (props) => ( <SvgIcon {...props}> <path d="M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4v-6h16v6zm0-10H4V6h16v2z"/> </SvgIcon> ); ActionCreditCard = pure(ActionCreditCard); ActionCreditCard.displayName = 'ActionCreditCard'; ActionCreditCard.muiName = 'SvgIcon'; export default ActionCreditCard;
modules/pages/NotFound.js
edvinerikson/isomorphic-react-kickstarter
import React from 'react'; import Header from 'shared/Header'; class NotFound extends React.Component { static contextTypes = { router: React.PropTypes.object.isRequired, } render() { return ( <div> <Header>Not found!</Header> </div> ); } } export default NotFound;
examples/websdk-samples/LayerReactNativeSample/src/ui/ConversationListItem.js
layerhq/layer-js-sampleapps
import React, { Component } from 'react'; import { StyleSheet, View, Text, TouchableOpacity, Modal } from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; import Avatar from './Avatar'; /** * This Component provides for a Conversation item * in the list, currently consisting of an * Avatar, title and Delete button. */ export default class ConversationListItem extends Component { constructor(props) { super(props); this.state = { showDeleteConfirm: false } } handleDeleteConversation = () => { this.props.onDeleteConversation(this.props.conversation.id); } handleSelectConversation = () => { this.props.onSelectConversation(this.props.conversation.id); } render() { const { conversation } = this.props; const participantUsers = conversation.participants.filter(user => !user.sessionOwner); const title = conversation.metadata.conversationName || participantUsers.map(function(user) { return user.displayName; }).join(', '); // Render the UI return ( <TouchableOpacity style={styles.container} onPress={this.handleSelectConversation} activeOpacity={.5} > <Avatar users={participantUsers}/> <Text style={[styles.title, (conversation.unreadCount > 0) ? styles.titleUnread : {}]}>{title}</Text> <TouchableOpacity style={styles.deleteButton} onPress={() => {this.setState({showDeleteConfirm: true})}} activeOpacity={.5} > <Icon style={styles.deleteIcon} name='times-circle' /> </TouchableOpacity> <Modal animationType={"slide"} transparent={true} visible={this.state.showDeleteConfirm} > <View style={styles.modalBackground}> <View style={styles.confirmDeleteDialog}> <Text style={styles.confirmText}>Are you sure you want to delete this conversation?</Text> <View style={styles.confirmButtonsContainer}> <TouchableOpacity style={styles.confirmButton} onPress={() => { this.setState({showDeleteConfirm: false}); this.handleDeleteConversation(); }} activeOpacity={.5} > <Text style={styles.confirmButtonText}>Delete</Text> </TouchableOpacity> <TouchableOpacity style={styles.confirmButton} onPress={() => { this.setState({showDeleteConfirm: false}); }} activeOpacity={.5} > <Text style={styles.confirmButtonText}>Cancel</Text> </TouchableOpacity> </View> </View> </View> </Modal> </TouchableOpacity> ); } } const styles = StyleSheet.create({ container: { flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center', paddingHorizontal: 15, paddingVertical: 15, borderBottomWidth: 1, borderColor: '#eee' }, title: { flex: 1, marginLeft: 20, fontFamily: 'System', fontSize: 14, color: '#666' }, titleUnread: { color: 'black', fontWeight: 'bold' }, deleteButton: { padding: 10, }, deleteIcon: { fontSize: 20, color: '#999' }, modalBackground: { flex: 1, backgroundColor: 'rgba(0,0,0,0.5)', justifyContent: 'center' }, confirmDeleteDialog: { backgroundColor: 'white', marginHorizontal: 30 }, confirmText: { fontFamily: 'System', fontSize: 18, textAlign: 'center', marginTop: 20 }, confirmButtonsContainer: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginVertical: 20 }, confirmButton: { borderWidth: 1, borderColor: '#aaa', padding: 10, marginHorizontal: 10 }, confirmButtonText: { fontFamily: 'System', fontSize: 16 } });
src/components/InfoBar/InfoBar.js
tpphu/react-pwa
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { load } from 'redux/modules/info'; @connect( state => ({ info: state.info.data }), { load }) export default class InfoBar extends Component { static propTypes = { info: PropTypes.object, load: PropTypes.func.isRequired } static defaultProps = { info: null }; render() { const { info, load } = this.props; // eslint-disable-line no-shadow const styles = require('./InfoBar.scss'); return ( <div className={`${styles.infoBar} well`}> <div className="container"> This is an info bar{' '} <strong>{info ? info.message : 'no info!'}</strong> <span className={styles.time}>{info && new Date(info.time).toString()}</span> <button className="btn btn-primary" onClick={load}>Reload from server</button> </div> </div> ); } }
src/js/containers/PictureGridContainer/PictureGridContainer.js
shane-arthur/react-redux-and-more-boilerplate
import React, { Component } from 'react'; import PictureIcon from '../../components/PictureIcon/PictureIcon'; import { styles } from './styles'; import { sendData } from '../../data/dataFetcher'; export default class PictureGridContainer extends Component { _getPictureContainerItems() { const pictureList = this.props.pictureList; const pictureIds = this.props.items.map(item => { return item.pictureId; }); const doesPicExist = (pictureId) => { return pictureIds.indexOf(Number(pictureId)) >= 0; }; const translatePictureId = (pictureName) => { return findObjectByValue(this.props.pictureMappings, pictureName, NaN); }; const findObjectByValue = (collection, value, defaultValue = null) => { let keyForValue = defaultValue; Object.keys(collection).forEach(key => { if (collection[key] === value) keyForValue = key; }); return keyForValue; } const formSelectedPicturePayload = (pictureName, pictureId, pageId) => { return { content: pictureName, pictureId, pageId } } const onCheckboxClick = (payload) => { sendData('/endpoint', payload).then(response => { //do nothing }).catch(error => { //catch error }) }; if (this.props.pictureList) { const pageId = this.props.pageId; return this.props.pictureList.map(picture => { const pictureName = picture.split(".jpg")[0]; const pictureId = translatePictureId(pictureName); const isPicSelected = doesPicExist(pictureId); return <PictureIcon selectedData={formSelectedPicturePayload(pictureName, pictureId, pageId)} onClick={onCheckboxClick} key={pictureName} selectedClass={'icon'} pictureName={pictureName} selected={isPicSelected} onClick={this.props.onClick} /> }, this); } else { return null } } render() { const picturesToDisplay = this._getPictureContainerItems(); return ( <div style={styles.wrapper}> {picturesToDisplay} </div> ); } }
examples/todomvc/index.js
alantrrs/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; import 'todomvc-app-css/index.css'; const store = configureStore(); React.render( <Provider store={store}> {() => <App />} </Provider>, document.getElementById('root') );
app/javascript/mastodon/features/ui/components/audio_modal.js
abcang/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Audio from 'mastodon/features/audio'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import Footer from 'mastodon/features/picture_in_picture/components/footer'; const mapStateToProps = (state, { statusId }) => ({ accountStaticAvatar: state.getIn(['accounts', state.getIn(['statuses', statusId, 'account']), 'avatar_static']), }); export default @connect(mapStateToProps) class AudioModal extends ImmutablePureComponent { static propTypes = { media: ImmutablePropTypes.map.isRequired, statusId: PropTypes.string.isRequired, accountStaticAvatar: PropTypes.string.isRequired, options: PropTypes.shape({ autoPlay: PropTypes.bool, }), onClose: PropTypes.func.isRequired, onChangeBackgroundColor: PropTypes.func.isRequired, }; render () { const { media, accountStaticAvatar, statusId, onClose } = this.props; const options = this.props.options || {}; return ( <div className='modal-root__modal audio-modal'> <div className='audio-modal__container'> <Audio src={media.get('url')} alt={media.get('description')} duration={media.getIn(['meta', 'original', 'duration'], 0)} height={150} poster={media.get('preview_url') || accountStaticAvatar} backgroundColor={media.getIn(['meta', 'colors', 'background'])} foregroundColor={media.getIn(['meta', 'colors', 'foreground'])} accentColor={media.getIn(['meta', 'colors', 'accent'])} autoPlay={options.autoPlay} /> </div> <div className='media-modal__overlay'> {statusId && <Footer statusId={statusId} withOpenButton onClose={onClose} />} </div> </div> ); } }
lib/index.js
devinmarieb/budget-app
import React from 'react'; import { render } from 'react-dom'; import Application from './components/Application'; import firebase from './firebase'; import MoneyQuotes, { randomQuote } from './components/MoneyQuotes'; require('./styles/reset.css'); require('./styles/style.scss'); render(<Application quote={ randomQuote() } />, document.getElementById('application'));
shared/container/DevTools/DevTools.js
Ripley6811/TAIMAU-CHARTS
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> );
lib/cli/generators/REACT_NATIVE/template-csf/storybook/stories/index.js
storybooks/react-storybook
import React from 'react'; import { Text } from 'react-native'; import { storiesOf } from '@storybook/react-native'; import { action } from '@storybook/addon-actions'; import { linkTo } from '@storybook/addon-links'; import Button from './Button'; import CenterView from './CenterView'; import Welcome from './Welcome'; storiesOf('Welcome', module).add('to Storybook', () => <Welcome showApp={linkTo('Button')} />); storiesOf('Button', module) .addDecorator(getStory => <CenterView>{getStory()}</CenterView>) .add('with text', () => ( <Button onPress={action('clicked-text')}> <Text>Hello Button</Text> </Button> )) .add('with some emoji', () => ( <Button onPress={action('clicked-emoji')}> <Text>😀 😎 👍 💯</Text> </Button> ));
src/pages/privacy.js
saschajullmann/gatsby-starter-gatsbythemes
/* eslint-disable no-undef, react/prop-types */ import React from 'react'; import { Box } from '../components/Layout'; import PageWrapper from '../components/PageWrapper'; import colors from '../utils/colors'; const Privacy = () => ( <PageWrapper> <Box bg={colors.primary}> <Box width={[1, 1, 1 / 2]} m={['3.5rem 0 0 0', '3.5rem 0 0 0', '3.5rem auto 0 auto']} px={[3, 3, 0]} color={colors.secondary} > <h1>Privacy Policy</h1> <p> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. </p> </Box> </Box> </PageWrapper> ); export default Privacy;
ui/line/index.js
DannyvanderJagt/portfolio
import React from 'react'; import Telescope from 'telescope'; import Config from '../../../portfolio.config'; class Line extends Telescope.Component{ render(){ return ( <div className='line'/> ); } }; export default Line;
map/src/containers/UserRecoverPassword/index.js
teikei/teikei
import React from 'react' import PropTypes from 'prop-types' import { Field, reduxForm } from 'redux-form' import { connect } from 'react-redux' import { recoverPassword } from '../UserOnboarding/duck' import i18n from '../../i18n' import InputField from '../../components/InputField/index' import { validator } from '../../common/formUtils' const RecoverPassword = ({ handleSubmit, error }) => ( <div className="user-account"> <div className="user-container"> <h1>{i18n.t('user.form.forgot_password')}</h1> <form onSubmit={handleSubmit}> <div className="form-inputs"> <strong>{error}</strong> <Field name="email" label={i18n.t('user.form.email')} component={InputField} type="email" maxLength="100" /> <p className="form-explanation"> {i18n.t('user.form.password_explanation')} </p> </div> <div className="form-actions"> <input type="submit" className="button submit" value={i18n.t('user.form.reset_password')} /> </div> </form> </div> </div> ) RecoverPassword.propTypes = { handleSubmit: PropTypes.func.isRequired, error: PropTypes.string, } RecoverPassword.defaultProps = { error: '', } const mapDispatchToProps = (dispatch) => ({ onSubmit: (payload) => dispatch(recoverPassword(payload)), }) const RecoverPasswordContainer = connect( null, mapDispatchToProps )( reduxForm({ form: 'recoverPassword', validate: validator('recoverPassword'), })(RecoverPassword) ) export default RecoverPasswordContainer
src/components/BoardGameItem/BoardGameItem.js
GJMcGowan/personal_site
import React from 'react'; import './BoardGameItem.css'; const BoardGameItem = (props) => { const { item } = props; return ( <li className='col-sm-10 col-sm-offset-1 col-xs-12 column'> <div className='image-container'> <img src={item.imageSource} className='img-fluid boardgame-image' alt={item.name}/> </div> <span className='text-container'> {item.name} </span> </li> ); }; BoardGameItem.propTypes = { item: React.PropTypes.object.isRequired }; export default BoardGameItem;
admin/src/components/AltText.js
geminiyellow/keystone
import React from 'react'; import blacklist from 'blacklist'; import vkey from 'vkey'; var AltText = React.createClass({ getDefaultProps () { return { component: 'span', modifier: '<alt>', normal: '', modified: '' }; }, getInitialState () { return { modified: false }; }, componentDidMount () { document.body.addEventListener('keydown', this.handleKeyDown, false); document.body.addEventListener('keyup', this.handleKeyUp, false); }, componentWillUnmount () { document.body.removeEventListener('keydown', this.handleKeyDown); document.body.removeEventListener('keyup', this.handleKeyUp); }, handleKeyDown (e) { if (vkey[e.keyCode] !== this.props.modifier) return; this.setState({ modified: true }); }, handleKeyUp (e) { if (vkey[e.keyCode] !== this.props.modifier) return; this.setState({ modified: false }); }, render () { var props = blacklist(this.props, 'component', 'modifier', 'normal', 'modified'); return React.createElement(this.props.component, props, this.state.modified ? this.props.modified : this.props.normal); } }); module.exports = AltText;
source/Checkbox.js
thomaswright/bayst
import React from 'react' import { IconButton } from './collator' /**___________________________________________________________________________*/ const Checkbox = ({ isDisabled = false, isChecked = false, color = "black", uncheckedColor, checkedColor, checkedIconProps, uncheckedIconProps, onToggle, disabledColor = "grey", ...props }) => { const checkedPropsApplied = { type: "material", name: "check-box", color: (isDisabled) ? disabledColor : checkedColor || color, underlayColor: "transparent", onPress: (isDisabled) ? undefined : onToggle, ...props, ...checkedIconProps } const uncheckedPropsApplied = { type: "material", name: "check-box-outline-blank", color: (isDisabled) ? disabledColor : uncheckedColor || color, underlayColor: "transparent", onPress: (isDisabled) ? undefined : onToggle, ...props, ...uncheckedIconProps } const resultComp = (isChecked) ? <IconButton {...checkedPropsApplied}/> : <IconButton {...uncheckedPropsApplied}/> return resultComp } /**___________________________________________________________________________*/ const RadioButton = ({ checkedIconProps, uncheckedIconProps, ...props }) => { const resultComp = ( <Checkbox {...props} checkedIconProps={{ name: "radio-button-checked", ...checkedIconProps }} uncheckedIconProps={{ name: "radio-button-unchecked", ...uncheckedIconProps }}/> ) return resultComp } /**___________________________________________________________________________*/ export { Checkbox, RadioButton }
react/IconEmployer/IconEmployer.js
seekinternational/seek-asia-style-guide
import svgMarkup from './IconEmployer.svg'; import React from 'react'; import Icon from '../private/Icon/Icon'; export default function IconEmployer(props) { return <Icon markup={svgMarkup} {...props} />; } IconEmployer.displayName = 'Employer icon';
es/components/toolbar/toolbar-button.js
vovance/3d-demo
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(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; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React, { Component } from 'react'; import PropTypes from 'prop-types'; import * as SharedStyle from '../../shared-style'; //http://www.cssportal.com/css-tooltip-generator/ var STYLE = { width: '30px', height: '30px', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: '5px', fontSize: '25px', position: 'relative', cursor: 'pointer' }; var STYLE_TOOLTIP = { position: 'absolute', width: '140px', color: SharedStyle.COLORS.white, background: SharedStyle.COLORS.black, height: '30px', lineHeight: '30px', textAlign: 'center', visibility: 'visible', borderRadius: '6px', opacity: '0.8', left: '100%', top: '50%', marginTop: '-15px', marginLeft: '15px', zIndex: '999', fontSize: '12px' }; var STYLE_TOOLTIP_PIN = { position: 'absolute', top: '50%', right: '100%', marginTop: '-8px', width: '0', height: '0', borderRight: '8px solid #000000', borderTop: '8px solid transparent', borderBottom: '8px solid transparent' }; var ToolbarButton = function (_Component) { _inherits(ToolbarButton, _Component); function ToolbarButton(props, context) { _classCallCheck(this, ToolbarButton); var _this = _possibleConstructorReturn(this, (ToolbarButton.__proto__ || Object.getPrototypeOf(ToolbarButton)).call(this, props, context)); _this.state = { active: false }; return _this; } _createClass(ToolbarButton, [{ key: 'render', value: function render() { var _this2 = this; var state = this.state, props = this.props; var color = props.active || state.active ? SharedStyle.SECONDARY_COLOR.icon : SharedStyle.PRIMARY_COLOR.icon; return React.createElement( 'div', { style: STYLE, onMouseOver: function onMouseOver(event) { return _this2.setState({ active: true }); }, onMouseOut: function onMouseOut(event) { return _this2.setState({ active: false }); } }, React.createElement( 'div', { style: { color: color }, onClick: props.onClick }, props.children ), state.active ? React.createElement( 'div', { style: STYLE_TOOLTIP }, React.createElement('span', { style: STYLE_TOOLTIP_PIN }), props.tooltip ) : null ); } }]); return ToolbarButton; }(Component); export default ToolbarButton; ToolbarButton.propTypes = { active: PropTypes.bool.isRequired, tooltip: PropTypes.string.isRequired, onClick: PropTypes.func.isRequired };
client/features/settings/page.js
LestaD/InstaClone
import React from 'react' import Helmet from 'react-helmet' import { Link } from 'react-router-dom' import { CommonTemplate } from 'ui' export const SettingsPage = () => ( <CommonTemplate> <Helmet title="Settings" /> Settings | <Link to="/">Feed</Link> </CommonTemplate> )
src/svg-icons/action/view-quilt.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionViewQuilt = (props) => ( <SvgIcon {...props}> <path d="M10 18h5v-6h-5v6zm-6 0h5V5H4v13zm12 0h5v-6h-5v6zM10 5v6h11V5H10z"/> </SvgIcon> ); ActionViewQuilt = pure(ActionViewQuilt); ActionViewQuilt.displayName = 'ActionViewQuilt'; ActionViewQuilt.muiName = 'SvgIcon'; export default ActionViewQuilt;
assets/js/org/component/user-form-dialog.js
ueokande/teamdone
import React, { Component } from 'react'; import Dialog from 'material-ui/Dialog'; import PropTypes from 'prop-types'; import TextField from 'material-ui/TextField'; import FlatButton from 'material-ui/FlatButton'; export default class UserFormDialog extends Component { constructor() { super(); } handleCreate() { if (typeof this.props.submit === 'undefined') { return } let userName = this.userName.getValue(); this.props.submit(userName) } render() { return ( <Dialog open={this.props.open} > <TextField ref={(e) => { this.userName = e; }} hintText="Alice" floatingLabelText="Name" errorText={this.props.userNameError} name="name" fullWidth={true} /><br /> <div style={{ textAlign: "right" }}> <FlatButton label="OK" onTouchTap={() => this.handleCreate()} /> </div> </Dialog> ); } } UserFormDialog.defaultProps = { }; UserFormDialog.propTypes = { open: PropTypes.bool.isRequired, userNameError: PropTypes.string, submit: PropTypes.func };
src/parser/shared/modules/features/Checklist/index.js
fyruna/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import './Checklist.scss'; class Checklist extends React.PureComponent { static propTypes = { children: PropTypes.node, }; render() { const { children } = this.props; return ( <ul className="checklist"> {!children && ( <li> <div className="alert alert-danger"> The checklist is not yet available for this spec. See <a href="https://github.com/WoWAnalyzer/WoWAnalyzer">GitHub</a> or join us on <a href="https://discord.gg/AxphPxU">Discord</a> if you're interested in contributing this. </div> </li> )} {children} </ul> ); } } export default Checklist;
docs/app/Examples/modules/Embed/States/index.js
vageeshb/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const EmbedStatesExamples = () => ( <ExampleSection title='States'> <ComponentExample title='Active' description='An embed can be active.' examplePath='modules/Embed/States/EmbedExampleActive' /> </ExampleSection> ) export default EmbedStatesExamples
src/components/auction/board/BidEntry.js
akeely/twoguysandadream-js
import React from 'react'; export default class BidEntry extends React.Component { constructor(props) { super(props); this.bid = this.bid.bind(this); } minBid(currentBid) { if (currentBid < 10) { return currentBid + 0.5; } return currentBid + 1; }; stepAmount(currentBid) { if (currentBid < 10) { return 0.5; } return 1; }; bidId(playerId) { return `${playerId}.bid.amount`; }; bid() { const playerId = this.props.bid.player.id; const amount = document.getElementById(this.bidId(playerId)).value; this.props.bidFunction(this.props.leagueId, playerId, amount); }; handleKeyPress = (e) => { if (e.key === 'Enter') { this.bid(); } }; render() { const currentBid = this.props.bid.amount; const playerId = this.props.bid.player.id; return ( <div className="input-group"> <input aria-label="Bid" className="form-control input-sm" id={this.bidId(playerId)} min={this.minBid(currentBid)} step={this.stepAmount(currentBid)} type="number" onKeyPress={this.handleKeyPress} /> <div className="input-group-btn"> <button aria-label="Bid" className="btn btn-success btn-sm" onClick={this.bid} type="button">Bid</button> </div> </div> ); }; };
src/components/isdindex/components/slider.js
lq782655835/ReactDemo
import React from 'react'; import { Icon, Tag, Button, Carousel } from 'antd'; class Slider extends React.Component { constructor(props) { super(props); } render(){ /*let settings ={ dots: true, infinite: true, speed: 20, slidesToShow: 1, slidesToScroll: 1 };*/ let carbg1 = require('../../../images/slider1.jpg'); let carbg2 = require('../../../images/slider2.jpg'); return ( <div className='slider' > <Carousel className='carousel' autoplay effect="fade"> {/*<div><SliderImage src='http://pic.c-ctrip.com/h5/supplier_vshop/home_bg.jpg'/></div> <div><SliderImage src='https://oerugfbxb.qnssl.com/wp-content/themes/Earthshaker-1/images/slide/eco.jpg'/></div>*/} <div><SliderImage src={ carbg1 } /></div> <div><SliderImage src={ carbg2 } /></div> </Carousel> {/* <VendorInfo />*/} </div> ); } } class VendorInfo extends React.Component{ render(){ return ( <div className='vendorinfo' data-flex='dir:top cross:center mian:center'> <div><h2>华为笑租车</h2></div> <div><span>上海市长宁区凯旋路448号</span></div> <div><span>客服热线:021-62410215</span></div> <div className='borderline'></div> <div><span>华为笑租车--您的租车旅游顾问</span></div> </div> ); } } class SliderImage extends React.Component{ render(){ let {src} = this.props; // if(src.indexOf('http') == -1){ // src = require(src); // } return ( <img src={src} /> ); } } export default Slider;
app/containers/LocaleToggle/index.js
AK33M/scalable-react
/* * * LanguageToggle * */ import React from 'react'; import { connect } from 'react-redux'; import { selectLocale } from '../LanguageProvider/selectors'; import { changeLocale } from '../LanguageProvider/actions'; import { appLocales } from '../../i18n'; import { createSelector } from 'reselect'; import styles from './styles.css'; import messages from './messages'; import Toggle from 'components/Toggle'; export class LocaleToggle extends React.Component { // eslint-disable-line render() { return ( <div className={styles.localeToggle}> <Toggle values={appLocales} messages={messages} onToggle={this.props.onLocaleToggle} /> </div> ); } } LocaleToggle.propTypes = { onLocaleToggle: React.PropTypes.func, }; const mapStateToProps = createSelector( selectLocale(), (locale) => ({ locale }) ); function mapDispatchToProps(dispatch) { return { onLocaleToggle: (evt) => dispatch(changeLocale(evt.target.value)), dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LocaleToggle);
web/src/main/client/containers/Login.js
cxpqwvtj/himawari
import React from 'react' import { connect } from 'react-redux' import TextField from '@material-ui/core/TextField' import Button from '@material-ui/core/Button' import AppBaseComponent from '../components/AppBaseComponent' class Login extends AppBaseComponent { render() { return ( <div> <div style={{ textAlign: 'center' }}> <span>ログイン</span> </div> <div style={{ textAlign: 'center' }}> <TextField floatingLabelText='メールアドレス' /> </div> <div style={{ textAlign: 'center' }}> <TextField floatingLabelText='パスワード' /> </div> <div style={{ textAlign: 'center' }}> <Button label="Default" style={{ margin: '12px' }} onClick={() => { super.handleUrlChange('/login') }} /> </div> </div> ) } } function mapStateToProps(state, ownProps) { return { } } export default connect(mapStateToProps, { })(Login)
src/index.js
FiberFoundation/Ground
import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render(<div>Fiber Ground</div>, document.getElementById('app'));
app/components/Library.js
robcalcroft/edison
import React from 'react'; import PropTypes from 'prop-types'; import { StyleSheet, TouchableHighlight, View } from 'react-native'; import Title from './Title'; import Header from './Header'; import Subtitle from './Subtitle'; // import Audiobook from './Audiobook'; const styles = StyleSheet.create({ container: { padding: 5, backgroundColor: 'white', }, spacedRow: { flexDirection: 'row', justifyContent: 'space-between', marginTop: 5, marginBottom: 5, }, }); const Library = ({ uid, libraryName, owner, edisonVersion, library, onPress, }) => ( <TouchableHighlight onPress={() => onPress({ uid, libraryName, owner, edisonVersion, library, })} > <View style={styles.container}> <Title>{libraryName}</Title> <Header>{library.length} audiobook{library.length === 1 ? '' : 's'}</Header> <View style={styles.spacedRow}> <Subtitle>By {owner}</Subtitle> </View> </View> </TouchableHighlight> ); Library.propTypes = { uid: PropTypes.string.isRequired, libraryName: PropTypes.string.isRequired, owner: PropTypes.string.isRequired, edisonVersion: PropTypes.string.isRequired, library: PropTypes.arrayOf(PropTypes.object).isRequired, onPress: PropTypes.func.isRequired, }; export default Library;
node_modules/react-bootstrap/es/Media.js
nikhil-ahuja/Express-React
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import MediaBody from './MediaBody'; import MediaHeading from './MediaHeading'; import MediaLeft from './MediaLeft'; import MediaList from './MediaList'; import MediaListItem from './MediaListItem'; import MediaRight from './MediaRight'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'div' }; var Media = function (_React$Component) { _inherits(Media, _React$Component); function Media() { _classCallCheck(this, Media); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Media.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return Media; }(React.Component); Media.propTypes = propTypes; Media.defaultProps = defaultProps; Media.Heading = MediaHeading; Media.Body = MediaBody; Media.Left = MediaLeft; Media.Right = MediaRight; Media.List = MediaList; Media.ListItem = MediaListItem; export default bsClass('media', Media);
index.ios.js
jamesburton/newsappreactnative
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ // Import rn-nodeify shims import './shim'; import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class NewsAppReactNative 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.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('NewsAppReactNative', () => NewsAppReactNative);
src/components/icons/DeleteIcon.js
austinknight/ui-components
import React from 'react'; const DeleteIcon = props => ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 24 24"> {props.title && <title>{props.title}</title>} <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" /> <path d="M0 0h24v24H0z" fill="none" /> </svg> ); export default DeleteIcon;
src/svg-icons/content/sort.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentSort = (props) => ( <SvgIcon {...props}> <path d="M3 18h6v-2H3v2zM3 6v2h18V6H3zm0 7h12v-2H3v2z"/> </SvgIcon> ); ContentSort = pure(ContentSort); ContentSort.displayName = 'ContentSort'; ContentSort.muiName = 'SvgIcon'; export default ContentSort;
src/svg-icons/action/today.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionToday = (props) => ( <SvgIcon {...props}> <path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zM7 10h5v5H7z"/> </SvgIcon> ); ActionToday = pure(ActionToday); ActionToday.displayName = 'ActionToday'; ActionToday.muiName = 'SvgIcon'; export default ActionToday;
src/icons/Battery80Icon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class Battery80Icon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path fillOpacity=".3" d="M34 10.67C34 9.19 32.81 8 31.33 8H28V4h-8v4h-3.33C15.19 8 14 9.19 14 10.67V18h20v-7.33z"/><path d="M14 18v23.33C14 42.8 15.19 44 16.67 44h14.67c1.47 0 2.67-1.19 2.67-2.67V18H14z"/></svg>;} };
src/components/topic/controlbar/TopicFilterBar.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { push } from 'react-router-redux'; import { connect } from 'react-redux'; import { injectIntl } from 'react-intl'; import ActiveFiltersContainer from './ActiveFiltersContainer'; import FilterSelectorContainer from './FilterSelectorContainer'; import { FilterButton } from '../../common/IconButton'; import { toggleFilterControls, filterByFocus, filterByQuery } from '../../../actions/topicActions'; import TimespanSelectorContainer from './timespans/TimespanSelectorContainer'; import { REMOVE_FOCUS } from './FocusSelector'; const localMessages = { permissions: { id: 'topic.changePermissions', defaultMessage: 'Permissions' }, changePermissionsDetails: { id: 'topic.changePermissions.details', defaultMessage: 'Control who else can see and/or change this topic' }, settings: { id: 'topic.changeSettings', defaultMessage: 'Settings' }, changeSettingsDetails: { id: 'topic.changeSettings.details', defaultMessage: 'Edit this topic\'s configuration and visibility' }, filterTopic: { id: 'topic.filter', defaultMessage: 'Filter this Topic' }, startedSpider: { id: 'topic.startedSpider', defaultMessage: 'Started a new spidering job for this topic' }, summaryMessage: { id: 'snapshot.required', defaultMessage: 'You have made some changes that you can only see if you generate a new Snapshot. <a href="{url}">Generate one now</a>.' }, topicHomepage: { id: 'topic.homepage', defaultMessage: 'Topic Summary' }, }; class TopicFilterBar extends React.Component { UNSAFE_componentWillMount() { const { setSideBarContent, handleFilterToggle, handleFocusSelected, handleQuerySelected } = this.props; const { formatMessage } = this.props.intl; const content = ( <> <FilterButton onClick={handleFilterToggle} tooltip={formatMessage(localMessages.filterTopic)} /> <ActiveFiltersContainer onRemoveFocus={() => handleFocusSelected(REMOVE_FOCUS)} onRemoveQuery={() => handleQuerySelected(null)} /> </> ); if (setSideBarContent) { setSideBarContent(content); } } render() { const { topicId, filters, location, handleFocusSelected, handleQuerySelected } = this.props; let timespanControls = null; // use HOC components to render in the filter control in control bar // both the focus and timespans selectors need the snapshot to be selected first if ((filters.snapshotId !== null) && (filters.snapshotId !== undefined)) { timespanControls = <TimespanSelectorContainer topicId={topicId} location={location} filters={filters} />; } return ( <div className="controlbar controlbar-topic"> <div className="main"> <FilterSelectorContainer location={location} onFocusSelected={handleFocusSelected} onQuerySelected={handleQuerySelected} /> {timespanControls} </div> </div> ); } } TopicFilterBar.propTypes = { // from context intl: PropTypes.object.isRequired, // from parent topicId: PropTypes.number, topic: PropTypes.object, location: PropTypes.object, filters: PropTypes.object.isRequired, setSideBarContent: PropTypes.func, goToUrl: PropTypes.func, handleFilterToggle: PropTypes.func.isRequired, handleFocusSelected: PropTypes.func.isRequired, handleQuerySelected: PropTypes.func.isRequired, }; const mapStateToProps = (state, ownProps) => ({ filters: state.topics.selected.filters, topicInfo: state.topics.selected.info, topicId: parseInt(ownProps.topicId, 10), }); const mapDispatchToProps = dispatch => ({ goToUrl: (url) => { dispatch(push(url)); }, handleFilterToggle: () => { dispatch(toggleFilterControls()); }, handleFocusSelected: (focus) => { const selectedFocusId = (focus.foci_id === REMOVE_FOCUS) ? null : focus.foci_id; dispatch(filterByFocus(selectedFocusId)); }, handleQuerySelected: (query) => { const queryToApply = ((query === null) || (query.length === 0)) ? null : query; // treat empty query as removal of query string, using null because '' != * dispatch(filterByQuery(queryToApply)); }, }); export default injectIntl( connect(mapStateToProps, mapDispatchToProps)( TopicFilterBar ) );
examples/universal/client/index.js
bnwan/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import configureStore from '../common/store/configureStore'; import App from '../common/containers/App'; const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const rootElement = document.getElementById('app'); React.render( <Provider store={store}> {() => <App/>} </Provider>, rootElement );
src/demos/graph/1-basic-graph/root.js
uber-common/vis-academy
import React from 'react'; import {render} from 'react-dom'; import App from './src/app'; const element = document.getElementById('root'); render(<App />, element); if (module.hot) { module.hot.accept('./src/app', () => { const Next = require('./src/app').default; render(<Next />, element); }); }
src/svg-icons/image/filter-5.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter5 = (props) => ( <SvgIcon {...props}> <path d="M21 1H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zM3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm14 8v-2c0-1.11-.9-2-2-2h-2V7h4V5h-6v6h4v2h-4v2h4c1.1 0 2-.89 2-2z"/> </SvgIcon> ); ImageFilter5 = pure(ImageFilter5); ImageFilter5.displayName = 'ImageFilter5'; ImageFilter5.muiName = 'SvgIcon'; export default ImageFilter5;
src/js/ui/pages/welcome/newCloudDiary.js
heartnotes/heartnotes
import _ from 'lodash'; import React from 'react'; import Button from '../../components/button'; import SignUpForm from '../../components/welcome/signUpForm'; import Layout from './layout'; import { connectRedux, routing } from '../../helpers/decorators'; var Component = React.createClass({ render: function() { return ( <Layout> <div className="new-cloud-diary"> <SignUpForm onCreate={this._createNew} progressCheckVar={this.props.data.diary.signingUp} /> <Button size="xs" onClick={this._goBack}>Back</Button> </div> </Layout> ); }, componentDidUpdate: function() { if (this.props.data.diary.diaryMgr) { this.props.router.push('/welcome/loadDiary'); } }, _createNew: function(id, password) { return this.props.actions.createDiary( 'cloud', id, password ); }, _goBack: function() { this.props.router.push('/welcome'); }, }); module.exports = connectRedux([ 'createDiary' ])(routing()(Component));
judge/client/src/Views/ProblemView.js
istamenov/NodeJS_Judge
import React, { Component } from 'react'; import Problem from '../Components/Problem'; import SolutionForm from '../Components/SolutionForm'; class ProblemView extends Component { render() { return ( <div className="ProblemView"> <Problem problem = {this.props.problem} /> <SolutionForm submitCallback = {this.props.submitCallback}/> </div> ); } } export default ProblemView;
react_docs/src/components/navigation.js
GobHash/GobHash-Backend
import React from 'react'; import PropTypes from 'prop-types'; import NavigationItem from './navigation_item'; import { footerContent } from '../custom'; function getAllInSectionFromChild(headings, idx) { for (var i = idx; i > 0; i--) { if (headings[i].depth === 2) { return getAllInSection(headings, i); } } } function getAllInSection(headings, idx) { var activeHeadings = []; for (var i = idx + 1; i < headings.length; i++) { if (headings[i].depth === 3) { activeHeadings.push(headings[i].children[0].value); } else if (headings[i].depth === 2) { break; } } return activeHeadings; } export default class Navigation extends React.PureComponent { static propTypes = { ast: PropTypes.object.isRequired, activeSection: PropTypes.string, navigationItemClicked: PropTypes.func.isRequired } render() { var activeHeadings = []; let headings = this.props.ast.children .filter(child => child.type === 'heading'); if (this.props.activeSection) { let activeHeadingIdx = headings.findIndex(heading => heading.children[0].value === this.props.activeSection); let activeHeading = headings[activeHeadingIdx]; if (activeHeading.depth === 3) { activeHeadings = [this.props.activeSection] .concat(getAllInSectionFromChild(headings, activeHeadingIdx)); } // this could potentially have children, try to find them if (activeHeading.depth === 2) { activeHeadings = [this.props.activeSection] .concat(getAllInSection(headings, activeHeadingIdx)); } } activeHeadings = activeHeadings.reduce((memo, heading) => { memo[heading] = true; return memo; }, {}); return (<div className='pad0x small'> {headings .map((child, i) => { let sectionName = child.children[0].value; var active = sectionName === this.props.activeSection; if (child.depth === 1) { return (<div key={i} onClick={this.navigationItemClicked} className='small pad0x quiet space-top1'>{sectionName}</div>); } else if (child.depth === 2) { return (<NavigationItem key={i} href={`#${child.data.id}`} onClick={this.props.navigationItemClicked} active={active} sectionName={sectionName} />); } else if (child.depth === 3) { if (activeHeadings.hasOwnProperty(sectionName)) { return (<div key={i} className='space-left1'> <NavigationItem href={`#${child.data.id}`} onClick={this.props.navigationItemClicked} active={active} sectionName={sectionName} /> </div>); } } })} {footerContent} </div>); } }
src/Col.js
Firfi/meteor-react-bootstrap
import React from 'react'; import classNames from 'classnames'; import styleMaps from './styleMaps'; const Col = React.createClass({ propTypes: { xs: React.PropTypes.number, sm: React.PropTypes.number, md: React.PropTypes.number, lg: React.PropTypes.number, xsOffset: React.PropTypes.number, smOffset: React.PropTypes.number, mdOffset: React.PropTypes.number, lgOffset: React.PropTypes.number, xsPush: React.PropTypes.number, smPush: React.PropTypes.number, mdPush: React.PropTypes.number, lgPush: React.PropTypes.number, xsPull: React.PropTypes.number, smPull: React.PropTypes.number, mdPull: React.PropTypes.number, lgPull: React.PropTypes.number, componentClass: React.PropTypes.node.isRequired }, getDefaultProps() { return { componentClass: 'div' }; }, render() { let ComponentClass = this.props.componentClass; let classes = {}; Object.keys(styleMaps.SIZES).forEach(function (key) { let size = styleMaps.SIZES[key]; let prop = size; let classPart = size + '-'; if (this.props[prop]) { classes['col-' + classPart + this.props[prop]] = true; } prop = size + 'Offset'; classPart = size + '-offset-'; if (this.props[prop] >= 0) { classes['col-' + classPart + this.props[prop]] = true; } prop = size + 'Push'; classPart = size + '-push-'; if (this.props[prop] >= 0) { classes['col-' + classPart + this.props[prop]] = true; } prop = size + 'Pull'; classPart = size + '-pull-'; if (this.props[prop] >= 0) { classes['col-' + classPart + this.props[prop]] = true; } }, this); return ( <ComponentClass {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </ComponentClass> ); } }); export default Col;
installer/templates/new/widgets/graph/graph.js
kittoframework/kitto
import ReactDOM from 'react-dom'; import React from 'react'; import 'd3'; import 'rickshaw'; import {Kitto, Widget} from 'kitto'; import './graph.scss'; class Graph extends Widget { static get defaultProps() { return { graphType: 'area' }; } componentDidMount() { this.$node = $(ReactDOM.findDOMNode(this)); this.current = 0; this.renderGraph(); } renderGraph() { let container = this.$node.parent(); let $gridster = $('.gridster'); let config = Kitto.config(); let widget_base_dimensions = config.widget_base_dimensions; let width = (widget_base_dimensions[0] * container.data('sizex')) + 5 * 2 * (container.data('sizex') - 1); let height = (widget_base_dimensions[1] * container.data('sizey')); this.graph = new Rickshaw.Graph({ element: this.$node[0], width: width, height: height, renderer: this.props.graphType, series: [{color: '#fff', data: [{ x: 0, y: 0 }]}] }); new Rickshaw.Graph.Axis.Time({ graph: this.graph }); new Rickshaw.Graph.Axis.Y({ graph: this.graph, tickFormat: Rickshaw.Fixtures.Number.formatKMBT }); this.graph.render(); } componentWillUpdate(_props, state) { this.graph.series[0].data = state.points; this.current = state.points[state.points.length -1].y; this.graph.render(); } currentValue() { return this.prettyNumber(this.prepend(this.current)); } render() { return ( <div className={this.props.className}> <h1 className="title">{this.props.title}</h1> <h2 className="value">{this.currentValue()}</h2> <p className="more-info">{this.props.moreinfo}</p> </div> ); } }; Widget.mount(Graph); export default Graph;
src/plugins/lists.js
MaxKelsen/ory-slate-plugin
/* eslint-disable prefer-reflect, default-case, react/display-name */ import React from 'react' import ListIcon from 'material-ui-icons/List' import OrderedListIcon from 'material-ui-icons/FormatListNumbered' import createListPlugin from 'slate-edit-list' import type { Props } from './props' import { makeTagNode, ToolbarButton } from '../helpers' import Plugin from './Plugin' export const UL = 'LISTS/UNORDERED-LIST' export const OL = 'LISTS/ORDERED-LIST' export const LI = 'LISTS/LIST-ITEM' export default class ListsPlugin extends Plugin { constructor(props: Props) { super(props) this.plugins = [ createListPlugin({ types: [UL, OL], typeItem: LI, typeDefault: props.DEFAULT_NODE }) ] } props: Props // eslint-disable-next-line react/display-name createButton = (type, icon) => ({ editorState, onChange }: Props) => { const onClick = e => { e.preventDefault() const isList = editorState.blocks.some(block => block.type === LI) const isType = editorState.blocks.some(block => Boolean( editorState.document.getClosest( block.key, parent => parent.type === type ) ) ) let transform = editorState.transform() if (isList && isType) { transform = transform .setBlock(this.DEFAULT_NODE) .unwrapBlock(UL) .unwrapBlock(OL) } else if (isList) { transform = transform.unwrapBlock(type === UL ? OL : UL).wrapBlock(type) } else { transform = transform.setBlock(LI).wrapBlock(type) } onChange(transform.apply()) } const isList = editorState.blocks.some(block => block.type === LI) const isType = editorState.blocks.some(block => Boolean( editorState.document.getClosest( block.key, parent => parent.type === type ) ) ) return ( <ToolbarButton onClick={onClick} isActive={isList && isType} icon={icon} /> ) } name = 'lists' nodes = { [UL]: makeTagNode('ul'), [OL]: makeTagNode('ol'), [LI]: makeTagNode('li') } toolbarButtons = [ this.createButton(UL, <ListIcon />), this.createButton(OL, <OrderedListIcon />) ] deserialize = (el, next) => { switch (el.tagName.toLowerCase()) { case 'ul': return { kind: 'block', type: UL, nodes: next(el.childNodes) } case 'li': return { kind: 'block', type: LI, nodes: next(el.childNodes) } case 'ol': return { kind: 'block', type: OL, nodes: next(el.childNodes) } } } serialize = (object: { type: string, kind: string }, children: any[]) => { if (object.kind !== 'block') { return } switch (object.type) { case UL: return <ul>{children}</ul> case LI: return <li>{children}</li> case OL: return <ol>{children}</ol> } } }
src/Fade.js
dozoisch/react-bootstrap
import classNames from 'classnames'; import React from 'react'; import Transition from 'react-overlays/lib/Transition'; const propTypes = { /** * Show the component; triggers the fade in or fade out animation */ in: React.PropTypes.bool, /** * Unmount the component (remove it from the DOM) when it is faded out */ unmountOnExit: React.PropTypes.bool, /** * Run the fade in animation when the component mounts, if it is initially * shown */ transitionAppear: React.PropTypes.bool, /** * Duration of the fade animation in milliseconds, to ensure that finishing * callbacks are fired even if the original browser transition end events are * canceled */ timeout: React.PropTypes.number, /** * Callback fired before the component fades in */ onEnter: React.PropTypes.func, /** * Callback fired after the component starts to fade in */ onEntering: React.PropTypes.func, /** * Callback fired after the has component faded in */ onEntered: React.PropTypes.func, /** * Callback fired before the component fades out */ onExit: React.PropTypes.func, /** * Callback fired after the component starts to fade out */ onExiting: React.PropTypes.func, /** * Callback fired after the component has faded out */ onExited: React.PropTypes.func, }; const defaultProps = { in: false, timeout: 300, unmountOnExit: false, transitionAppear: false, }; class Fade extends React.Component { render() { return ( <Transition {...this.props} className={classNames(this.props.className, 'fade')} enteredClassName="in" enteringClassName="in" /> ); } } Fade.propTypes = propTypes; Fade.defaultProps = defaultProps; export default Fade;
src/i18n.js
tomek-f/tomekf
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { IntlProvider, injectIntl } from 'react-intl'; import config from 'App/config'; const intl = {}; if (process.env.NODE_ENV === 'test') { // mock for jest, will be removed in prod build by uglifyjs Object.assign(intl, { formatMessage: () => 'Error generic', // add more if needed }); } function processLanguage(localStorageLanguage) { let language = localStorageLanguage || config.language.app; language = config.language.available.includes(language) ? language : config.language.default; return language; } const loadLocaleData = language => [ import( /* webpackChunkName: "language-message-data-[request]" */ /* webpackInclude: /\/(en|pl).json$/ */ `App/locales/${language}.json` // eslint-disable-line comma-dangle ), import( /* webpackChunkName: "react-intl-locale-data-[request]" */ /* webpackInclude: /\/(en|pl).js$/ */ `react-intl/locale-data/${language}.js` // eslint-disable-line comma-dangle ), ]; class IntlGlobalProvider extends Component { static propTypes = { children: PropTypes.node.isRequired, intl: PropTypes.shape().isRequired, }; constructor(props) { super(props); const { intl: intlProp } = this.props; Object.assign(intl, intlProp); } render() { const { children } = this.props; return children; } } const IntlGlobalProviderInjected = injectIntl(IntlGlobalProvider); const IntlProviderCustomPure = ({ children, ...rest }) => ( <IntlProvider {...rest}> <IntlGlobalProviderInjected> {children} </IntlGlobalProviderInjected> </IntlProvider> ); IntlProviderCustomPure.propTypes = { children: PropTypes.node.isRequired, }; const mapStateToProps = ({ app }) => { const language = app.get('language'); return { locale: language, key: language, messages: config.language.cache.messageData[language], }; }; const IntlProviderCustom = connect(mapStateToProps)(IntlProviderCustomPure); export { processLanguage, loadLocaleData, IntlProviderCustom, intl, };
docs/src/app/components/pages/components/IconButton/ExampleTooltip.js
pomerantsev/material-ui
import React from 'react'; import IconButton from 'material-ui/IconButton'; const IconButtonExampleTooltip = () => ( <div> <IconButton iconClassName="muidocs-icon-custom-github" tooltip="bottom-right" tooltipPosition="bottom-right" /> <IconButton iconClassName="muidocs-icon-custom-github" tooltip="bottom-center" tooltipPosition="bottom-center" /> <IconButton iconClassName="muidocs-icon-custom-github" tooltip="bottom-left" tooltipPosition="bottom-left" /> <IconButton iconClassName="muidocs-icon-custom-github" tooltip="top-right" tooltipPosition="top-right" /> <IconButton iconClassName="muidocs-icon-custom-github" tooltip="top-center" tooltipPosition="top-center" /> <IconButton iconClassName="muidocs-icon-custom-github" tooltip="top-left" tooltipPosition="top-left" /> </div> ); export default IconButtonExampleTooltip;
node_modules/eslint-config-airbnb/test/test-react-order.js
ishan993/IshanBlogReactRedux
import test from 'tape'; import { CLIEngine } from 'eslint'; import eslintrc from '../'; import reactRules from '../rules/react'; import reactA11yRules from '../rules/react-a11y'; const cli = new CLIEngine({ useEslintrc: false, baseConfig: eslintrc, rules: { // It is okay to import devDependencies in tests. 'import/no-extraneous-dependencies': [2, { devDependencies: true }], }, }); function lint(text) { // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeontext const linter = cli.executeOnText(text); return linter.results[0]; } function wrapComponent(body) { return ` import React from 'react'; export default class MyComponent extends React.Component { /* eslint no-empty-function: 0, class-methods-use-this: 0 */ ${body} } `; } test('validate react prop order', (t) => { t.test('make sure our eslintrc has React and JSX linting dependencies', (t) => { t.plan(2); t.deepEqual(reactRules.plugins, ['react']); t.deepEqual(reactA11yRules.plugins, ['jsx-a11y', 'react']); }); t.test('passes a good component', (t) => { t.plan(3); const result = lint(wrapComponent(` componentWillMount() {} componentDidMount() {} setFoo() {} getFoo() {} setBar() {} someMethod() {} renderDogs() {} render() { return <div />; }`)); t.notOk(result.warningCount, 'no warnings'); t.notOk(result.errorCount, 'no errors'); t.deepEquals(result.messages, [], 'no messages in results'); }); t.test('order: when random method is first', (t) => { t.plan(2); const result = lint(wrapComponent(` someMethod() {} componentWillMount() {} componentDidMount() {} setFoo() {} getFoo() {} setBar() {} renderDogs() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort'); }); t.test('order: when random method after lifecycle methods', (t) => { t.plan(2); const result = lint(wrapComponent(` componentWillMount() {} componentDidMount() {} someMethod() {} setFoo() {} getFoo() {} setBar() {} renderDogs() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort'); }); });
src/layouts/CoreLayout/CoreLayout.js
dontexpectanythingsensible/password-checker
import React from 'react'; import PropTypes from 'prop-types'; import Header from 'components/Header'; import Footer from 'components/Footer'; import classnames from 'classnames'; import 'styles/core.scss'; export default class CoreLayout extends React.Component { static propTypes = { strength: PropTypes.string, children: PropTypes.element.isRequired }; render () { const level = `strength--${ [this.props.strength] }`; const classes = classnames('core-layout', { [level]: true }); return ( <div className={ classes }> <Header /> <div className='core-layout__viewport container'> { this.props.children } </div> <Footer /> </div> ); } }
src/admin/src/components/controls/renderers/render_datetime.js
jgretz/zen-express
import React from 'react'; import moment from 'moment'; const render = (data, format) => { const m = moment(data); return ( <span>{m.format(format)}</span> ); }; export const renderDateTime = (data) => render(data, 'MMMM Do YYYY, h:mm:ss a'); export const renderDate = (data) => render(data, 'MMMM Do YYYY'); export const renderTime = (data) => render(data, 'h:mm:ss a');
angular2-tour-of-heroes/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
rchcomm/Angular2Tranning
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
lib/components/map/regional.js
conveyal/analysis-ui
import React from 'react' import {useSelector} from 'react-redux' import selectDisplayGrid from 'lib/selectors/regional-display-grid' import selectDisplayScale from 'lib/selectors/regional-display-scale' import createDrawTile from 'lib/utils/create-draw-tile' import Gridualizer from './gridualizer' /** * A map layer showing a Regional comparison */ let key = 0 export default React.memo(function Regional() { const grid = useSelector(selectDisplayGrid) const {error, colorizer} = useSelector(selectDisplayScale) || {} if (!grid || !colorizer || error) return null // Function is cheap. It just wraps draw tile with the necessary parts const drawTile = createDrawTile({colorizer, grid}) // Remount every time there is a change to drawTile return <Gridualizer key={key++} drawTile={drawTile} zIndex={300} /> })
browserify-buble-inferno-compat/index.js
zarjay/react-bundle-showdown
/* global document */ import React from 'react' import { render } from 'react-dom' render(<div>Hello World</div>, document.getElementById('app'))
packages/material-ui/src/Table/TablePagination.js
cherniavskii/material-ui
// @inheritedComponent TableCell import React from 'react'; import PropTypes from 'prop-types'; import withStyles from '../styles/withStyles'; import Input from '../Input'; import { MenuItem } from '../Menu'; import Select from '../Select'; import TableCell from './TableCell'; import Toolbar from '../Toolbar'; import Typography from '../Typography'; import TablePaginationActions from './TablePaginationActions'; export const styles = theme => ({ root: { fontSize: theme.typography.pxToRem(12), // Increase the specificity to override TableCell. '&:last-child': { padding: 0, }, }, toolbar: { height: 56, minHeight: 56, paddingRight: 2, }, spacer: { flex: '1 1 100%', }, caption: { flexShrink: 0, }, input: { fontSize: 'inherit', flexShrink: 0, }, selectRoot: { marginRight: theme.spacing.unit * 4, marginLeft: theme.spacing.unit, color: theme.palette.text.secondary, }, select: { paddingLeft: theme.spacing.unit, paddingRight: theme.spacing.unit * 2, }, selectIcon: { top: 1, }, actions: { flexShrink: 0, color: theme.palette.text.secondary, marginLeft: theme.spacing.unit * 2.5, }, }); /** * A `TableCell` based component for placing inside `TableFooter` for pagination. */ class TablePagination extends React.Component { // This logic would be better handled on userside. // However, we have it just in case. componentDidUpdate() { const { count, onChangePage, page, rowsPerPage } = this.props; const newLastPage = Math.max(0, Math.ceil(count / rowsPerPage) - 1); if (page > newLastPage) { onChangePage(null, newLastPage); } } render() { const { Actions, backIconButtonProps, classes, colSpan: colSpanProp, component: Component, count, labelDisplayedRows, labelRowsPerPage, nextIconButtonProps, onChangePage, onChangeRowsPerPage, page, rowsPerPage, rowsPerPageOptions, SelectProps, ...other } = this.props; let colSpan; if (Component === TableCell || Component === 'td') { colSpan = colSpanProp || 1000; // col-span over everything } return ( <Component className={classes.root} colSpan={colSpan} {...other}> <Toolbar className={classes.toolbar}> <div className={classes.spacer} /> {rowsPerPageOptions.length > 1 && ( <Typography variant="caption" className={classes.caption}> {labelRowsPerPage} </Typography> )} {rowsPerPageOptions.length > 1 && ( <Select classes={{ root: classes.selectRoot, select: classes.select, icon: classes.selectIcon, }} input={<Input className={classes.input} disableUnderline />} value={rowsPerPage} onChange={onChangeRowsPerPage} {...SelectProps} > {rowsPerPageOptions.map(rowsPerPageOption => ( <MenuItem key={rowsPerPageOption} value={rowsPerPageOption}> {rowsPerPageOption} </MenuItem> ))} </Select> )} <Typography variant="caption" className={classes.caption}> {labelDisplayedRows({ from: count === 0 ? 0 : page * rowsPerPage + 1, to: Math.min(count, (page + 1) * rowsPerPage), count, page, })} </Typography> <Actions className={classes.actions} backIconButtonProps={backIconButtonProps} count={count} nextIconButtonProps={nextIconButtonProps} onChangePage={onChangePage} page={page} rowsPerPage={rowsPerPage} /> </Toolbar> </Component> ); } } TablePagination.propTypes = { /** * The component used for displaying the actions. * Either a string to use a DOM element or a component. */ Actions: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), /** * Properties applied to the back arrow `IconButton` component. */ backIconButtonProps: PropTypes.object, /** * Useful to extend the style applied to components. */ classes: PropTypes.object.isRequired, /** * @ignore */ colSpan: PropTypes.number, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), /** * The total number of rows. */ count: PropTypes.number.isRequired, /** * Useful to customize the displayed rows label. */ labelDisplayedRows: PropTypes.func, /** * Useful to customize the rows per page label. Invoked with a `{ from, to, count, page }` * object. */ labelRowsPerPage: PropTypes.node, /** * Properties applied to the next arrow `IconButton` element. */ nextIconButtonProps: PropTypes.object, /** * Callback fired when the page is changed. * * @param {object} event The event source of the callback * @param {number} page The page selected */ onChangePage: PropTypes.func.isRequired, /** * Callback fired when the number of rows per page is changed. * * @param {object} event The event source of the callback */ onChangeRowsPerPage: PropTypes.func, /** * The zero-based index of the current page. */ page: PropTypes.number.isRequired, /** * The number of rows per page. */ rowsPerPage: PropTypes.number.isRequired, /** * Customizes the options of the rows per page select field. If less than two options are * available, no select field will be displayed. */ rowsPerPageOptions: PropTypes.array, /** * Properties applied to the rows per page `Select` element. */ SelectProps: PropTypes.object, }; TablePagination.defaultProps = { Actions: TablePaginationActions, component: TableCell, labelDisplayedRows: ({ from, to, count }) => `${from}-${to} of ${count}`, labelRowsPerPage: 'Rows per page:', rowsPerPageOptions: [5, 10, 25], }; export default withStyles(styles, { name: 'MuiTablePagination' })(TablePagination);
src/admin/views/notifications/index.js
ccetc/platform
import React from 'react' import Collection from 'admin/components/collection' import Feed from './feed' class Notifications extends React.Component { static contextTypes = { modal: React.PropTypes.object } render() { return ( <div className="chrome-notifications"> <div className="chrome-notifications-header"> <div className="chrome-notifications-header-cancel"> </div> <div className="chrome-notifications-header-title"> Notifications </div> <div className="chrome-notifications-header-proceed"> <a onClick={ this._handleClose.bind(this) }> Done </a> </div> </div> <div className="chrome-notifications-body"> <Collection { ...this._getCollection() } /> </div> </div> ) } _getCollection() { return { endpoint: '/admin/notifications', sort: { key: 'created_at', order: 'desc' }, layout: Feed, entity: 'notifications' } } _handleClose() { this.context.modal.pop() } } export default Notifications
Console/app/node_modules/rc-progress/es/Circle.js
RisenEsports/RisenEsports.github.io
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; /* eslint react/prop-types: 0 */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import enhancer from './enhancer'; import { propTypes, defaultProps } from './types'; var Circle = function (_Component) { _inherits(Circle, _Component); function Circle() { _classCallCheck(this, Circle); return _possibleConstructorReturn(this, (Circle.__proto__ || Object.getPrototypeOf(Circle)).apply(this, arguments)); } _createClass(Circle, [{ key: 'getPathStyles', value: function getPathStyles() { var _props = this.props, percent = _props.percent, strokeWidth = _props.strokeWidth, _props$gapDegree = _props.gapDegree, gapDegree = _props$gapDegree === undefined ? 0 : _props$gapDegree, gapPosition = _props.gapPosition; var radius = 50 - strokeWidth / 2; var beginPositionX = 0; var beginPositionY = -radius; var endPositionX = 0; var endPositionY = -2 * radius; switch (gapPosition) { case 'left': beginPositionX = -radius; beginPositionY = 0; endPositionX = 2 * radius; endPositionY = 0; break; case 'right': beginPositionX = radius; beginPositionY = 0; endPositionX = -2 * radius; endPositionY = 0; break; case 'bottom': beginPositionY = radius; endPositionY = 2 * radius; break; default: } var pathString = 'M 50,50 m ' + beginPositionX + ',' + beginPositionY + '\n a ' + radius + ',' + radius + ' 0 1 1 ' + endPositionX + ',' + -endPositionY + '\n a ' + radius + ',' + radius + ' 0 1 1 ' + -endPositionX + ',' + endPositionY; var len = Math.PI * 2 * radius; var trailPathStyle = { strokeDasharray: len - gapDegree + 'px ' + len + 'px', strokeDashoffset: '-' + gapDegree / 2 + 'px', transition: 'stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s' }; var strokePathStyle = { strokeDasharray: percent / 100 * (len - gapDegree) + 'px ' + len + 'px', strokeDashoffset: '-' + gapDegree / 2 + 'px', transition: 'stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s' }; return { pathString: pathString, trailPathStyle: trailPathStyle, strokePathStyle: strokePathStyle }; } }, { key: 'render', value: function render() { var _this2 = this; var _props2 = this.props, prefixCls = _props2.prefixCls, strokeWidth = _props2.strokeWidth, trailWidth = _props2.trailWidth, strokeColor = _props2.strokeColor, trailColor = _props2.trailColor, strokeLinecap = _props2.strokeLinecap, style = _props2.style, className = _props2.className, restProps = _objectWithoutProperties(_props2, ['prefixCls', 'strokeWidth', 'trailWidth', 'strokeColor', 'trailColor', 'strokeLinecap', 'style', 'className']); var _getPathStyles = this.getPathStyles(), pathString = _getPathStyles.pathString, trailPathStyle = _getPathStyles.trailPathStyle, strokePathStyle = _getPathStyles.strokePathStyle; var showCirclePath = restProps.percent > 0; delete restProps.percent; delete restProps.gapDegree; delete restProps.gapPosition; return React.createElement( 'svg', _extends({ className: prefixCls + '-circle ' + className, viewBox: '0 0 100 100', style: style }, restProps), React.createElement('path', { className: prefixCls + '-circle-trail', d: pathString, stroke: trailColor, strokeWidth: trailWidth || strokeWidth, fillOpacity: '0', style: trailPathStyle }), showCirclePath && React.createElement('path', { className: prefixCls + '-circle-path', d: pathString, strokeLinecap: strokeLinecap, stroke: strokeColor, strokeWidth: strokeWidth, fillOpacity: '0', ref: function ref(path) { _this2.path = path; }, style: strokePathStyle }) ); } }]); return Circle; }(Component); Circle.propTypes = _extends({}, propTypes, { gapPosition: PropTypes.oneOf(['top', 'bottom', 'left', 'right']) }); Circle.defaultProps = _extends({}, defaultProps, { gapPosition: 'top' }); export default enhancer(Circle);
frontend/node_modules/react-router/es/RouterContext.js
andres81/auth-service
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 _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; import invariant from 'invariant'; import React from 'react'; import getRouteParams from './getRouteParams'; import { ContextProvider } from './ContextUtils'; import { isReactChildren } from './RouteUtils'; var _React$PropTypes = React.PropTypes, array = _React$PropTypes.array, func = _React$PropTypes.func, object = _React$PropTypes.object; /** * A <RouterContext> renders the component tree for a given router state * and sets the history object and the current location in context. */ var RouterContext = React.createClass({ displayName: 'RouterContext', mixins: [ContextProvider('router')], propTypes: { router: object.isRequired, location: object.isRequired, routes: array.isRequired, params: object.isRequired, components: array.isRequired, createElement: func.isRequired }, getDefaultProps: function getDefaultProps() { return { createElement: React.createElement }; }, childContextTypes: { router: object.isRequired }, getChildContext: function getChildContext() { return { router: this.props.router }; }, createElement: function createElement(component, props) { return component == null ? null : this.props.createElement(component, props); }, render: function render() { var _this = this; var _props = this.props, location = _props.location, routes = _props.routes, params = _props.params, components = _props.components, router = _props.router; var element = null; if (components) { element = components.reduceRight(function (element, components, index) { if (components == null) return element; // Don't create new children; use the grandchildren. var route = routes[index]; var routeParams = getRouteParams(route, params); var props = { location: location, params: params, route: route, router: router, routeParams: routeParams, routes: routes }; if (isReactChildren(element)) { props.children = element; } else if (element) { for (var prop in element) { if (Object.prototype.hasOwnProperty.call(element, prop)) props[prop] = element[prop]; } } if ((typeof components === 'undefined' ? 'undefined' : _typeof(components)) === 'object') { var elements = {}; for (var key in components) { if (Object.prototype.hasOwnProperty.call(components, key)) { // Pass through the key as a prop to createElement to allow // custom createElement functions to know which named component // they're rendering, for e.g. matching up to fetched data. elements[key] = _this.createElement(components[key], _extends({ key: key }, props)); } } return elements; } return _this.createElement(components, props); }, element); } !(element === null || element === false || React.isValidElement(element)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The root route must render a single element') : invariant(false) : void 0; return element; } }); export default RouterContext;
client/landing/components/vision/index.js
bryanph/Geist
import React from 'react' import ReactDom from 'react-dom' import CreationLoop from '../home/CreationLoop' class Landing extends React.Component { constructor(props) { super(props) } render() { const { content } = this.props return ( <React.Fragment> <section className="creationLoopSection"> <h2 className="sectionTitle">A vision: The Creation Loop</h2> <CreationLoop /> </section> </React.Fragment> ) } } export default Landing
admin/client/App/shared/Portal.js
Adam14Four/keystone
/** * Used by the Popout component and the Lightbox component of the fields for * popouts. Renders a non-react DOM node. */ import React from 'react'; import ReactDOM from 'react-dom'; module.exports = React.createClass({ displayName: 'Portal', portalElement: null, // eslint-disable-line react/sort-comp componentDidMount () { const el = document.createElement('div'); document.body.appendChild(el); this.portalElement = el; this.componentDidUpdate(); }, componentWillUnmount () { document.body.removeChild(this.portalElement); }, componentDidUpdate () { ReactDOM.render(<div {...this.props} />, this.portalElement); }, getPortalDOMNode () { return this.portalElement; }, render () { return null; }, });
src/routes/Account/components/Prefs/PathPrefs/PathItem/PathItem.js
bhj/karaoke-forever
import PropTypes from 'prop-types' import React from 'react' import { Draggable } from 'react-beautiful-dnd' import Button from 'components/Button' import Icon from 'components/Icon' import styles from './PathItem.css' const PathItem = props => { const { path, pathId } = props.path return ( <Draggable draggableId={`path-${pathId}`} index={props.index}> {(provided, snapshot) => ( <div className={styles.pathItem} key={pathId} ref={provided.innerRef} style={provided.draggableProps.style} {...provided.draggableProps} > <div {...provided.dragHandleProps}> <Icon icon='DRAG_INDICATOR' size={24} className={styles.btnDrag} /> </div> <div className={styles.pathName}> {path} </div> <Button className={styles.btnClear} data-path-id={pathId} icon='CLEAR' onClick={props.onRemove} size={32} /> </div> )} </Draggable> ) } PathItem.propTypes = { index: PropTypes.number.isRequired, onRemove: PropTypes.func.isRequired, path: PropTypes.object.isRequired, } export default PathItem
src/common/components/ResetPassword/index.js
micahroberson/node-boilerplate
import React from 'react'; import shouldComponentUpdatePure from '../../lib/shouldComponentUpdatePure'; import AuthForm, {Modes} from '../AuthForm'; class ResetPassword extends React.Component { shouldComponentUpdate = shouldComponentUpdatePure; render() { let authFormProps = { mode: Modes.ResetPassword, passwordResetToken: this.props.routeParams.token }; return <AuthForm {...authFormProps} />; } } export default ResetPassword
react/src/components/CommandEditor/CommandEditor.js
ozlerhakan/rapid
/** * Created by hakan on 13/02/2017. */ import React from 'react' import AceEditor from 'react-ace'; import * as shortcuts from './shortcuts'; import * as docker from './docker-editor'; import 'brace/theme/chrome'; import 'brace/ext/searchbox'; import 'brace/ext/language_tools'; import 'brace/ext/keybinding_menu'; import 'brace/snippets/snippets'; class CommandEditor extends React.Component { constructor(props) { super(props); let dValue = "# list all containers\n\nGET containers/json?all=true&size=true"; const dashboard = localStorage.getItem("rapid-dashboard"); if (dashboard) { dValue = dashboard; } this.state = {defaultValue: dValue}; this.onChange = this.onChange.bind(this); this.onBeforeLoad = this.onBeforeLoad.bind(this); } ace = null; onBeforeLoad(ace) { this.ace = ace; docker.init(ace); } onSplitPaneChanged(newValue) { this.aceEditor.editor.session.setWrapLimitRange(0, newValue + 1); this.setState({defaultValue: this.aceEditor.editor.session.getValue()}); } getSelectedText() { return this.aceEditor.editor.getSelectedText(); } addCommandExample(command) { this.aceEditor.editor.session.insert(this.aceEditor.editor.getCursorPosition(), command.example); this.setState({defaultValue: this.aceEditor.editor.session.getValue()}); this.aceEditor.editor.focus(); } onChange() { this.setState({defaultValue: this.aceEditor.editor.session.getValue()}); } componentDidMount() { shortcuts.apply(this.aceEditor.editor,this.ace); } componentDidUpdate() { localStorage.setItem("rapid-dashboard", this.aceEditor.editor.session.getValue()); } render() { return <AceEditor mode="docker" theme="chrome" name="rest_editor" width="100%" height="100%" fontSize={14} tabSize={2} focus wrapEnabled enableBasicAutocompletion enableLiveAutocompletion highlightActiveLine showInvisibles enableSnippets onBeforeLoad={this.onBeforeLoad} onChange={this.onChange} editorProps={{$blockScrolling: Infinity}} value={this.state.defaultValue} ref={(input) => this.aceEditor = input} /> } } export default CommandEditor;
client/src/index.js
apologeticcookie/apologeticcookie
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; ReactDOM.render(<App />, document.querySelector('.app'));
src/containers/userProfile/userProfile.js
psenger/ReactJS-Rapid-Prototype-Template
import moment from 'moment'; import { safeGet } from '../../utils'; import PropTypes from 'prop-types'; import validate from 'validate.js'; import { connect } from 'react-redux'; import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import Form from '../../components/form/form'; import InputText from '../../components/inputText/inputText'; import { Button } from 'react-bootstrap'; import DateField from '../../components/dateField/dateField'; import I18NInjector from '../../decorator/i18nInjector'; import * as ProfileAction from '../../actionCreators/profileAction'; validate.extend(validate.validators.datetime, { // The value is guaranteed not to be null or undefined but otherwise it could be anything. needs to be UTC Unix Timestamp (milliseconds) parse: function (value) { return moment.utc(value).valueOf(); }, // Input is a utc unix timestamp. this example only assumes the format is the date part of a ISO 8601 format: function (value) { return moment.utc().unix(value).format('YYYY-MM-DD'); } }); // http://validatejs.org/ let constraints = { 'name.first': { presence: true, length: {max: 20} }, 'name.last': { length: {min: 4} }, email: { presence: true, email: true }, dob: { datetime: { dateOnly: true } } }; let options = { format: 'flat' }; const getModelToValidate = (target) => { switch (target) { case 'firstName': return (value) => ({name: {first: value} }); case 'lastName': return (value) => ({name: {last: value} }); case 'email': return (email) => ({email}); case 'dob': return (dob) => ({dob: dob}); } }; @I18NInjector() export class UserProfile extends Component { constructor (props) { super(props); this.displayName = 'containers/userProfile'; this.onSubmit = this.onSubmit.bind(this); this.createOnChange = this.createOnChange.bind(this); this.createValidator = this.createValidator.bind(this); this.state = {loading: false}; } componentWillMount () { /** * Test to see if there is an id in the url, if so, load the record. */ if (this.props.match && this.props.match.params && this.props.match.params.id && this.props.match.params.id !== '0') { this.load(this.props.match.params.id); } } load (id) { this.props.profileActionDispatcher.requestProfile(id); } onSubmit () { // @todo PAS working on validation here. // if ( createValidator('*') !== 'success' ) // console.log('onSubmit', this.props.profileAction.updateEmail('xxxxx') ); // console.log('onSubmit'); // this.setState({ type: 'info', message: 'Sending...' }, this.sendFormData); } createOnChange (fn) { return function (e) { fn(e.target.value); }; } // The function _validator_ fires every time the render is called on InputText... // Which only happens when props are changed. createValidator (relatedModelConstraintPaths, constraints, validatorOptions, scope) { // Build a cut down copy of the constraints let _constraints = {}; relatedModelConstraintPaths.forEach(function (cv) { _constraints[cv] = safeGet(constraints, cv, null); }); // What I would like to see is how to get these messages into some model return function (model, dirty = false) { if (!dirty) return 'success'; // validation results will be an array of strings with messages if it fails. undefined if it passes. let validationResults = validate(model, _constraints, validatorOptions); if (validationResults === undefined) { return 'success'; } else { return 'error'; } }.bind(scope); } render () { let {first, last, email} = this.props; let {translate} = this.props.i18n; return ( <section data-component-name={this.displayName}> <h1>{translate('Profile Edit')}</h1> <Form> <InputText fieldId="firstName" label={translate('Enter the first name')} help={translate('The first name is required and can be no larger than %n characters', 20)} placeholder={translate('First Name')} value={first} required={true} onChange={this.createOnChange(this.props.profileActionDispatcher.updateFirstName)} getModelToValidate={getModelToValidate('firstName')} validator={this.createValidator(['name.first'], constraints, options, this)} /> <InputText fieldId="lastName" label={translate('Enter the last name')} help={translate('The last name is required and can be no larger than %n characters', 20)} placeholder={translate('Last Name')} value={last} required={false} onChange={this.createOnChange(this.props.profileActionDispatcher.updateLastName)} getModelToValidate={getModelToValidate('lastName')} validator={this.createValidator(['name.last'], constraints, options, this)} /> <InputText fieldId="email" label={translate('Enter the email')} help={translate('The email is required and must be a valid format')} placeholder={translate('Email')} value={email} required={true} onChange={this.createOnChange(this.props.profileActionDispatcher.updateEmail)} getModelToValidate={getModelToValidate('email')} validator={this.createValidator(['email'], constraints, options, this)} /> <DateField fieldId="dob" label={translate('Enter the Date of Birth')} help={translate('The Date of Birth is required')} placeholder={translate('dob')} value={this.props.dob} day={this.props.day} month={this.props.month} year={this.props.year} onChange={this.createOnChange(this.props.profileActionDispatcher.updateDob)} getModelToValidate={getModelToValidate('dob')} validator={this.createValidator(['dob'], constraints, options, this)} /> <Button type="button" className="btn btn-primary" onClick={this.onSubmit}>{translate('Submit')}</Button> </Form> </section> ); } } // Use props to create warnings in the console if they are missing. UserProfile.propTypes = { profileReducer: PropTypes.object.isRequired }; /** * The default values on the props if they are not set. * * @type {{first: string, last: string, email: string, dob: string, year: number, month: number, day: number}} */ UserProfile.defaultProps = { first: '', last: '', email: '', dob: '2017-01-01', year: 2017, month: 1, day: 1 }; /** * Map a specific store's state to the props. * * @param {*} state - the state of the store/reducer * @param ownProps * @returns {{profileReducer: *, first: *, last: *, email: *, dob: *, year: number, month: number, day: number}} */ let mapStateToProps = (state /**, ownProps **/) => { let def = moment(new Date()).format('YYYY-MM-DD'); /** * ownProp is the props, this component was created with https://github.com/reactjs/redux/issues/693 */ // console.log( safeGet( state,'profileReducer.profile.dob', def ) ); // console.log( safeGet( state,'profileReducer.profile.dob', def ).split('-')[0] ); return { profileReducer: state.profileReducer, // first: ( ifPathExists(state.profileReducer,'profile.name.first') )? state.profileReducer.profile.name.first : '', // last: ( ifPathExists(state.profileReducer,'profile.name.last') )? state.profileReducer.profile.name.last : '', // email: ( ifPathExists(state.profileReducer,'profile.email') ) ? state.profileReducer.profile.email : '', // dob: ( ifPathExists(state.profileReducer,'profile.dob') ) ? state.profileReducer.profile.dob : '', // year: Number( (ifPathExists(state.profileReducer,'profile.dob')||def).split('-')[0] ), // month: Number( (ifPathExists(state.profileReducer,'profile.dob')||def).split('-')[1] ), // day: Number( (ifPathExists(state.profileReducer,'profile.dob')||def).split('-')[2] ) first: safeGet(state, 'profileReducer.profile.name.first', null), last: safeGet(state, 'profileReducer.profile.name.last', null), email: safeGet(state, 'profileReducer.profile.email', null), dob: safeGet(state, 'profileReducer.profile.dob', null), year: Number(safeGet(state, 'profileReducer.profile.dob', def).split('-')[0]), month: Number(safeGet(state, 'profileReducer.profile.dob', def).split('-')[1]), day: Number(safeGet(state, 'profileReducer.profile.dob', def).split('-')[2]) }; }; /** * Map the Action(s)'s Dispatcher(s) to the props. The way this is written all the action's dispatch functions are * mapped to the given name space. * * @param dispatch * @returns {{profileActionDispatcher: (A|B|M|N)}} */ let mapDispatchToProps = (dispatch) => { return { profileActionDispatcher: bindActionCreators(ProfileAction, dispatch) }; }; /** * @TODO: needs more research, I cant figure this out right now. * * * @param stateProps * @param dispatchProps * @param ownProps * @returns {{profileReducer: *, state: *, actions: *}} */ // let mergeProps = (stateProps, dispatchProps /**, ownProps**/) => { // // console.log( 'mergeProps', stateProps, dispatchProps, ownProps); // /** // * Here is where we determine the default values or link them up. // */ // return { // // ...ownProps, // profileReducer: stateProps.profileReducer, // state: stateProps, // actions: dispatchProps // }; // }; export default connect(mapStateToProps, mapDispatchToProps /**, mergeProps **/)(UserProfile); UserProfile.propTypes = { i18n: PropTypes.object.isRequired, profileReducer: PropTypes.object.isRequired, profilesActionDispatcher: PropTypes.object, profileActionDispatcher: PropTypes.object, first: PropTypes.string, last: PropTypes.string, email: PropTypes.string, dob: PropTypes.string, match: PropTypes.object, 'match.params': PropTypes.object, day: PropTypes.number, month: PropTypes.number, year: PropTypes.number };
src/svg-icons/maps/add-location.js
hwo411/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/index.js
selfberry/selfberry-web
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); ReactDOM.render( <App />, document.getElementById('root') );
modules/gui/src/widget/toolbar/context.js
openforis/sepal
import React from 'react' export const Context = React.createContext()
entry_types/scrolled/package/src/contentElements/iframeEmbed/IframeEmbed.js
codevise/pageflow
import React from 'react'; import classNames from 'classnames'; import { ContentElementBox, Figure, FitViewport, useContentElementEditorState, useContentElementLifecycle, usePortraitOrientation } from 'pageflow-scrolled/frontend'; import styles from './IframeEmbed.module.css'; const aspectRatios = { wide: 0.5625, narrow: 0.75, square: 1, portrait: 1.7777 }; export function IframeEmbed({configuration}) { const {shouldLoad} = useContentElementLifecycle(); const {isEditable, isSelected} = useContentElementEditorState(); const portraitOrientation = usePortraitOrientation(); const aspectRatio = portraitOrientation && configuration.portraitAspectRatio ? configuration.portraitAspectRatio : configuration.aspectRatio; return ( <div className={styles.wrapper} style={{pointerEvents: isEditable && !isSelected ? 'none' : undefined}}> <FitViewport aspectRatio={aspectRatios[aspectRatio || 'wide']}> <ContentElementBox> <Figure caption={configuration.caption}> <FitViewport.Content> {shouldLoad && <iframe className={classNames(styles.iframe, styles[`scale-${configuration.scale}`])} title={configuration.title} src={configuration.source} />} </FitViewport.Content> </Figure> </ContentElementBox> </FitViewport> </div> ); }
5.0.0/src/index.js
erikras/redux-form-docs
import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import store from 'redux/store' import DevTools from './components/DevTools' import component from './routes' import Perf from 'react-addons-perf' import devToolsEnabled from './devToolsEnabled' const dest = document.getElementById('content') window.Perf = Perf render( (<Provider store={store}> <div> {component} {devToolsEnabled && !window.devToolsExtension && <DevTools/>} </div> </Provider>), dest )
src/components/DataTable/TableExpandHeader.js
carbon-design-system/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; const TableExpandHeader = props => <th scope="col" {...props} />; export default TableExpandHeader;
TaskMapper/src/components/search/GoogleSearch.js
Elizabeth-Roche/TaskMapper
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ var {GooglePlacesAutocomplete} = require('react-native-google-places-autocomplete'); var UltimateMap = require('../map/UltimateMap'); import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, AsyncStorage, } from 'react-native'; const homePlace = {description: 'Home', geometry: { location: { lat: 48.8152937, lng: 2.4597668 } }}; const workPlace = {description: 'Work', geometry: { location: { lat: 48.8496818, lng: 2.2940881 } }}; class GoogleSearch extends Component { render() { var locationName = '' if (locationName != null ){ locationName = this.props.location.name } else { locationName = 'Search' } return ( <GooglePlacesAutocomplete placeholder={locationName} minLength={2} // minimum length of text to search autoFocus={false} fetchDetails={true} onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true currentSearch = JSON.stringify({location: details.geometry.location, name: details.name}) AsyncStorage.setItem("currentSearch", currentSearch) }} // // module.exports = function() { // return details.geometry.location; // console.log("This"); // } getDefaultValue={() => { return''; // text input default value }} query={{ // available options: https://developers.google.com/places/web-service/autocomplete key: 'AIzaSyC6Vddmul5fb0LppQnNaMbySTzfzbNI9Gc', language: 'en', // language of the results types: '', // default: 'geocode' }} styles={{ description: { fontWeight: 'bold', }, predefinedPlacesDescription: { color: '#1faadb', }, }} currentLocation={true} // Will add a 'Current location' button at the top of the predefined places list currentLocationLabel="Current location" nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch GoogleReverseGeocodingQuery={{ // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro }} GooglePlacesSearchQuery={{ // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search rankby: 'distance', types: 'grocery_or_supermarket', }} filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities // predefinedPlaces={[homePlace, workPlace]} / > ) } } module.exports = GoogleSearch;
modules/dreamview/frontend/src/components/PNCMonitor/StoryTellingMonitor.js
ApolloAuto/apollo
import React from 'react'; import { inject, observer } from 'mobx-react'; import classNames from 'classnames'; import { Tabs, TabList, Tab, TabPanel, } from 'react-tabs'; class StoryItem extends React.PureComponent { render() { const { name, value } = this.props; const textClassNames = classNames({ text: true, active: value, }); return ( <tr className="monitor-table-item"> <td className={textClassNames}>{name.toUpperCase()}</td> <td className={textClassNames}>{value ? 'YES' : 'No'}</td> </tr> ); } } @inject('store') @observer export default class StoryTellingMonitor extends React.Component { render() { const { stories } = this.props.store.storyTellers; let storyTable = null; if (stories.size > 0) { storyTable = stories.entries().map(([story, isOn]) => <StoryItem key={`story_${story}`} name={story} value={isOn} /> ); } else { storyTable = ( <tr className="monitor-table-item"> <td className="text">No Data</td> </tr> ); } return ( <Tabs> <TabList> <Tab>Story Tellers</Tab> </TabList> <TabPanel className="monitor-table-container"> <table className="monitor-table"> <tbody>{storyTable}</tbody> </table> </TabPanel> </Tabs> ); } }
hw5/src/components/article/article.js
lanyangyang025/COMP531
import React from 'react' import { connect } from 'react-redux' import { Comment } from './comment' //content of a card export const Article = ({ _id, author, date, text, img, comments, visible}) => ( <div className="panel panel-default text-left"> <div className="panel-body"> <div className="col-sm-3"> <div className="well"> <p><span>{date}, {author}:</span></p> </div> </div> <div className="col-sm-9"> <p><img src={img} id="december18" className="ys"></img></p> <p>{text}</p> </div> <div> { (visible=="Hide comments" && comments.length>0)? comments.sort((a,b) => { if (a.date < b.date) return 1; if (a.date > b.date) return -1; return 0 }).map( comment => (<Comment commentId={comment.commentId} key={comment.commentId} author={comment.author} date={comment.date} text={comment.text}/>) ) :'' } </div> </div> </div> ) export default connect()(Article)
components/scenes/awesome_summary_scene.js
yamashiro0110/ReactNative
import React, { Component } from 'react'; import { View, Text, Navigator } from 'react-native'; import AwesomeNavigationBar from '../view/awesome_navigation_bar'; import AwesomeTableView from '../view/awesome_tableview'; export default class AwesomeSummary extends Component { render() { return ( <View style={{ flex: 1, }}> <AwesomeNavigationBar title="すごいタイトル" /> <AwesomeTableView /> </View> ); } }
app/src/www/index.js
juanmadurand/flatboard
import Express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import favicon from 'serve-favicon'; import compression from 'compression'; import path from 'path'; import createStore from './store'; import ApiClient from './helpers/ApiClient'; import Html from './helpers/Html'; import { match } from 'react-router'; import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect'; import createHistory from 'react-router/lib/createMemoryHistory'; import { Provider } from 'react-redux'; import getRoutes from './routes'; export function init(app) { app.use(compression()); app.use(favicon(path.join(__dirname, '../..', 'static', 'favicon.png'))); // Set app/static for static assets (needed in prod) app.use(Express.static(path.join(__dirname, '../..', 'static'))); app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const client = new ApiClient(req); const history = createHistory(req.originalUrl); const store = createStore(history, client); function hydrateOnClient() { res.send(`<!doctype html>\n ${ReactDOM.renderToString( <Html assets={webpackIsomorphicTools.assets()} store={store} />)}` ); } if (__DISABLE_SSR__) { hydrateOnClient(); return; } match({ history, routes: getRoutes(store), location: req.originalUrl }, (error, redirectLocation, renderProps) => { if (redirectLocation) { res.redirect(redirectLocation.pathname + redirectLocation.search); } else if (error) { console.error(error); res.status(500); hydrateOnClient(); } else if (renderProps) { loadOnServer({...renderProps, store, helpers: {client}}).then(() => { const component = ( <Provider store={store} key="provider"> <ReduxAsyncConnect {...renderProps} /> </Provider> ); res.status(200); global.navigator = { userAgent: req.headers['user-agent'] }; res.send(`<!doctype html>\n ${ReactDOM.renderToString( <Html assets={webpackIsomorphicTools.assets()} component={component} store={store} />)}` ); }); } else { res.status(404).send('Not found'); } }); }); return Promise.resolve(); }
screens/JobScreen.js
15chrjef/mobileHackerNews
import Exponent from 'exponent'; import React from 'react'; import { StyleSheet, Text, View, Dimensions, ListView, TouchableOpacity, WebView, RefreshControl } from 'react-native'; const {height, width} = Dimensions.get('window'); import Title from '../components/Title.js' export default class JobScreen extends React.Component { constructor(){ super() this.state = { stories: '', webUrl: '', scalesPageToFit: true, refreshing: false } this.fetchData = this.fetchData.bind(this) this._onRefresh = this._onRefresh.bind(this) } componentWillMount(){ this.fetchData() } _onRefresh() { var self = this; this.setState({refreshing: true}); this.fetchData() } fetchData(){ let self = this; fetch('https://hacker-news.firebaseio.com/v0/jobstories.json?print=pretty') .then((response) => { return ((JSON.parse(response._bodyInit)).slice(0,10)) }) .then( async function(stories) { let myStories = []; for(var i = 0; i < stories.length; i++) { await fetch(`https://hacker-news.firebaseio.com/v0/item/${stories[i]}.json?print=pretty`) .then(async (response) => { await myStories.push((JSON.parse(response._bodyInit))) }) } const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); self.setState({ stories: ds.cloneWithRows(myStories) }) if(self.state.refreshing === true) { self.setState({refreshing: false}); } }) .catch((error) => { console.error(error); }); } render() { let self = this; if(this.state.stories !== '' && this.state.webUrl === ''){ return ( <View style={styles.container}> <Title/> <View style={styles.body}> <View> <Text style={styles.screenHeader}>Job Stories</Text> </View> <View style={styles.news}> <ListView contentInset={{bottom:30}} dataSource={this.state.stories} renderFooter={() => <View style={styles.footer}></View>} refreshControl={ <RefreshControl refreshing={self.state.refreshing} onRefresh={self._onRefresh} /> } renderRow={(rowData, sectionId, rowId) => ( <View style={styles.newsRow}> <View style={styles.linkRow}> <Text>{Number(rowId) + 1}. Title: </Text> <TouchableOpacity onPress={function(){ self.setState({ webUrl: rowData.url }) }} > <Text style={styles.link}> {rowData.title} </Text> </TouchableOpacity> </View> <Text>{` `}Author: {rowData.by} Score: {rowData.score}</Text> </View> )} /> </View> </View> </View> ); } else if( this.state.webUrl !== '') { console.log('webviewwebviewwebviewwebview', this.state.webUrl) return ( <View style={styles.container}> <WebView ref={'webview'} automaticallyAdjustContentInsets={false} style={styles.webView} source={{uri: this.state.webUrl}} javaScriptEnabled={true} domStorageEnabled={true} decelerationRate="normal" startInLoadingState={true} scalesPageToFit={this.state.scalesPageToFit} /> <TouchableOpacity style={styles.goBack} onPress={function() { self.setState({ webUrl: '' }) }}> <Text style={{textAlign: 'center'}}> Return to App </Text> </TouchableOpacity> </View> ) } else { return ( <View style={styles.container}> <Title/> <View style={styles.body}> <View> <Text style={styles.screenHeader}>Loading...</Text> </View> </View> </View> ) } } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, body: { flex: 10, alignItems: 'center' }, story: { width: width, height: 30 }, screenHeader: { fontSize: 20 }, linkRow: { flexDirection: 'row', width: width * .7, }, news: { marginTop: 10, width: width * .9 }, newsRow: { marginTop: 10 }, link: { color: 'blue', textDecorationLine : 'underline', width: width * .7, }, goBack: { backgroundColor: 'rgba(200, 200, 200, .9)', justifyContent: 'center', alignItems: 'center', width: width, flex: .07 }, webView: { backgroundColor: 'rgba(255,255,255,0.8)', height: height, width: width }, footer: { paddingBottom: 50 } });
src/components/Pagination/Pagination.js
Chogyuwon/chogyuwon.github.io
import React from 'react'; import classNames from 'classnames/bind'; import { Link } from 'gatsby'; import { PAGINATION } from '../../constants'; import styles from './Pagination.module.scss'; const cx = classNames.bind(styles); const Pagination = ({ prevPagePath, nextPagePath, hasNextPage, hasPrevPage }) => { const prevClassName = cx({ 'pagination__prev-link': true, 'pagination__prev-link--disable': !hasPrevPage }); const nextClassName = cx({ 'pagination__next-link': true, 'pagination__next-link--disable': !hasNextPage }); return ( <div className={styles['pagination']}> <div className={styles['pagination__prev']}> <Link rel="prev" to={prevPagePath} className={prevClassName}>{PAGINATION.PREV_PAGE}</Link> </div> <div className={styles['pagination__next']}> <Link rel="next" to={nextPagePath} className={nextClassName}>{PAGINATION.NEXT_PAGE}</Link> </div> </div> ); }; export default Pagination;
src/components/Results.js
edwardcroh/traveler
import React, { Component } from 'react'; import { connect } from 'react-redux'; class Results extends Component { constructor(props) { super(props) console.log(this.props.results) this.renderResults = this.renderResults.bind(this); } componentDidUpdate() { console.log(this.props.results) } renderResults(results) { return results.map(result => { return <li className="list-group-item"> <ul><h4>{result.name}</h4></ul> <ul>&#9734; {result.rating}/5</ul> <ul>{result.price}</ul> <ul> <a href={result.url}> <img src={result.image_url} className="img-thumbnail" /> </a> </ul> </li> }); } render() { return ( <div className="row"> <div className="col-md-6"> <ul className="list-group" className="pull-left"> <h2><strong>Food Near Me</strong></h2> { this.renderResults(this.props.results.foodNearMe) } </ul> </div> <div className="col-md-6"> <ul className="list-group" className="pull-right"> <h2><strong>Things To Do</strong></h2> { this.renderResults(this.props.results.thingsToDo) } </ul> </div> </div> ); } } function mapStateToProps(state) { return { results: state.results } } export default connect(mapStateToProps, {})(Results);
app/MenuItem.js
mtreilly/react-native-wordpress
import React from 'react'; import { Text, View } from 'react-native'; export default MenuItem = (props) => ( <View> <Text>Menu Title: {props.title}</Text> <Text>Menu URL: {props.url}</Text> </View> );
react/rock-paper-token/src/index.js
ripter/Workshops
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import { GameRoot } from './components/GameRoot'; import * as serviceWorker from './serviceWorker'; ReactDOM.render(<GameRoot />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
packages/wix-style-react/src/CalendarPanelFooter/CalendarPanelFooter.js
wix/wix-style-react
import React from 'react'; import PropTypes from 'prop-types'; import Text from '../Text'; import { Item, ItemGroup, Toolbar } from '../TableToolbar'; import Calendar from '../Calendar'; import Button from '../Button'; import Box from '../Box'; class CalendarPanelFooter extends React.PureComponent { static displayName = 'CalendarPanelFooter'; static propTypes = { dataHook: PropTypes.string, primaryActionLabel: PropTypes.string.isRequired, secondaryActionLabel: PropTypes.string.isRequired, primaryActionDisabled: PropTypes.bool.isRequired, primaryActionOnClick: PropTypes.func.isRequired, secondaryActionOnClick: PropTypes.func.isRequired, selectedDays: PropTypes.oneOfType([ PropTypes.string, PropTypes.instanceOf(Date), PropTypes.shape({ from: PropTypes.oneOfType([ PropTypes.string, PropTypes.instanceOf(Date), ]), to: PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(Date)]), }), ]), /** Formats a Date into a string for displaying the current selected days. Receives a Date instance (not undefined). */ dateToString: PropTypes.func.isRequired, }; render() { const { dataHook, dateToString, secondaryActionLabel, primaryActionLabel, selectedDays: selectedDaysProp, primaryActionDisabled, primaryActionOnClick, secondaryActionOnClick, } = this.props; function getSelectedDaysString(selectedDaysRaw) { if (!selectedDaysRaw) { return ''; } const selectedDays = Calendar.parseValue(selectedDaysRaw); if (Calendar.isRangeValue(selectedDays)) { const toSuffix = selectedDays.to ? ` ${dateToString(selectedDays.to)}` : ''; return `${dateToString(selectedDays.from)} -${toSuffix}`; } else { return dateToString(selectedDays); } } return ( <div data-hook={dataHook}> <Toolbar> <ItemGroup position="start"> <Item> <Text size="small" weight="thin" secondary dataHook="selected-days-text" > {getSelectedDaysString(selectedDaysProp)} </Text> </Item> </ItemGroup> <ItemGroup position="end"> <Box> <Button size="small" priority="secondary" dataHook="secondary-action-button" onClick={secondaryActionOnClick} > {secondaryActionLabel} </Button> <Box margin="0 6px" /> <Button size="small" disabled={primaryActionDisabled} dataHook="primary-action-button" onClick={primaryActionOnClick} > {primaryActionLabel} </Button> </Box> </ItemGroup> </Toolbar> </div> ); } } export default CalendarPanelFooter;