path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/scripts/components/import/searchResult.js
bluedaniel/Kakapo-app
import React from 'react'; import { FormattedMessage, FormattedNumber } from 'react-intl'; import { push } from 'connected-react-router'; import { soundActions } from 'actions/'; export default ({ i, service, sound, dispatch }) => { const handleClick = () => { let actionParams; if (service === 'youtube') { actionParams = { file: sound.videoId, img: sound.img, link: `https://www.youtube.com/watch?v=${sound.videoId}`, name: sound.name, source: 'youtubeStream', tags: sound.tags, }; } if (service === 'soundcloud') { actionParams = sound.scId; } dispatch(soundActions.addSound(service, actionParams)); dispatch(push('/')); }; const viewCountId = service === 'youtube' ? 'youtube.views' : 'soundcloud.plays'; return ( <div className={`${service}-item`} role="button" tabIndex={i} onClick={handleClick} key={sound.videoId} > <div className="thumbnail"> <img src={sound.img} alt={sound.name} /> <span className="duration">{sound.duration}</span> </div> <span className="title"> {sound.name} <span className="view-count"> <FormattedNumber value={sound.viewCount} />{' '} <FormattedMessage id={viewCountId} /> </span> </span> </div> ); };
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/node_modules/antd/es/input-number/index.js
bhathiya/test
import _extends from 'babel-runtime/helpers/extends'; import _defineProperty from 'babel-runtime/helpers/defineProperty'; 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'; var __rest = this && this.__rest || function (s, e) { var t = {}; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; }if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; }return t; }; import React from 'react'; import classNames from 'classnames'; import RcInputNumber from 'rc-input-number'; var InputNumber = function (_React$Component) { _inherits(InputNumber, _React$Component); function InputNumber() { _classCallCheck(this, InputNumber); return _possibleConstructorReturn(this, (InputNumber.__proto__ || Object.getPrototypeOf(InputNumber)).apply(this, arguments)); } _createClass(InputNumber, [{ key: 'render', value: function render() { var _classNames; var _a = this.props, className = _a.className, size = _a.size, others = __rest(_a, ["className", "size"]); var inputNumberClass = classNames((_classNames = {}, _defineProperty(_classNames, this.props.prefixCls + '-lg', size === 'large'), _defineProperty(_classNames, this.props.prefixCls + '-sm', size === 'small'), _classNames), className); return React.createElement(RcInputNumber, _extends({ className: inputNumberClass }, others)); } }]); return InputNumber; }(React.Component); export default InputNumber; InputNumber.defaultProps = { prefixCls: 'ant-input-number', step: 1 };
frontend/src/App.js
Muhiz/filmfinder
import React from 'react'; import {render} from 'react-dom'; import axios from 'axios'; import ShowsList from './ShowsList.js'; let apiBase = 'https://filmfinder-api.herokuapp.com/api'; let theatres = []; let shows = []; let Loader = function(props){ if(!props.isReady){ return (<div className="loader"></div>); } else{ return (<div className="loader-ready"></div>); } } class App extends React.Component { constructor(props) { super(props); // Set initial location to Helsinki this.state = { currentTheatre: 0, // Id of current theatre shows: shows, theatres: theatres, location: { latitude: 60.1695200, longitude: 24.9354500 } } // We need to bind to this this.handleTheatreChange = this.handleTheatreChange.bind(this); this.setClosestTheatre = this.setClosestTheatre.bind(this); //this.loadTheatres = this.loadTheatres.bind(this); } componentDidMount(){ // Ask for user location if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(function(pos){ that.setState({ location: { latitude: pos.coords.latitude, longitude: pos.coords.longitude } }); }); } let that = this; // Fetch theatres axios.get(apiBase+'/theatres').then((response) => { var newTheatres = response.data.theatres; that.setState({theatres: newTheatres}); that.setClosestTheatre(); }).catch((error) => { console.log(error); }); } handleTheatreChange(event){ this.setState({currentTheatre: event.target.value}); // Clear shows this.setState({shows:[]}); // Fetch shows let that = this; axios.get(apiBase+'/theatres/'+event.target.value+'/shows').then((response) => { that.setState({shows: response.data.shows}); }); } setClosestTheatre(){ var closestId = 0; var minDistance = 360; var newTheatres = this.state.theatres.slice(); for (var i = newTheatres.length - 1; i >= 0; i--) { newTheatres.isClosest = false; if(newTheatres[i].location == null){ continue; } var x0 = this.state.location.latitude; var x1 = newTheatres[i].location.lat; var y0 = this.state.location.longitude; var y1 = newTheatres[i].location.lng; var dist = Math.sqrt((x0-x1)*(x0-x1) + (y0-y1)*(y0-y1)); if(dist < minDistance){ minDistance = dist; closestId = i; } } newTheatres[closestId].isClosest = true; this.setState({theatres: newTheatres}); // trigger fake event to update shows var fakeEvent = { target: { value: newTheatres[closestId].id } }; this.handleTheatreChange(fakeEvent); } render() { return ( <div> <div className="header"> <h1>FilmFinder</h1> </div> <div className="content"> <select onChange={this.handleTheatreChange}> <option key="0" value="0">Select theatre...</option> {this.state.theatres.map( function(theatre, i) { return ( <option key={theatre.id} value={theatre.id} selected={theatre.isClosest == true}>{theatre.city} - {theatre.name}</option> ); })} </select> <ShowsList shows={this.state.shows} /> <Loader isReady={this.state.shows.length} /> </div> </div> ); } } render(<App />, document.getElementById('app'));
react/L3/src/index.js
luolisave/starters
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './rootReducer'; import { composeWithDevTools } from 'redux-devtools-extension'; import { Provider } from 'react-redux'; import { BrowserRouter} from 'react-router-dom' import registerServiceWorker from './registerServiceWorker'; const store = createStore( rootReducer, composeWithDevTools( applyMiddleware(thunk) ) ); ReactDOM.render( <BrowserRouter> <Provider store={store}> <App /> </Provider> </BrowserRouter>, document.getElementById('root') ); registerServiceWorker();
index.ios.js
ColdForge/icebox
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; class iceboxiOS 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('iceboxiOS', () => iceboxiOS);
public/javascripts/modules/App.js
McLemore/ant
/* eslint-disable import/no-extraneous-dependencies */ import React from 'react'; import Nav from './Nav'; import util from '../common/util'; import '../../stylesheets/modules/App.less'; class App extends React.Component { render() { let items = [{ key: 'home', to: '/', icon: 'home', name: '首页', }, { key: 'blog', to: '/blog', icon: 'book', name: '博客', }, { key: 'download', to: '/download', icon: 'download', name: '下载', }, { key: 'picture', to: '/picture', icon: 'picture', name: '图片', }, { key: 'lab', to: '/lab', icon: 'code', name: '实验室', }]; if (window.__userinfo.role === 'admin') { items = items.concat([{ key: 'stock', to: '/admin_stock', icon: 'line-chart', name: '股票', }, { key: 'note', to: '/admin_note', icon: 'file-text', name: '笔记', }]); } const pathname = this.props.location.pathname; const selectedKeys = [util.getActiveKey(pathname, items)]; return ( <div> <Nav items={items} selectedKeys={selectedKeys} /> {this.props.children} <footer>京ICP备15002157号-1</footer> </div> ); } } App.propTypes = { children: React.PropTypes.element, location: React.PropTypes.shape({ pathname: React.PropTypes.string, }), }; export default App;
ReactApp/screens/first.load.ios.js
johnsiwicki/tbsrn
/** * First Load * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ 'use strict'; /* ============================== Initialise Component =============================== */ // React import React, { Component } from 'react'; import { StyleSheet, View, Text, TouchableOpacity, StatusBar, TextInput } from 'react-native'; // App Globals import AppStyles from '../styles.ios'; import AppConfig from '../config.ios'; // Screens / Pages import ComingSoon from './soon.ios'; // Components import Button from '../components/button.ios'; /* ============================== View =============================== */ var FirstLoad = React.createClass({ /** * On Load */ componentWillMount: function() { StatusBar.setHidden(true, 'slide'); }, /** * When it unmounts */ componentWillUnmount: function() { StatusBar.setHidden(false, 'slide'); }, /** * Navigates to Sign Up */ _navigate: function() { this.props.navigator.push({ title: 'Sign Up', component: ComingSoon, index: 2 }); }, /** * RENDER */ render() { return ( <View style={[AppStyles.container, styles.containerCover]}> <View style={[AppStyles.paddingHorizontal]}> <Text style={[AppStyles.baseText, AppStyles.p, AppStyles.centered]}> Sign Up Now! </Text> <View style={[AppStyles.spacer_10]} /> <TextInput style={styles.textInput}></TextInput> <TextInput style={styles.textInput}></TextInput> <View style={[AppStyles.spacer_10]} /> <View style={[AppStyles.grid_row]}> <View style={[AppStyles.grid_half, AppStyles.paddingRightSml]}> <Button text={'Sign In/Up Now'} onPress={()=>this._navigate()} /> </View> <View style={[AppStyles.grid_half, AppStyles.paddingLeftSml]}> <Button text={'Skip'} style={'outlined'} onPress={()=>this.props.navigator.pop()} /> </View> </View> </View> </View> ); } }); /* ============================== Styles =============================== */ var styles = StyleSheet.create({ containerCover: { marginTop: -AppConfig.navbarHeight, backgroundColor: "#FFF", justifyContent: 'center', }, textInput:{ height:50, fontSize:15, color:'black', borderColor: 'black', borderWidth: 1, marginLeft:20, marginTop:20, marginRight:20, }, }); /* ============================== Done! =============================== */ module.exports = FirstLoad; module.exports.details = { title: 'FirstLoad' };
framework/react-native/meituan/src/RootScene.js
huajianmao/learning
import React, { Component } from 'react'; import { StyleSheet, Text, View, StatusBar } from 'react-native'; import { Router, Scene, Actions } from 'react-native-router-flux'; import HomeScene from './scene/home/index' import NearbyScene from './scene/nearby/index' import DiscoverScene from './scene/discover/index' import OrderScene from './scene/order/index' import MineScene from './scene/mine/index' import PurchaseScene from './scene/purchase/index' import WebScene from './scene/web/index' import color from './widget/color' import screen from './widget/screen' import system from './widget/system' import TabItem from './widget/tabitem' class RootScene extends Component { render() { return ( <Router ref='router' titleStyle={styles.navigationBarTitle} barButtonIconStyle={styles.navigationBarButtonIcon} navigationBarStyle={styles.navigationBarStyle} getSceneStyle={this.sceneStyle} panHandlers={null} animationStyle={this.animate} onSelect={this.onSelect} onBack={this.onBack}> <Scene initial key='tabBar' tabs tabBarStyle={styles.tabBar} tabBarSelectedItemStyle={styles.tabBarSelectedItem} tabBarSelectedTitleStyle={styles.tabBarSelectedTitle} tabBarUnselectedTitleStyle={styles.tabBarUnselectedTitle}> <Scene key="home" component={HomeScene} title="首页" titleStyle={{ color: 'white' }} navigationBarStyle={{ backgroundColor: color.theme }} statusBarStyle='light-content' image={require('./img/tabbar/[email protected]')} selectedImage={require('./img/tabbar/[email protected]')} icon={TabItem} /> <Scene key="nearby" component={NearbyScene} title="附近" image={require('./img/tabbar/[email protected]')} selectedImage={require('./img/tabbar/[email protected]')} icon={TabItem} /> <Scene key="discover" component={DiscoverScene} title="逛一逛" image={require('./img/tabbar/[email protected]')} selectedImage={require('./img/tabbar/[email protected]')} icon={TabItem} /> <Scene key="order" component={OrderScene} title="订单" image={require('./img/tabbar/[email protected]')} selectedImage={require('./img/tabbar/[email protected]')} icon={TabItem} /> <Scene key="mine" component={MineScene} title="我的" hideNavBar statusBarStyle='light-content' image={require('./img/tabbar/[email protected]')} selectedImage={require('./img/tabbar/[email protected]')} icon={TabItem} /> </Scene> <Scene key='web' component={WebScene} title='加载中' hideTabBar clone /> <Scene key='purchase' component={PurchaseScene} title='团购详情' hideTabBar clone /> </Router> ) } sceneStyle = (props: Object, computedProps: Object) => { const style = { flex: 1, backgroundColor: color.theme, shadowColor: null, shadowOffset: null, shadowOpacity: null, shadowRadius: null, marginTop: 0, marginBottom: 0, }; if (computedProps.isActive) { style.marginTop = computedProps.hideNavBar ? (system.isIOS ? 20 : 0) : (system.isIOS ? 64 : 54); style.marginBottom = computedProps.hideTabBar ? 0 : 50; } return style; } animate = props => { const { position, scene } = props; const index = scene.index; const inputRange = [index - 1, index + 1]; const outputRange = [screen.width, -screen.width]; const translateX = position.interpolate({ inputRange, outputRange }); return { transform: [{ translateX }] }; } onSelect = (el: Object) => { const { sceneKey, statusBarStyle } = el.props if (statusBarStyle) { StatusBar.setBarStyle(statusBarStyle, false) } else { StatusBar.setBarStyle('default', false) } Actions[sceneKey]() } onBack = (el: Object) => { if (el.sceneKey == 'home' && el.children.length == 2) { StatusBar.setBarStyle('light-content', false) } Actions.pop() } } const styles = StyleSheet.create({ tabBar: { backgroundColor: '#ffffff', }, tabBarSelectedItem: { backgroundColor: '#ffffff', }, tabBarSelectedTitle: { color: color.theme, }, tabBarUnselectedTitle: { color: '#979797', }, tabBarSelectedImage: { tintColor: color.theme, }, tabBarUnselectedImage: { tintColor: '#979797' }, navigationBarStyle: { backgroundColor: 'white' }, navigationBarTitle: { color: '#333333' }, navigationBarButtonIcon: { tintColor: color.theme }, }); export default RootScene;
Libraries/Components/WebView/WebView.ios.js
ptomasroos/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule WebView * @noflow */ 'use strict'; var ActivityIndicator = require('ActivityIndicator'); var EdgeInsetsPropType = require('EdgeInsetsPropType'); var React = require('React'); var PropTypes = require('prop-types'); var ReactNative = require('ReactNative'); var StyleSheet = require('StyleSheet'); var Text = require('Text'); var UIManager = require('UIManager'); var View = require('View'); var ViewPropTypes = require('ViewPropTypes'); var ScrollView = require('ScrollView'); var deprecatedPropType = require('deprecatedPropType'); var invariant = require('fbjs/lib/invariant'); var keyMirror = require('fbjs/lib/keyMirror'); var processDecelerationRate = require('processDecelerationRate'); var requireNativeComponent = require('requireNativeComponent'); var resolveAssetSource = require('resolveAssetSource'); var RCTWebViewManager = require('NativeModules').WebViewManager; var BGWASH = 'rgba(255,255,255,0.8)'; var RCT_WEBVIEW_REF = 'webview'; var WebViewState = keyMirror({ IDLE: null, LOADING: null, ERROR: null, }); const NavigationType = keyMirror({ click: true, formsubmit: true, backforward: true, reload: true, formresubmit: true, other: true, }); const JSNavigationScheme = 'react-js-navigation'; type ErrorEvent = { domain: any, code: any, description: any, } type Event = Object; const DataDetectorTypes = [ 'phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all', ]; var defaultRenderLoading = () => ( <View style={styles.loadingView}> <ActivityIndicator /> </View> ); var defaultRenderError = (errorDomain, errorCode, errorDesc) => ( <View style={styles.errorContainer}> <Text style={styles.errorTextTitle}> Error loading page </Text> <Text style={styles.errorText}> {'Domain: ' + errorDomain} </Text> <Text style={styles.errorText}> {'Error Code: ' + errorCode} </Text> <Text style={styles.errorText}> {'Description: ' + errorDesc} </Text> </View> ); /** * `WebView` renders web content in a native view. * *``` * import React, { Component } from 'react'; * import { WebView } from 'react-native'; * * class MyWeb extends Component { * render() { * return ( * <WebView * source={{uri: 'https://github.com/facebook/react-native'}} * style={{marginTop: 20}} * /> * ); * } * } *``` * * You can use this component to navigate back and forth in the web view's * history and configure various properties for the web content. */ class WebView extends React.Component { static JSNavigationScheme = JSNavigationScheme; static NavigationType = NavigationType; static propTypes = { ...ViewPropTypes, html: deprecatedPropType( PropTypes.string, 'Use the `source` prop instead.' ), url: deprecatedPropType( PropTypes.string, 'Use the `source` prop instead.' ), /** * Loads static html or a uri (with optional headers) in the WebView. */ source: PropTypes.oneOfType([ PropTypes.shape({ /* * The URI to load in the `WebView`. Can be a local or remote file. */ uri: PropTypes.string, /* * The HTTP Method to use. Defaults to GET if not specified. * NOTE: On Android, only GET and POST are supported. */ method: PropTypes.string, /* * Additional HTTP headers to send with the request. * NOTE: On Android, this can only be used with GET requests. */ headers: PropTypes.object, /* * The HTTP body to send with the request. This must be a valid * UTF-8 string, and will be sent exactly as specified, with no * additional encoding (e.g. URL-escaping or base64) applied. * NOTE: On Android, this can only be used with POST requests. */ body: PropTypes.string, }), PropTypes.shape({ /* * A static HTML page to display in the WebView. */ html: PropTypes.string, /* * The base URL to be used for any relative links in the HTML. */ baseUrl: PropTypes.string, }), /* * Used internally by packager. */ PropTypes.number, ]), /** * Function that returns a view to show if there's an error. */ renderError: PropTypes.func, // view to show if there's an error /** * Function that returns a loading indicator. */ renderLoading: PropTypes.func, /** * Function that is invoked when the `WebView` has finished loading. */ onLoad: PropTypes.func, /** * Function that is invoked when the `WebView` load succeeds or fails. */ onLoadEnd: PropTypes.func, /** * Function that is invoked when the `WebView` starts loading. */ onLoadStart: PropTypes.func, /** * Function that is invoked when the `WebView` load fails. */ onError: PropTypes.func, /** * Boolean value that determines whether the web view bounces * when it reaches the edge of the content. The default value is `true`. * @platform ios */ bounces: PropTypes.bool, /** * A floating-point number that determines how quickly the scroll view * decelerates after the user lifts their finger. You may also use the * string shortcuts `"normal"` and `"fast"` which match the underlying iOS * settings for `UIScrollViewDecelerationRateNormal` and * `UIScrollViewDecelerationRateFast` respectively: * * - normal: 0.998 * - fast: 0.99 (the default for iOS web view) * @platform ios */ decelerationRate: ScrollView.propTypes.decelerationRate, /** * Boolean value that determines whether scrolling is enabled in the * `WebView`. The default value is `true`. * @platform ios */ scrollEnabled: PropTypes.bool, /** * Controls whether to adjust the content inset for web views that are * placed behind a navigation bar, tab bar, or toolbar. The default value * is `true`. */ automaticallyAdjustContentInsets: PropTypes.bool, /** * The amount by which the web view content is inset from the edges of * the scroll view. Defaults to {top: 0, left: 0, bottom: 0, right: 0}. */ contentInset: EdgeInsetsPropType, /** * Function that is invoked when the `WebView` loading starts or ends. */ onNavigationStateChange: PropTypes.func, /** * A function that is invoked when the webview calls `window.postMessage`. * Setting this property will inject a `postMessage` global into your * webview, but will still call pre-existing values of `postMessage`. * * `window.postMessage` accepts one argument, `data`, which will be * available on the event object, `event.nativeEvent.data`. `data` * must be a string. */ onMessage: PropTypes.func, /** * Boolean value that forces the `WebView` to show the loading view * on the first load. */ startInLoadingState: PropTypes.bool, /** * The style to apply to the `WebView`. */ style: ViewPropTypes.style, /** * Determines the types of data converted to clickable URLs in the web view’s content. * By default only phone numbers are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes: PropTypes.oneOfType([ PropTypes.oneOf(DataDetectorTypes), PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), ]), /** * Boolean value to enable JavaScript in the `WebView`. Used on Android only * as JavaScript is enabled by default on iOS. The default value is `true`. * @platform android */ javaScriptEnabled: PropTypes.bool, /** * Boolean value to control whether DOM Storage is enabled. Used only in * Android. * @platform android */ domStorageEnabled: PropTypes.bool, /** * Set this to provide JavaScript that will be injected into the web page * when the view loads. */ injectedJavaScript: PropTypes.string, /** * Sets the user-agent for the `WebView`. * @platform android */ userAgent: PropTypes.string, /** * Boolean that controls whether the web content is scaled to fit * the view and enables the user to change the scale. The default value * is `true`. */ scalesPageToFit: PropTypes.bool, /** * Function that allows custom handling of any web view requests. Return * `true` from the function to continue loading the request and `false` * to stop loading. * @platform ios */ onShouldStartLoadWithRequest: PropTypes.func, /** * Boolean that determines whether HTML5 videos play inline or use the * native full-screen controller. The default value is `false`. * * **NOTE** : In order for video to play inline, not only does this * property need to be set to `true`, but the video element in the HTML * document must also include the `webkit-playsinline` attribute. * @platform ios */ allowsInlineMediaPlayback: PropTypes.bool, /** * Boolean that determines whether HTML5 audio and video requires the user * to tap them before they start playing. The default value is `true`. */ mediaPlaybackRequiresUserAction: PropTypes.bool, /** * Function that accepts a string that will be passed to the WebView and * executed immediately as JavaScript. */ injectJavaScript: PropTypes.func, /** * Specifies the mixed content mode. i.e WebView will allow a secure origin to load content from any other origin. * * Possible values for `mixedContentMode` are: * * - `'never'` (default) - WebView will not allow a secure origin to load content from an insecure origin. * - `'always'` - WebView will allow a secure origin to load content from any other origin, even if that origin is insecure. * - `'compatibility'` - WebView will attempt to be compatible with the approach of a modern web browser with regard to mixed content. * @platform android */ mixedContentMode: PropTypes.oneOf([ 'never', 'always', 'compatibility' ]), }; state = { viewState: WebViewState.IDLE, lastErrorEvent: (null: ?ErrorEvent), startInLoadingState: true, }; componentWillMount() { if (this.props.startInLoadingState) { this.setState({viewState: WebViewState.LOADING}); } } render() { var otherView = null; if (this.state.viewState === WebViewState.LOADING) { otherView = (this.props.renderLoading || defaultRenderLoading)(); } else if (this.state.viewState === WebViewState.ERROR) { var errorEvent = this.state.lastErrorEvent; invariant( errorEvent != null, 'lastErrorEvent expected to be non-null' ); otherView = (this.props.renderError || defaultRenderError)( errorEvent.domain, errorEvent.code, errorEvent.description ); } else if (this.state.viewState !== WebViewState.IDLE) { console.error( 'RCTWebView invalid state encountered: ' + this.state.loading ); } var webViewStyles = [styles.container, styles.webView, this.props.style]; if (this.state.viewState === WebViewState.LOADING || this.state.viewState === WebViewState.ERROR) { // if we're in either LOADING or ERROR states, don't show the webView webViewStyles.push(styles.hidden); } var onShouldStartLoadWithRequest = this.props.onShouldStartLoadWithRequest && ((event: Event) => { var shouldStart = this.props.onShouldStartLoadWithRequest && this.props.onShouldStartLoadWithRequest(event.nativeEvent); RCTWebViewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier); }); var decelerationRate = processDecelerationRate(this.props.decelerationRate); var source = this.props.source || {}; if (this.props.html) { source.html = this.props.html; } else if (this.props.url) { source.uri = this.props.url; } const messagingEnabled = typeof this.props.onMessage === 'function'; var webView = <RCTWebView ref={RCT_WEBVIEW_REF} key="webViewKey" style={webViewStyles} source={resolveAssetSource(source)} injectedJavaScript={this.props.injectedJavaScript} bounces={this.props.bounces} scrollEnabled={this.props.scrollEnabled} decelerationRate={decelerationRate} contentInset={this.props.contentInset} automaticallyAdjustContentInsets={this.props.automaticallyAdjustContentInsets} onLoadingStart={this._onLoadingStart} onLoadingFinish={this._onLoadingFinish} onLoadingError={this._onLoadingError} messagingEnabled={messagingEnabled} onMessage={this._onMessage} onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} scalesPageToFit={this.props.scalesPageToFit} allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback} mediaPlaybackRequiresUserAction={this.props.mediaPlaybackRequiresUserAction} dataDetectorTypes={this.props.dataDetectorTypes} />; return ( <View style={styles.container}> {webView} {otherView} </View> ); } /** * Go forward one page in the web view's history. */ goForward = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.goForward, null ); }; /** * Go back one page in the web view's history. */ goBack = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.goBack, null ); }; /** * Reloads the current page. */ reload = () => { this.setState({viewState: WebViewState.LOADING}); UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.reload, null ); }; /** * Stop loading the current page. */ stopLoading = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.stopLoading, null ); }; /** * Posts a message to the web view, which will emit a `message` event. * Accepts one argument, `data`, which must be a string. * * In your webview, you'll need to something like the following. * * ```js * document.addEventListener('message', e => { document.title = e.data; }); * ``` */ postMessage = (data) => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.postMessage, [String(data)] ); }; /** * Injects a javascript string into the referenced WebView. Deliberately does not * return a response because using eval() to return a response breaks this method * on pages with a Content Security Policy that disallows eval(). If you need that * functionality, look into postMessage/onMessage. */ injectJavaScript = (data) => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.injectJavaScript, [data] ); }; /** * We return an event with a bunch of fields including: * url, title, loading, canGoBack, canGoForward */ _updateNavigationState = (event: Event) => { if (this.props.onNavigationStateChange) { this.props.onNavigationStateChange(event.nativeEvent); } }; /** * Returns the native `WebView` node. */ getWebViewHandle = (): any => { return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]); }; _onLoadingStart = (event: Event) => { var onLoadStart = this.props.onLoadStart; onLoadStart && onLoadStart(event); this._updateNavigationState(event); }; _onLoadingError = (event: Event) => { event.persist(); // persist this event because we need to store it var {onError, onLoadEnd} = this.props; onError && onError(event); onLoadEnd && onLoadEnd(event); console.warn('Encountered an error loading page', event.nativeEvent); this.setState({ lastErrorEvent: event.nativeEvent, viewState: WebViewState.ERROR }); }; _onLoadingFinish = (event: Event) => { var {onLoad, onLoadEnd} = this.props; onLoad && onLoad(event); onLoadEnd && onLoadEnd(event); this.setState({ viewState: WebViewState.IDLE, }); this._updateNavigationState(event); }; _onMessage = (event: Event) => { var {onMessage} = this.props; onMessage && onMessage(event); } } var RCTWebView = requireNativeComponent('RCTWebView', WebView, { nativeOnly: { onLoadingStart: true, onLoadingError: true, onLoadingFinish: true, onMessage: true, messagingEnabled: PropTypes.bool, }, }); var styles = StyleSheet.create({ container: { flex: 1, }, errorContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: BGWASH, }, errorText: { fontSize: 14, textAlign: 'center', marginBottom: 2, }, errorTextTitle: { fontSize: 15, fontWeight: '500', marginBottom: 10, }, hidden: { height: 0, flex: 0, // disable 'flex:1' when hiding a View }, loadingView: { backgroundColor: BGWASH, flex: 1, justifyContent: 'center', alignItems: 'center', height: 100, }, webView: { backgroundColor: '#ffffff', } }); module.exports = WebView;
src/client/app/footer.react.js
skaldo/este
import Component from '../components/component.react'; import React from 'react'; import {FormattedHTMLMessage} from 'react-intl'; export default class Footer extends Component { static propTypes = { msg: React.PropTypes.object.isRequired } render() { const {msg: {app: {footer}}} = this.props; return ( <footer> <p> <FormattedHTMLMessage message={footer.madeByHtml} /> </p> </footer> ); } }
actor-apps/app-web/src/app/utils/require-auth.js
nguyenhongson03/actor-platform
import React from 'react'; import LoginStore from 'stores/LoginStore'; export default (Component) => { return class Authenticated extends React.Component { static willTransitionTo(transition) { if (!LoginStore.isLoggedIn()) { transition.redirect('/auth', {}, {'nextPath': transition.path}); } } render() { return <Component {...this.props}/>; } }; };
src/main.js
avidreder/monmach-client
import React from 'react' import ReactDOM from 'react-dom' import createStore from './store/createStore' import AppContainer from './containers/AppContainer' // ======================================================== // Store Instantiation // ======================================================== const initialState = window.___INITIAL_STATE__ const store = createStore(initialState) // ======================================================== // Render Setup // ======================================================== const MOUNT_NODE = document.getElementById('root') let render = () => { const routes = require('./routes/index').default(store) ReactDOM.render( <AppContainer store={store} routes={routes} />, MOUNT_NODE ) } // This code is excluded from production bundle if (__DEV__) { if (module.hot) { // Development render functions const renderApp = render const renderError = (error) => { const RedBox = require('redbox-react').default ReactDOM.render(<RedBox error={error} />, MOUNT_NODE) } // Wrap render in try/catch render = () => { try { renderApp() } catch (error) { renderError(error) } } // Setup hot module replacement module.hot.accept('./routes/index', () => setImmediate(() => { ReactDOM.unmountComponentAtNode(MOUNT_NODE) render() }) ) } } // ======================================================== // Go! // ======================================================== render()
Frontend/src/search-bar.js
fabiofernandesx/kbArticle
import React, { Component } from 'react'; class SearchBar extends Component { constructor(props){ super(props); this.state={ term: '' }; } render() { return( <div className="form-group"> <label>Start to typing for articles search</label> <input type="text" className="form-control" placeholder="Search..." value={ this.state.term } onChange={ event => this.onInputChange( event.target.value) } /> </div> ); } onInputChange(term){ this.setState({term}); this.props.onSearchTermChange(term); } } export default SearchBar;
ui/js/dfv/src/components/field-wrapper/field-error-boundary.js
pods-framework/pods
/** * External dependencies */ import React from 'react'; import PropTypes from 'prop-types'; class FieldErrorBoundary extends React.Component { constructor( props ) { super( props ); this.state = { hasError: false, error: null, }; } static getDerivedStateFromError( error ) { return { hasError: true, error, }; } componentDidCatch( error, errorInfo ) { // eslint-disable-next-line no-console console.warn( 'There was an error rendering this field.', error, errorInfo ); } render() { if ( this.state.hasError ) { return ( <div>There was an error rendering the field.</div> ); } return <>{ this.props.children }</>; } } FieldErrorBoundary.propTypes = { children: PropTypes.element.isRequired, }; export default FieldErrorBoundary;
examples/tree-view/index.js
joaomilho/redux
import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import Node from './containers/Node' import configureStore from './store/configureStore' import generateTree from './generateTree' const tree = generateTree() const store = configureStore(tree) render( <Provider store={store}> <Node id={0} /> </Provider>, document.getElementById('root') )
app/components/link/index.js
MakersLab/farm-client
import React from 'react'; const Link = (href, a) => (<a href={href}>{a}</a>); export default Link;
src/Textfield/Helptext.js
kradio3/react-mdc-web
import PropTypes from 'prop-types'; import React from 'react'; import classnames from 'classnames'; const propTypes = { children: PropTypes.node, focused: PropTypes.bool, helptextPersistent: PropTypes.bool, helptextValidation: PropTypes.bool, invalid: PropTypes.bool, }; const ROOT = 'mdc-text-field-helper-text'; const PERSISTENT = 'mdc-text-field-helper-text--persistent'; const VALIDATION = 'mdc-text-field-helper-text--validation-msg'; const Helptext = ({ children, focused, helptextPersistent, helptextValidation, invalid, }) => { const validationMsgNeedsDisplay = helptextValidation && invalid; const ariaHidden = !focused && !helptextPersistent && !validationMsgNeedsDisplay; const ariaProp = ariaHidden ? { 'aria-hidden': true } : {}; const roleProp = validationMsgNeedsDisplay ? { role: 'alert' } : {}; return ( <p className={classnames( ROOT, { [PERSISTENT]: helptextPersistent, [VALIDATION]: helptextValidation, }, )} {...ariaProp} {...roleProp} > {children} </p> ); }; Helptext.propTypes = propTypes; export default Helptext;
mxcube3/ui/containers/PleaseWaitDialog.js
mguijarr/mxcube3
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { Modal, ProgressBar, Button } from 'react-bootstrap'; import { setLoading } from '../actions/general'; export class PleaseWaitDialog extends React.Component { constructor(props) { super(props); this.getHideFun = this.getHideFun.bind(this); this.abort = this.abort.bind(this); } getTitle() { return this.props.title || 'Please wait'; } getMessage() { return this.props.message || ''; } getHideFun() { let fun = this.props.setLoadingFalse; if (this.props.blocking) { fun = this.props.setLoadingTrue; } return fun; } abort() { if (this.props.abortFun) { this.props.abortFun(); } this.props.setLoadingFalse(); } renderHeader() { let header = ( <Modal.Header closeButton> <Modal.Title>{this.getTitle()}</Modal.Title> </Modal.Header> ); if (this.props.blocking) { header = ( <Modal.Header> <Modal.Title>{this.getTitle()}</Modal.Title> </Modal.Header> ); } return header; } renderFooter() { let footer = ( <Modal.Footer> <Button onClick={this.getHideFun()}>OK</Button> </Modal.Footer> ); if (this.props.blocking) { footer = ( <Modal.Footer> <Button onClick={this.abort}>Cancel</Button> </Modal.Footer> ); } return footer; } renderContent() { let content = ( <div> <p> {this.getMessage()} </p> </div>); if (this.props.blocking) { content = ( <div> <p> {this.getMessage()} </p> <ProgressBar active now={100} /> </div>); } return content; } render() { return ( <Modal ref="modal" animation={false} show={this.props.loading} onHide={this.getHideFun}> {this.renderHeader()} <Modal.Body closeButton> {this.renderContent()} </Modal.Body> {this.renderFooter()} </Modal> ); } } function mapStateToProps(state) { return { loading: state.general.loading, title: state.general.title, message: state.general.message, blocking: state.general.blocking, abortFun: state.general.abortFun }; } function mapDispatchToProps(dispatch) { return { setLoadingFalse: bindActionCreators(setLoading.bind(this, false), dispatch), setLoadingTrue: bindActionCreators(setLoading.bind(this, true), dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(PleaseWaitDialog);
src/components/buttons/Button.js
ProAI/react-essentials
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import BaseTouchable from '../../utils/rnw-compat/BaseTouchable'; import { BUTTON_COLORS, SIZES } from '../../utils/constants'; import useAction, { ActionPropTypes } from '../../hooks/useAction'; import useTrigger, { TriggerPropTypes } from '../../hooks/useTrigger'; import useLink, { LinkPropTypes } from '../../hooks/useLink'; import concatClasses from '../../utils/concatClasses'; import concatTouchableProps from '../../utils/concatTouchableProps'; import optional from '../../utils/optional'; const propTypes = { ...TriggerPropTypes, ...LinkPropTypes, ...ActionPropTypes, children: PropTypes.node.isRequired, color: PropTypes.oneOf(BUTTON_COLORS), size: PropTypes.oneOf(SIZES), outline: PropTypes.bool, block: PropTypes.bool, caret: PropTypes.bool, active: PropTypes.bool, disabled: PropTypes.bool, }; const Button = React.forwardRef((props, ref) => { const { color = 'primary', size, outline = false, block = false, caret = false, toggle, dismiss, target, to, replace = false, external = false, keepFocus = false, active = false, disabled = false, ...elementProps } = props; const trigger = useTrigger(toggle, dismiss, target); const link = useLink(to, replace, external); const action = useAction(keepFocus); const classes = cx( // constant classes 'btn', outline ? `btn-outline-${color}` : `btn-${color}`, // variable classes size === 'sm' && 'btn-sm', size === 'lg' && 'btn-lg', active && 'active', disabled && 'disabled', block && 'btn-block', caret && 'dropdown-toggle', ...concatClasses(trigger), ); return ( <BaseTouchable {...concatTouchableProps({ ...elementProps, ref }, action, link, trigger)} {...optional(active, { 'aria-pressed': true })} disabled={disabled} essentials={{ className: classes }} /> ); }); Button.displayName = 'Button'; Button.propTypes = propTypes; export default Button;
app/javascript/flavours/glitch/components/display_name.js
im-in-space/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { autoPlayGif } from 'flavours/glitch/util/initial_state'; export default class DisplayName extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map, className: PropTypes.string, inline: PropTypes.bool, localDomain: PropTypes.string, others: ImmutablePropTypes.list, handleClick: PropTypes.func, }; handleMouseEnter = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-original'); } } handleMouseLeave = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-static'); } } render() { const { account, className, inline, localDomain, others, onAccountClick } = this.props; const computedClass = classNames('display-name', { inline }, className); if (!account) return null; let displayName, suffix; let acct = account.get('acct'); if (acct.indexOf('@') === -1 && localDomain) { acct = `${acct}@${localDomain}`; } if (others && others.size > 0) { displayName = others.take(2).map(a => ( <a href={a.get('url')} target='_blank' onClick={(e) => onAccountClick(a.get('acct'), e)} title={`@${a.get('acct')}`} rel='noopener noreferrer' > <bdi key={a.get('id')}> <strong className='display-name__html' dangerouslySetInnerHTML={{ __html: a.get('display_name_html') }} /> </bdi> </a> )).reduce((prev, cur) => [prev, ', ', cur]); if (others.size - 2 > 0) { displayName.push(` +${others.size - 2}`); } suffix = ( <a href={account.get('url')} target='_blank' onClick={(e) => onAccountClick(account.get('acct'), e)} rel='noopener noreferrer'> <span className='display-name__account'>@{acct}</span> </a> ); } else { displayName = <bdi><strong className='display-name__html' dangerouslySetInnerHTML={{ __html: account.get('display_name_html') }} /></bdi>; suffix = <span className='display-name__account'>@{acct}</span>; } return ( <span className={computedClass} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> {displayName} {inline ? ' ' : null} {suffix} </span> ); } }
src/routes/user/Filter.js
tigaly/antd-admin
import React from 'react' import PropTypes from 'prop-types' import moment from 'moment' import { FilterItem } from '../../components' import { Form, Button, Row, Col, DatePicker, Input, Cascader, Switch } from 'antd' import city from '../../utils/city' const Search = Input.Search const { RangePicker } = DatePicker const ColProps = { xs: 24, sm: 12, style: { marginBottom: 16, }, } const TwoColProps = { ...ColProps, xl: 96, } const Filter = ({ onAdd, isMotion, switchIsMotion, onFilterChange, filter, form: { getFieldDecorator, getFieldsValue, setFieldsValue, }, }) => { const handleFields = (fields) => { const { createTime } = fields if (createTime.length) { fields.createTime = [createTime[0].format('YYYY-MM-DD'), createTime[1].format('YYYY-MM-DD')] } return fields } const handleSubmit = () => { let fields = getFieldsValue() fields = handleFields(fields) onFilterChange(fields) } const handleReset = () => { const fields = getFieldsValue() for (let item in fields) { if ({}.hasOwnProperty.call(fields, item)) { if (fields[item] instanceof Array) { fields[item] = [] } else { fields[item] = undefined } } } setFieldsValue(fields) handleSubmit() } const handleChange = (key, values) => { let fields = getFieldsValue() fields[key] = values fields = handleFields(fields) onFilterChange(fields) } const { name, address } = filter let initialCreateTime = [] if (filter.createTime && filter.createTime[0]) { initialCreateTime[0] = moment(filter.createTime[0]) } if (filter.createTime && filter.createTime[1]) { initialCreateTime[1] = moment(filter.createTime[1]) } return ( <Row gutter={24}> <Col {...ColProps} xl={{ span: 4 }} md={{ span: 8 }}> {getFieldDecorator('name', { initialValue: name })(<Search placeholder="Search Name" size="large" onSearch={handleSubmit} />)} </Col> <Col {...ColProps} xl={{ span: 4 }} md={{ span: 8 }}> {getFieldDecorator('address', { initialValue: address })( <Cascader size="large" style={{ width: '100%' }} options={city} placeholder="Please pick an address" onChange={handleChange.bind(null, 'address')} />)} </Col> <Col {...ColProps} xl={{ span: 6 }} md={{ span: 8 }} sm={{ span: 12 }}> <FilterItem label="Createtime"> {getFieldDecorator('createTime', { initialValue: initialCreateTime })( <RangePicker style={{ width: '100%' }} size="large" onChange={handleChange.bind(null, 'createTime')} /> )} </FilterItem> </Col> <Col {...TwoColProps} xl={{ span: 10 }} md={{ span: 24 }} sm={{ span: 24 }}> <div style={{ display: 'flex', justifyContent: 'space-between' }}> <div > <Button type="primary" size="large" className="margin-right" onClick={handleSubmit}>Search</Button> <Button size="large" onClick={handleReset}>Reset</Button> </div> <div> <Switch style={{ marginRight: 16 }} size="large" defaultChecked={isMotion} onChange={switchIsMotion} checkedChildren={'Motion'} unCheckedChildren={'Motion'} /> <Button size="large" type="ghost" onClick={onAdd}>Create</Button> </div> </div> </Col> </Row> ) } Filter.propTypes = { onAdd: PropTypes.func, isMotion: PropTypes.bool, switchIsMotion: PropTypes.func, form: PropTypes.object, filter: PropTypes.object, onFilterChange: PropTypes.func, } export default Form.create()(Filter)
src/Enterbutton.js
RuiGeng/interview_test
import React from 'react' export default React.createClass({ render: function() { return( <div className = "row" > <button type="button" className = "mainlogin mainlogin__nextbtn main--center" onClick={this.props.validateUser}>{this.props.text}</button> </div> ); } });
docs/src/Root.js
zerkms/react-bootstrap
import React from 'react'; import Router from 'react-router'; const Root = React.createClass({ statics: { /** * Get the list of pages that are renderable * * @returns {Array} */ getPages() { return [ 'index.html', 'introduction.html', 'getting-started.html', 'components.html', 'support.html' ]; } }, getDefaultProps() { return { assetBaseUrl: '' }; }, childContextTypes: { metadata: React.PropTypes.object }, getChildContext(){ return { metadata: this.props.propData }; }, render() { // Dump out our current props to a global object via a script tag so // when initialising the browser environment we can bootstrap from the // same props as what each page was rendered with. let browserInitScriptObj = { __html: `window.INITIAL_PROPS = ${JSON.stringify(this.props)}; // console noop shim for IE8/9 (function (w) { var noop = function () {}; if (!w.console) { w.console = {}; ['log', 'info', 'warn', 'error'].forEach(function (method) { w.console[method] = noop; }); } }(window));` }; let head = { __html: `<title>React-Bootstrap</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="${this.props.assetBaseUrl}/assets/bundle.css" rel="stylesheet"> <link href="${this.props.assetBaseUrl}/assets/favicon.ico?v=2" type="image/x-icon" rel="shortcut icon"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-sham.js"></script> <![endif]-->` }; return ( <html> <head dangerouslySetInnerHTML={head} /> <body> <Router.RouteHandler propData={this.props.propData} /> <script dangerouslySetInnerHTML={browserInitScriptObj} /> <script src={`${this.props.assetBaseUrl}/assets/bundle.js`} /> </body> </html> ); } }); export default Root;
src/docs/components/samples/ConfirmationForm.js
grommet/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Box from 'grommet/components/Box'; import Form from 'grommet/components/Form'; import FormFields from 'grommet/components/FormFields'; import FormField from 'grommet/components/FormField'; import Header from 'grommet/components/Header'; import CheckBox from 'grommet/components/CheckBox'; import Footer from 'grommet/components/Footer'; import Button from 'grommet/components/Button'; export default class ConfirmationForm extends Component { constructor () { super(); this._onSubmit = this._onSubmit.bind(this); this._onChangeCheckBox = this._onChangeCheckBox.bind(this); this.state = {acknowledged: false, error: null}; } _onSubmit (event) { event.preventDefault(); if (this.state.acknowledged) { this.props.onSubmit(); } else { this.setState({error: 'required'}); } } _onChangeCheckBox (event) { var acknowledged = event.target.checked; this.setState({acknowledged: acknowledged}); if (acknowledged) { this.setState({error: null}); } } render () { const p = this.props.prefix; return ( <Box full="vertical" justify="center"> <Form onSubmit={this._onSubmit} compact={this.props.compact}> <Header> <h1>Confirmation</h1> </Header> <FormFields> <fieldset> <p>You must acknowledge the destructive aspects of this action.</p> <FormField error={this.state.error}> <CheckBox id={p + "agree"} name="agree" label="I acknowledge that I may lose data." onChange={this._onChangeCheckBox} /> </FormField> </fieldset> </FormFields> <Footer pad={{vertical: 'medium'}}> <Button label="Destroy" primary={true} onClick={this._onSubmit} /> </Footer> </Form> </Box> ); } }; ConfirmationForm.propTypes = { compact: PropTypes.bool, onCancel: PropTypes.func, onSubmit: PropTypes.func, prefix: PropTypes.string }; ConfirmationForm.defaultProps = { prefix: 'cf' };
src/components/PageControl.js
jacklam718/react-native-carousel-component
// @flow import React, { Component } from 'react'; import type { ReactElement } from 'react'; import { View, StyleSheet } from 'react-native'; const CIRCLE_SIZE = 4; const styles = StyleSheet.create({ container: { alignItems: 'center', justifyContent: 'center', }, innerContainer: { flexDirection: 'row', }, circle: { margin: 2, width: CIRCLE_SIZE, height: CIRCLE_SIZE, borderRadius: CIRCLE_SIZE / 2, }, full: { backgroundColor: '#fff', }, empty: { backgroundColor: '#fff5', }, }); type Props = { style?: any; count: number; selectedIndex: number; } const defaultProps = { style: null, }; function Circle({ isSelected }: { isSelected: boolean }): ReactElement { const extraStyle = isSelected ? styles.full : styles.empty; return ( <View style={[styles.circle, extraStyle]} /> ); } class PageControl extends Component { static defaultProps = defaultProps props: Props render() { const { style, count, selectedIndex, } = this.props; const images = []; for (let i = 0; i < count; i += 1) { const isSelected = selectedIndex === i; images.push(<Circle key={i} isSelected={isSelected} />); } return ( <View style={[styles.container, style]}> <View style={styles.innerContainer}> {images} </View> </View> ); } } export default PageControl;
src/components/LoginForm.js
brianyamasaki/rideshare
import React, { Component } from 'react'; import { TouchableWithoutFeedback, Image } from 'react-native'; import { connect } from 'react-redux'; import { Actions } from 'react-native-router-flux'; import { Card, CardSection, InputNoLabel, Button, Spinner, AnchorText, ErrorMessage } from './common'; import { emailChanged, passwordChanged, loginUser } from '../actions'; class LoginForm extends Component { onEmailChange(text) { this.props.emailChanged(text); } onPasswordChange(text) { this.props.passwordChanged(text); } onButtonPress() { const { email, password } = this.props; this.props.loginUser({ email, password }); } autoLogin() { this.onEmailChange('[email protected]'); this.onPasswordChange('foobar1'); } renderButton() { if (this.props.loading) { return <Spinner size='large' />; } return ( <Button onPress={this.onButtonPress.bind(this)}> Login </Button> ); } render() { return ( <Card> <TouchableWithoutFeedback onPress={this.autoLogin.bind(this)}> <Image source={require('../assets/rideshare.png')} style={styles.iconStyle} /> </TouchableWithoutFeedback> <CardSection> <InputNoLabel placeholder="email" onChangeText={this.onEmailChange.bind(this)} value={this.props.email} /> </CardSection> <CardSection> <InputNoLabel secureTextEntry placeholder='password' onChangeText={this.onPasswordChange.bind(this)} value={this.props.password} /> </CardSection> <ErrorMessage> {this.props.errorMsg} </ErrorMessage> <CardSection> {this.renderButton()} </CardSection> <CardSection> <AnchorText onPress={() => Actions.createAccount()}> Create an account </AnchorText> </CardSection> </Card> ); } } const styles = { iconStyle: { alignSelf: 'center', height: 70, width: 80, marginVertical: 10, } }; const mapStateToProps = (state) => { const { email, password, errorMsg, loading } = state.auth; return { email, password, errorMsg, loading }; }; export default connect(mapStateToProps, { emailChanged, passwordChanged, loginUser })(LoginForm);
src/browser/app/Header.js
TheoMer/Gyms-Of-The-World
// @flow import type { State, User } from '../../common/types'; import React from 'react'; import linksMessages from '../../common/app/linksMessages'; import { Box } from '../../common/components'; import { FormattedMessage } from 'react-intl'; import { Link } from '../components'; import { compose } from 'ramda'; import { connect } from 'react-redux'; const HeaderLink = ({ to, message, ...props }) => ( <FormattedMessage {...message}> {message => ( <Link backgroundColor="primary" bold color="white" paddingHorizontal={0.5} paddingVertical={0.5} to={to} {...props} > {message} </Link> )} </FormattedMessage> ); type HeaderProps = { viewer: ?User, }; const Header = ({ viewer }: HeaderProps) => ( <Box backgroundColor="primary" flexWrap="wrap" flexDirection="row" marginVertical={0.5} paddingHorizontal={0.5} > <HeaderLink exact to="/" message={linksMessages.home} /> <HeaderLink to="/users" message={linksMessages.users} /> <HeaderLink to="/todos" message={linksMessages.todos} /> <HeaderLink to="/fields" message={linksMessages.fields} /> <HeaderLink to="/intl" message={linksMessages.intl} /> <HeaderLink to="/offline" message={linksMessages.offline} /> <HeaderLink to="/me" message={linksMessages.me} /> {!viewer && <HeaderLink to="/signin" message={linksMessages.signIn} />} </Box> ); export default compose( connect((state: State) => ({ viewer: state.users.viewer })), )(Header);
util/ReadJSON.js
xeejp/xee_double_auction
import React from 'react' export function ReadJSON() { if (typeof ReadJSON.text === 'undefined') ReadJSON.text = require('./language.json') return ReadJSON.text } export function LineBreak(text) { var regex = /(\n)/g return text.split(regex).map(function (line) { if (line.match(regex)) { return React.createElement('br') } else { return line } }) } export function SplitAndInsert(text, dynamic_text) { var split = text.match(/<[^<^>]+>/g) var strings = text.split(/<[^<^>]+>/g) for(let i = 0; i < split.length; i++) { let temp = dynamic_text let value = split[i].slice(1, split[i].length - 1).split(/[\s ]*,[\s ]*/) for(let i = 0; i < value.length; i++){ temp = temp[value[i]] } strings[i] += temp? temp : split[i] } return LineBreak(strings.join("")) } export function InsertVariable(text, variables, dynamic_variables) { if(dynamic_variables) Object.assign(variables, dynamic_variables) Object.keys(variables).forEach(key => text = text.split('<' + key + '>').join(variables[key])) return text; }
src/components/slide.js
waywaaard/spectacle
/* eslint-disable no-invalid-this */ import React from 'react'; import PropTypes from 'prop-types'; import isUndefined from 'lodash/isUndefined'; import { getStyles } from '../utils/base'; import Radium from 'radium'; import { addFragment } from '../actions'; import { Transitionable, renderTransition } from './transitionable'; import stepCounter from '../utils/step-counter'; @Transitionable @Radium class Slide extends React.PureComponent { constructor(props) { super(props); this.stepCounter = stepCounter(); } state = { contentScale: 1, transitioning: true, z: 1, zoom: 1 }; getChildContext() { return { stepCounter: { setFragments: this.stepCounter.setFragments }, slideHash: this.props.hash }; } componentDidMount() { this.setZoom(); const slide = this.slideRef; const frags = slide.querySelectorAll('.fragment'); if (frags && frags.length && !this.context.overview) { Array.prototype.slice.call(frags, 0).forEach((frag, i) => { frag.dataset.fid = i; return ( this.props.dispatch && this.props.dispatch( addFragment({ slide: this.props.hash, id: i, visible: this.props.lastSlideIndex > this.props.slideIndex, }) ) ); }); } window.addEventListener('load', this.setZoom); window.addEventListener('resize', this.setZoom); } componentDidUpdate() { const { steps, slideIndex } = this.stepCounter.getSteps(); if (this.props.getAppearStep) { if (slideIndex === this.props.slideIndex) {this.props.getAppearStep(steps);} } } componentWillUnmount() { window.removeEventListener('resize', this.setZoom); } setZoom = () => { const mobile = window.matchMedia('(max-width: 628px)').matches; const content = this.contentRef; if (content) { const zoom = this.props.viewerScaleMode ? 1 : content.offsetWidth / this.context.contentWidth; const contentScaleY = content.parentNode.offsetHeight / this.context.contentHeight; const contentScaleX = this.props.viewerScaleMode ? content.parentNode.offsetWidth / this.context.contentWidth : content.parentNode.offsetWidth / this.context.contentHeight; const minScale = Math.min(contentScaleY, contentScaleX); let contentScale = minScale < 1 ? minScale : 1; if (mobile && this.props.viewerScaleMode !== true) { contentScale = 1; } this.setState({ zoom: zoom > 0.6 ? zoom : 0.6, contentScale, }); } }; allStyles() { const { align, print } = this.props; const styles = { outer: { position: this.props.export ? 'relative' : 'absolute', top: 0, left: 0, width: '100%', height: '100%', display: 'flex', overflow: 'hidden', backgroundColor: this.context.styles.global.body.background ? this.context.styles.global.body.background : '', ...this.props.style, }, inner: { display: 'flex', position: 'relative', flex: 1, alignItems: align ? align.split(' ')[1] : 'center', justifyContent: align ? align.split(' ')[0] : 'center', }, content: { flex: 1, maxHeight: this.context.contentHeight || 700, maxWidth: this.context.contentWidth || 1000, transform: `scale(${this.state.contentScale})`, padding: this.state.zoom > 0.6 ? this.props.margin || 40 : 10, }, }; const overViewStyles = { inner: { flexDirection: 'column', }, content: { width: '100%', }, }; const printStyles = print ? { backgroundColor: 'white', backgroundImage: 'none', } : {}; return { styles, overViewStyles, printStyles }; } @renderTransition render() { const { presenterStyle, children } = this.props; const { styles, overViewStyles, printStyles } = this.allStyles(); if (!this.props.viewerScaleMode) { document.documentElement.style.fontSize = `${16 * this.state.zoom}px`; } const contentClass = isUndefined(this.props.className) ? '' : this.props.className; return ( <div className="spectacle-slide" ref={s => { this.slideRef = s; }} style={[ styles.outer, getStyles.call(this), printStyles, presenterStyle, ]} > <div style={[styles.inner, this.context.overview && overViewStyles.inner]} > <div ref={c => { this.contentRef = c; }} className={`${contentClass} spectacle-content`} style={[ styles.content, this.context.styles.components.content, this.context.overview && overViewStyles.content, ]} > {children} </div> </div> </div> ); } } Slide.defaultProps = { align: 'center center', presenterStyle: {}, style: {}, viewerScaleMode: false, }; Slide.propTypes = { align: PropTypes.string, children: PropTypes.node, className: PropTypes.string, dispatch: PropTypes.func, export: PropTypes.bool, getAppearStep: PropTypes.func, hash: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), lastSlideIndex: PropTypes.number, margin: PropTypes.number, notes: PropTypes.any, presenterStyle: PropTypes.object, print: PropTypes.bool, slideIndex: PropTypes.number, style: PropTypes.object, viewerScaleMode: PropTypes.bool, }; Slide.contextTypes = { styles: PropTypes.object, contentWidth: PropTypes.number, contentHeight: PropTypes.number, export: PropTypes.bool, print: PropTypes.object, overview: PropTypes.bool, store: PropTypes.object }; Slide.childContextTypes = { slideHash: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), stepCounter: PropTypes.shape({ setFragments: PropTypes.func }) }; export default Slide;
src/routes/adminNew/index.js
oct16/Blog-FE
import React from 'react'; import Layout from 'components/Layout'; import New from './New'; const title = 'New Post'; export default { path: '/admin/new', name: 'new', action() { return { title, component: <Layout><New title={title} /></Layout>, }; }, };
core/src/plugins/access.ajxp_conf/res/js/AdminPlugins/updater/UpdaterDashboard.js
pydio/pydio-core
/* * Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io> * This file is part of Pydio. * * Pydio is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pydio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Pydio. If not, see <http://www.gnu.org/licenses/>. * * The latest code can be found at <https://pydio.com>. */ import React from 'react' import PluginEditor from '../core/PluginEditor' import {RaisedButton, Checkbox} from 'material-ui' const UpdaterDashboard = React.createClass({ mixins:[AdminComponents.MessagesConsumerMixin], getInitialState: function(){ return {checks: -1, version:'...', versionDate:''}; }, componentDidMount:function(){ this.checkForUpgrade(); this.checkCurrentVersion(); }, checkCurrentVersion(){ PydioApi.getClient().request({get_action:'get_version_info'}, (transp)=>{ if(transp.responseJSON){ this.setState(transp.responseJSON); } }); }, checkForUpgrade: function(){ this.setState({loading:true}); PydioApi.getClient().request({get_action:'get_upgrade_path'}, function(transp){ this.setState({loading:false}); if(!this.isMounted()) return; var response = transp.responseJSON; var length = 0; if(response && response.packages.length){ length = response.packages.length; this.setState({packages:response.packages}); if(response.latest_note){ let latest = response.latest_note; latest = pydio.Parameters.get('ajxpServerAccess') + '&get_action=display_upgrade_note'; this.setState({src:latest}); } }else{ this.setState({no_upgrade:true}); } var node = pydio.getContextNode(); node.getMetadata().set('flag', length); AdminComponents.MenuItemListener.getInstance().notify("item_changed"); }.bind(this)); }, performUpgrade: function(){ if(this.state.checks < 0){ alert('Please select at least one package!'); return; } if(confirm(this.context.getMessage('15', 'updater'))){ var client = PydioApi.getClient(); this.setState({src:''}, function(){ this.setState({src: client._baseUrl + '?secure_token=' + pydio.Parameters.get("SECURE_TOKEN") + '&get_action=perform_upgrade&package_index=' + this.state.checks}); }.bind(this)); } }, onCheckStateChange: function(index, value){ if(value) this.setState({checks: index}); else this.setState({checks: index - 1}); }, render:function(){ var list = null; const {packages, checks, loading} = this.state; if(packages){ list = ( <div style={{paddingBottom:30,paddingRight:5}}> <span style={{float:'right'}}> <RaisedButton primary={true} label={this.context.getMessage('4', 'updater')} onTouchTap={this.performUpgrade}/> </span> {this.context.getMessage('16', 'updater')} <div style={{paddingLeft:30}}>{packages.map((p, index) => { return <div><Checkbox style={{listStyle:'inherit'}} key={p} label={PathUtils.getBasename(p)} onCheck={(e,v)=> this.onCheckStateChange(index, v)} checked={index <= checks} /></div> })}</div> <br/>{this.context.getMessage('3', 'updater')} </div> ); }else if(this.state && this.state.loading){ list = ( <div>{this.context.getMessage('17', 'updater')}</div> ); }else{ list = ( <div> <span style={{float:'right'}}> <RaisedButton secondary={true} label={this.context.getMessage('20', 'updater')} onTouchTap={this.checkForUpgrade}/> </span> { (this.state && this.state.no_upgrade) ? this.context.getMessage('18', 'updater') : this.context.getMessage('19', 'updater') } </div> ); } var updateCheckPane = ( <div style={{padding:'0 20px'}}> <h3>{this.context.getMessage('2', 'updater')}</h3> <div style={{paddingBottom:20,paddingRight:5}}>{list}</div> <iframe ref="iframe" style={{width:'100%',height:400, border:'1px solid #ccc'}} src={this.state?this.state.src:''} ></iframe> </div> ); const {version, versionDate} = this.state; let additionalDescription; if(version === '##VERSION_NUMBER##'){ additionalDescription = this.context.getMessage('21', 'updater'); }else if (version !== '...') { additionalDescription = this.context.getMessage('22', 'updater').replace('%1', version).replace('%2', versionDate); } return ( <div className="update-checker" style={{height:'100%'}}> <PluginEditor {...this.props} additionalDescription={additionalDescription} additionalPanes={{top:[updateCheckPane], bottom:[]}} /> </div> ); } }); export {UpdaterDashboard as default}
Hebrides/SmartHome/Global/Constant.js
HarrisLee/React-Native-Express
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { Platform, Dimensions } from 'react-native'; const {height,width} = Dimensions.get('window'); // 第一种设置全局变量的方法 // export default { // nameExport : '全局变量', // screen_width : width, // screen_height : height, // status_height : (Platform.OS === 'ios' ? 20 : 25), // navigtor_height : (Platform.OS === 'ios' ? 44 : 54), // textColor : '#333333', // fontSize_26 : 13, // } // 第二种设置全局变量的方法 module.exports = { nameExport : '全局变量', screen_width : width, screen_height : height, status_height : (Platform.OS === 'ios' ? 20 : 25), navigtor_height : (Platform.OS === 'ios' ? 44 : 54), textColor : '#333333', fontSize_26 : 13, } // 第三种设置全局变量的方法 global.CONSTANST = { website : 'reactnative.cn', name : 'React Native 中文网', showNaviBar: true, screen_width : width, screen_height : height, } global.CONFIG = { host : 'smarthome.suning.com', hostname : '苏宁智能', }
src/svg-icons/action/touch-app.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTouchApp = (props) => ( <SvgIcon {...props}> <path d="M9 11.24V7.5C9 6.12 10.12 5 11.5 5S14 6.12 14 7.5v3.74c1.21-.81 2-2.18 2-3.74C16 5.01 13.99 3 11.5 3S7 5.01 7 7.5c0 1.56.79 2.93 2 3.74zm9.84 4.63l-4.54-2.26c-.17-.07-.35-.11-.54-.11H13v-6c0-.83-.67-1.5-1.5-1.5S10 6.67 10 7.5v10.74l-3.43-.72c-.08-.01-.15-.03-.24-.03-.31 0-.59.13-.79.33l-.79.8 4.94 4.94c.27.27.65.44 1.06.44h6.79c.75 0 1.33-.55 1.44-1.28l.75-5.27c.01-.07.02-.14.02-.2 0-.62-.38-1.16-.91-1.38z"/> </SvgIcon> ); ActionTouchApp = pure(ActionTouchApp); ActionTouchApp.displayName = 'ActionTouchApp'; ActionTouchApp.muiName = 'SvgIcon'; export default ActionTouchApp;
src/svg-icons/content/next-week.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentNextWeek = (props) => ( <SvgIcon {...props}> <path d="M20 7h-4V5c0-.55-.22-1.05-.59-1.41C15.05 3.22 14.55 3 14 3h-4c-1.1 0-2 .9-2 2v2H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zM10 5h4v2h-4V5zm1 13.5l-1-1 3-3-3-3 1-1 4 4-4 4z"/> </SvgIcon> ); ContentNextWeek = pure(ContentNextWeek); ContentNextWeek.displayName = 'ContentNextWeek'; ContentNextWeek.muiName = 'SvgIcon'; export default ContentNextWeek;
docs-src/js/components/options/CloseButton.js
gomo/react-calcpicker
import React from 'react' import {CalcPicker, Rect, Action} from '../../../../dist/react-calcpicker' import SyntaxHighlighter from 'react-syntax-highlighter' import { tomorrowNightEighties } from 'react-syntax-highlighter/dist/styles' export default class CloseButton extends React.Component { constructor(props) { super(props); } render(){ return ( <div> <section className="docs--para-options-cont"> <p>You can change the contents of the button. Not only text but HTML can also be used.</p> </section> <section className="docs--para-options-cont"> <h3>Demo</h3> <CalcPicker onChange={val => console.log(val)} closeButton={<i className="fa fa-times" aria-hidden="true"></i>} /> </section> <section className="docs--para-options-cont"> <h3>Source</h3> <SyntaxHighlighter language='javascript' style={tomorrowNightEighties}> {`<CalcPicker onChange={val => console.log(val)} closeButton={<i className="fa fa-times" aria-hidden="true"></i>} />`} </SyntaxHighlighter> </section> </div> ); } }
src/components/Footer/Footer.js
jhlav/mpn-web-app
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Footer.css'; import Link from '../Link'; class Footer extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <span className={s.text}>© Your Company</span> <span className={s.spacer}>·</span> <Link className={s.link} to="/"> Home </Link> <span className={s.spacer}>·</span> <Link className={s.link} to="/admin"> Admin </Link> <span className={s.spacer}>·</span> <Link className={s.link} to="/privacy"> Privacy </Link> <span className={s.spacer}>·</span> <Link className={s.link} to="/not-found"> Not Found </Link> </div> </div> ); } } export default withStyles(s)(Footer);
examples/RaisedButton.js
chris-gooley/react-materialize
import React from 'react'; import Button from '../src/Button'; import Icon from '../src/Icon'; export default <div> <Button waves='light'>button</Button> <Button waves='light'>button<Icon left>cloud</Icon></Button> <Button waves='light'>button<Icon right>cloud</Icon></Button> </div>;
react/src/components/ThumbnailSizes/ThumbnailSize/index.js
sinfin/folio
import React from 'react' import Scroller from './Scroller' import { RawPicture } from 'components/Picture' class ThumbnailSize extends React.Component { constructor (props) { super(props) this.state = { editing: false } } save = (offset) => { this.props.updateThumbnail(this.props.thumbKey, offset) this.close() } close = () => { this.setState({ ...this.state, editing: false }) } render () { const { thumb, thumbKey } = this.props const editable = thumbKey.indexOf('#') !== -1 const height = 140 const width = thumb.width * height / thumb.height return ( <div className='mr-g my-h position-relative' style={{ width: width }}> {this.state.editing ? ( <Scroller file={this.props.file} thumb={this.props.thumb} thumbKey={thumbKey} height={height} width={width} close={this.close} save={this.save} /> ) : ( <div> <div style={{ height: height, width: width, backgroundColor: '#495057' }}> {thumb._saving ? null : <RawPicture src={this.props.thumb.url} webpSrc={this.props.thumb.webp_url} imageStyle={{ height: height, width: width }} alt={thumbKey} />} </div> <div className='mt-2 pt-1 small'>{thumbKey}</div> {editable && ( <div className='f-c-with-icon cursor-pointer text-semi-muted mt-1 d-flex' onClick={() => { this.setState({ ...this.state, editing: true }) }}> <span className='mi mi--18'>crop</span> {window.FolioConsole.translations.editOffset} </div> )} </div> )} {thumb._saving && <div className='folio-loader' />} </div> ) } } export default ThumbnailSize
src/plugins/ConsolePlugin/ConsolePanel.js
whinc/xConsole
import React from 'react' import './ConsolePanel.css' import {ErrorBoundary, MessageBox} from './components' export default class ConsolePanel extends React.Component { constructor (props) { super(props) this.state = { messages: [], // flag indicate if setting panel visble isSettingVisible: false, // flag indicate if timestamp enable isTimestampEnable: false, // filter string filter: '', // javascript code enter by user jsCode: '', logLevel: LogLevel.ALL } } componentDidMount () { const {messages = []} = this.props if (messages.length > 0) { this.setState({ messages }) } } clearMessages () { this.setState({ messages: [] }) } onChangeLogLevel (newLogLevel) { this.setState({ logLevel: newLogLevel }) } changeFilter (value) { this.setState({ filter: value }) } changeJSCode (code) { this.setState({ jsCode: code }) } toggleTimestampEnable () { this.setState({ ...this.state, isTimestampEnable: !this.state.isTimestampEnable }) } toggleSettingVisible () { this.setState({ ...this.state, isSettingVisible: !this.state.isSettingVisible }) } executeJSCode () { const {jsCode} = this.state if (!jsCode) return try { const $ = window.document.querySelector.bind(window.document) || (() => null) const $$ = window.document.querySelectorAll.bind(window.document) || (() => null) const result = eval(jsCode) console.log(result) } catch (error) { window.xConsole.commands.dispatch('console:error', {texts: [error]}) } } render () { const {messages, logLevel, filter, isSettingVisible, isTimestampEnable, jsCode} = this.state // filte messages with the filter rules let _messages = messages.filter(msg => { let b1 = new RegExp(msg.level).test(logLevel) let b2 = true if (filter) { // TODO: use the formated string to match instead of the origin arguments const content = JSON.stringify(msg.texts) // try match with regular expression, if it's failed use string search try { b2 = new RegExp(filter, 'i').test(content) } catch (error) { b2 = content.indexOf(filter) !== -1 } } return b1 && b2 }) let rows = 0 if (jsCode) { rows = jsCode.split('').reduce((n, c) => c === '\n' ? ++n : n, 0) + 1 } return ( <div className='ConsolePanel'> <div className='ConsolePanel__toolbar ConsolePanel-toolbar'> <div className='ConsolePanel-toolbar__clear'> <span onClick={() => this.clearMessages()} className='fa fa-ban' /> </div> <div className='ConsolePanel-toolbar__filter'> <input type='text' placeholder='Filter' value={filter} onChange={e => this.changeFilter(e.target.value)} /> <select value={logLevel} onChange={event => this.onChangeLogLevel(event.target.value)}> <option value={LogLevel.ALL}>All</option> <option value={LogLevel.LOG}>Log</option> <option value={LogLevel.ERROR}>Error</option> <option value={LogLevel.INFO}>Info</option> <option value={LogLevel.WARN}>Warn</option> <option value={LogLevel.DEBUG}>Debug</option> </select> </div> <div className='ConsolePanel-toolbar__setting' onClick={e => this.toggleSettingVisible()}> <span className='fa fa-cog' style={{color: isSettingVisible ? 'rgb(81, 128, 229)' : ''}} /> </div> </div> {isSettingVisible && <div className='ConsolePanel__setting'> <div> <label> <input type='checkbox' value={isTimestampEnable} onChange={e => this.toggleTimestampEnable()} /> Show timestamps </label> </div> </div> } <div className='ConsolePanel__content'> {/* <div> <TextInlineBlock value={{ a: 1, b: 'b', c: true, d: null, e: undefined, f: function () { }, g: {}, h: {a: 1, b: {a: 2, c: {a: 3, d: {e: 3}}}}, m: [], n: [1, 'b'] }} depth={-1} /> </div> <div> <TextInlineBlock value={[1, 'b', null, true]} /> </div> <div> <TextInlineBlock value={999} /> </div> <div> <TextInlineBlock value /> </div> <div> <TextInlineBlock value={'hello'} /> </div> <div> <TextInlineBlock value={null} /> </div> <div> <TextInlineBlock value={undefined} /> </div> */} {_messages.map(msg => <ErrorBoundary key={msg.id}> <MessageBox message={msg} isTimestampVisible={isTimestampEnable} /> </ErrorBoundary> )} {/* input and valuate javascript expression */} <div className='ConsolePanel-expression'> <textarea value={jsCode} onChange={e => this.changeJSCode(e.target.value)} rows={Math.max(rows, 2)} placeholder='Enter expression here' className='ConsolePanel-expression__input' /> <button className='ConsolePanel-expression__button' onClick={e => this.executeJSCode()}>exec</button> </div> </div> </div> ) } } const LogLevel = { ALL: 'log info warn error debug', LOG: 'log', INFO: 'info', WARN: 'warn', ERROR: 'error', DEBUG: 'debug' }
src/ColorPicker/color-picker-hsb.js
skyiea/wix-style-react
import React from 'react'; import {object, func} from 'prop-types'; import color from 'color'; import clamp from 'lodash/clamp'; import WixComponent from '../BaseComponents/WixComponent'; import {getBoundingRect} from './utils'; import css from './color-picker-hsb.scss'; export default class ColorPickerHsb extends WixComponent { static propTypes = { current: object.isRequired, onChange: func.isRequired } onMarkerDragStart = e => { e.preventDefault(); window.addEventListener('mousemove', this.onMarkerDrag); window.addEventListener('mouseup', this.onMarkerDragEnd); this.gradientRect = getBoundingRect(this.gradient); this.setNewColorByMouseEvent(e); } onMarkerDrag = e => { this.setNewColorByMouseEvent(e); } onMarkerDragEnd = () => { window.removeEventListener('mousemove', this.onMarkerDrag); window.removeEventListener('mouseup', this.onMarkerDragEnd); } getSVByMouseEvent = e => { const x = e.clientX - this.gradientRect.left; const y = e.clientY - this.gradientRect.top; const s = clamp(100 * x / this.gradientRect.width, 0, 100); const v = clamp(100 - (100 * y / this.gradientRect.height), 0, 100); return {s, v}; }; setNewColorByMouseEvent = e => { const {onChange, current} = this.props; const {s, v} = this.getSVByMouseEvent(e); onChange(color({h: current.hue(), s, v})); } componentWillUnmount() { this.onMarkerDragEnd(); } render() { const {current} = this.props; const hue = current.saturationv(100).lightness(50); const style = { left: `${current.saturationv()}%`, top: `${100 - current.value()}%` }; return ( <div className={css.root} ref={e => this.gradient = e} onMouseDown={this.onMarkerDragStart}> <div className={css.hue} style={{background: hue.hex()}}/> <div className={css.saturation}/> <div className={css.brightness}/> <div className={css.handle} style={style}/> </div> ); } }
app/containers/EditStudents/EditStudents.js
klpdotorg/tada-frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import get from 'lodash.get'; import isEmpty from 'lodash.isempty'; import { connect } from 'react-redux'; import { EditStudentsView } from '../../components/EditStudents'; import { getBoundariesEntities, getLanguages } from '../../actions'; import { checkPermissions, getEntitiesPath } from '../../utils'; class FetchAddStudentResources extends Component { componentDidMount() { const { params, studentGroup, parentId } = this.props; const { blockNodeId, districtNodeId, clusterNodeId, institutionNodeId, studentGroupNodeId, } = params; if (isEmpty(studentGroup)) { const entities = [ parentId, districtNodeId, blockNodeId, clusterNodeId, institutionNodeId, studentGroupNodeId, ].map((id, i) => { return { depth: i, uniqueId: id }; }); this.props.getBoundariesEntities(entities); } this.props.getLanguages(); } render() { const { blockNodeId, districtNodeId, clusterNodeId, institutionNodeId, studentGroupNodeId, } = this.props.params; const path = [ districtNodeId, blockNodeId, clusterNodeId, institutionNodeId, studentGroupNodeId, ]; return <EditStudentsView {...this.props} depth={path.length} />; } } FetchAddStudentResources.propTypes = { params: PropTypes.object, studentGroup: PropTypes.object, getBoundariesEntities: PropTypes.func, getLanguages: PropTypes.func, parentId: PropTypes.string, }; const mapStateToProps = (state, ownProps) => { const { blockNodeId, districtNodeId, clusterNodeId, institutionNodeId, studentGroupNodeId, } = ownProps.params; const { isAdmin } = state.profile; const district = get(state.boundaries.boundaryDetails, districtNodeId, {}); const block = get(state.boundaries.boundaryDetails, blockNodeId, {}); const cluster = get(state.boundaries.boundaryDetails, clusterNodeId, {}); const institution = get(state.boundaries.boundaryDetails, institutionNodeId, {}); const hasPermissions = checkPermissions( isAdmin, state.userPermissions, [district.id, block.id, cluster.id], institution.id, ); const pathname = get(ownProps, ['location', 'pathname'], ''); const paths = getEntitiesPath(pathname, [ districtNodeId, blockNodeId, clusterNodeId, institutionNodeId, studentGroupNodeId, ]); return { district, block, cluster, institution, studentGroup: get(state.boundaries.boundaryDetails, studentGroupNodeId, {}), studentIds: get(state.boundaries.boundariesByParentId, '5', []), isLoading: state.appstate.loadingBoundary, hasPermissions, paths, parentId: state.profile.parentNodeId, }; }; const EditStudents = connect(mapStateToProps, { getBoundariesEntities, getLanguages, })(FetchAddStudentResources); export default EditStudents;
generators/app/templates/src/index.js
jonidelv/generator-create-redux-app
import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import store from './store' import Routes from './routes' import './styles/globalStyles.css' import * as serviceWorker from './utils/serviceWorker' render( <Provider store={store}> <Routes /> </Provider>, document.getElementById('root'), ) // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: http://bit.ly/CRA-PWA serviceWorker.unregister()
js/src/NoAccess.js
syslo/file_publisher
import React from 'react' export default class NoAccess extends React.Component { render() { return ( <div> <p>You have no access!</p> </div> ) } }
Example/src/TagInputExample.js
jwohlfert23/react-native-tag-input
import React, { Component } from 'react'; import { Text, View, Platform, } from 'react-native'; import TagInput from 'react-native-tag-input'; const inputProps = { keyboardType: 'default', placeholder: 'email', autoFocus: true, style: { fontSize: 14, marginVertical: Platform.OS == 'ios' ? 10 : -2, }, }; const horizontalInputProps = { keyboardType: 'default', returnKeyType: 'search', placeholder: 'Search', style: { fontSize: 14, marginVertical: Platform.OS == 'ios' ? 10 : -2, }, }; const horizontalScrollViewProps = { horizontal: true, showsHorizontalScrollIndicator: false, }; export default class TagInputExample extends Component { state = { tags: [], text: "", horizontalTags: [], horizontalText: "", }; onChangeTags = (tags) => { this.setState({ tags }); } onChangeText = (text) => { this.setState({ text }); const lastTyped = text.charAt(text.length - 1); const parseWhen = [',', ' ', ';', '\n']; if (parseWhen.indexOf(lastTyped) > -1) { this.setState({ tags: [...this.state.tags, this.state.text], text: "", }); } } labelExtractor = (tag) => tag; onChangeHorizontalTags = (horizontalTags) => { this.setState({ horizontalTags, }); }; onChangeHorizontalText = (horizontalText) => { this.setState({ horizontalText }); const lastTyped = horizontalText.charAt(horizontalText.length - 1); const parseWhen = [',', ' ', ';', '\n']; if (parseWhen.indexOf(lastTyped) > -1) { this.setState({ horizontalTags: [...this.state.horizontalTags, this.state.horizontalText], horizontalText: "", }); this._horizontalTagInput.scrollToEnd(); } } render() { return ( <View style={{ flex: 1, margin: 10, marginTop: 30 }}> <Text style={{marginVertical: 10}}>Vertical Scroll</Text> <View style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: 'lightgray'}}> <Text>To: </Text> <TagInput value={this.state.tags} onChange={this.onChangeTags} labelExtractor={this.labelExtractor} text={this.state.text} onChangeText={this.onChangeText} tagColor="blue" tagTextColor="white" inputProps={inputProps} maxHeight={75} /> </View> <Text style={{marginVertical: 10}}>Horizontal Scroll</Text> <View style={{marginBottom: 10, flexDirection: 'row', alignItems: 'center', backgroundColor: 'lightgray'}}> <Text>To: </Text> <TagInput ref={(horizontalTagInput) => {this._horizontalTagInput = horizontalTagInput}} value={this.state.horizontalTags} onChange={this.onChangeHorizontalTags} labelExtractor={this.labelExtractor} text={this.state.horizontalText} onChangeText={this.onChangeHorizontalText} tagColor="blue" tagTextColor="white" inputProps={horizontalInputProps} scrollViewProps={horizontalScrollViewProps} /> </View> </View> ); } }
src/views/Activity/MiddleTitle.js
daxiangaikafei/QBGoods
import React from 'react' import classNames from 'classnames' import styles from './channelEntry.less' import CSSModules from 'react-css-modules' const MiddleTitle = ({ title, className, today }) => { return ( <div styleName={classNames('middle-title', className, { 'today': today })}> {today ? <span styleName="title-bg"></span> : ''} {title} {today ? <span styleName="title-bg right"></span> : ''} </div> ) } MiddleTitle.defaultProps ={ title: '', styleName: '', today: false } export default CSSModules(MiddleTitle, styles, { allowMultiple: true })
plugins/react/server/__test__/components/otherComponents/ComponentD.js
carteb/carte-blanche
import React from 'react'; export default () => <div></div>;
app/javascript/mastodon/components/domain.js
kirakiratter/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import IconButton from './icon_button'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unblock domain {domain}' }, }); export default @injectIntl class Account extends ImmutablePureComponent { static propTypes = { domain: PropTypes.string, onUnblockDomain: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleDomainUnblock = () => { this.props.onUnblockDomain(this.props.domain); } render () { const { domain, intl } = this.props; return ( <div className='domain'> <div className='domain__wrapper'> <span className='domain__domain-name'> <strong>{domain}</strong> </span> <div className='domain__buttons'> <IconButton active icon='unlock' title={intl.formatMessage(messages.unblockDomain, { domain })} onClick={this.handleDomainUnblock} /> </div> </div> </div> ); } }
src/svg-icons/hardware/laptop.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareLaptop = (props) => ( <SvgIcon {...props}> <path d="M20 18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2h-4zM4 6h16v10H4V6z"/> </SvgIcon> ); HardwareLaptop = pure(HardwareLaptop); HardwareLaptop.displayName = 'HardwareLaptop'; export default HardwareLaptop;
src/app/components/common/OpenMobileAppButton/index.stories.js
GolosChain/tolstoy
import React from 'react'; import { storiesOf } from '@storybook/react'; import OpenMobileAppButton from './index'; storiesOf('OpenMobileAppButton', module).add('button', () => ( <div> <OpenMobileAppButton onClick={noop} onHide={noop} onHideForever={noop} /> </div> )); function noop() {}
app/client/src/components/ShiftScheduler/ShiftScheduler.js
uprisecampaigns/uprise-app
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import moment from 'moment'; import DatePicker from 'material-ui/DatePicker'; import TimePicker from 'material-ui/TimePicker'; import Divider from 'material-ui/Divider'; import AddCircle from 'material-ui/svg-icons/content/add-circle'; import RemoveCircle from 'material-ui/svg-icons/content/remove-circle'; import s from 'styles/Form.scss'; const blankShift = ( date = moment() .startOf('day') .toDate(), ) => ({ id: undefined, start: undefined, end: moment(date) .add(16, 'hour') .toDate(), startError: null, endError: null, }); class ShiftScheduler extends Component { static propTypes = { data: PropTypes.object.isRequired, submit: PropTypes.func.isRequired, }; constructor(props) { super(props); // TODO change to Date objects? const shifts = props.data.shifts.length === 0 ? [blankShift()] : props.data.shifts; const shiftDates = []; shifts.forEach((shift) => { const placeholderShift = typeof shift.start === 'undefined'; const shiftDate = placeholderShift ? undefined : moment(shift.start) .startOf('day') .toDate(); const foundIndex = placeholderShift ? -1 : shiftDates.findIndex((d) => moment(d.date).isSame(shiftDate, 'day')); const newShift = { id: shift.id, start: moment(shift.start).toDate(), end: moment(shift.end).toDate(), startError: null, endError: null, }; if (foundIndex === -1) { shiftDates.push({ date: shiftDate, dateError: null, shifts: [newShift] }); } else { shiftDates[foundIndex].shifts.push(newShift); } }); this.state = { shiftDates }; } componentDidUpdate() { if (this.errorElem) { this.errorElem.scrollIntoView(); } } validate = () => { let hasErrors = false; const newShiftDates = this.state.shiftDates.map((shiftDate) => { const newShiftDate = { ...shiftDate }; newShiftDate.dateError = null; if (typeof newShiftDate.date !== 'object') { hasErrors = true; newShiftDate.dateError = 'Date required'; } const newShifts = newShiftDate.shifts.map((shift) => { let shiftError = false; const newShift = { ...shift }; newShift.startError = null; newShift.endError = null; if (typeof newShift.start !== 'object') { shiftError = true; newShift.startError = 'Starting time required'; } if (typeof shift.end !== 'object') { shiftError = true; newShift.endError = 'Starting time required'; } if (!shiftError) { if (!moment(newShift.end).isAfter(moment(newShift.start))) { shiftError = true; newShift.endError = 'End time must be before start'; } } hasErrors = hasErrors || shiftError; return newShift; }); newShiftDate.shifts = newShifts; return newShiftDate; }); this.setState({ shiftDates: newShiftDates }); return hasErrors; }; formSubmit = () => { const hasErrors = this.validate(); if (!hasErrors) { const shifts = this.state.shiftDates.reduce((accumulator, shiftDate) => { const newShifts = shiftDate.shifts.map((shift) => ({ start: moment(shift.start).format(), end: moment(shift.end).format(), id: shift.id, })); return [...accumulator, ...newShifts]; }, []); this.props.submit({ shifts }); } }; addDate = () => { const newShifts = [...this.state.shiftDates]; const newDate = moment() .startOf('day') .toDate(); newShifts.push({ date: newDate, dateError: null, shifts: [blankShift(newDate)] }); this.setState({ shiftDates: newShifts }); }; addShift = (dateIndex) => { const newShifts = [...this.state.shiftDates]; const { date } = newShifts[dateIndex]; newShifts[dateIndex].shifts.push(blankShift(date)); this.setState({ shiftDates: newShifts }); }; removeDate = (dateIndex) => { const newShifts = [...this.state.shiftDates]; newShifts.splice(dateIndex, 1); this.setState({ shiftDates: newShifts }); }; removeShift = (dateIndex, shiftIndex) => { const newShifts = [...this.state.shiftDates]; newShifts[dateIndex].shifts.splice(shiftIndex, 1); this.setState({ shiftDates: newShifts }); }; changeShift = (type, time, dateIndex, shiftIndex) => { const newShifts = [...this.state.shiftDates]; const date = moment(this.state.shiftDates[dateIndex].date); const mTime = moment(time); const newTime = date.hour(mTime.hour()).minute(mTime.minute()); newShifts[dateIndex].shifts[shiftIndex][type] = newTime.toDate(); newShifts[dateIndex].shifts[shiftIndex][`${type}Error`] = null; this.setState({ shiftDates: newShifts }); }; changeDate = (dateIndex, date) => { const newShifts = [...this.state.shiftDates]; newShifts[dateIndex].date = date; newShifts[dateIndex].dateError = null; const mDate = moment(date); // eslint-disable-next-line no-restricted-syntax for (const shift of newShifts[dateIndex].shifts) { shift.start = moment(shift.start) .date(mDate.date()) .month(mDate.month()) .year(mDate.year()) .toDate(); shift.end = moment(shift.end) .date(mDate.date()) .month(mDate.month()) .year(mDate.year()) .toDate(); } this.setState({ shiftDates: newShifts }); }; render() { const { shiftDates } = this.state; const { formSubmit, addShift, addDate, changeDate, changeShift, removeShift, removeDate } = this; const formatDate = (date) => moment(date).format('M/D/YYYY'); const dialogStyle = { zIndex: '3200', }; const renderDateForm = (shiftDate, dateIndex) => { const renderedShifts = shiftDate.shifts.map((shift, shiftIndex) => ( <div key={JSON.stringify(shift)} className={s.shiftContainer}> <div className={s.shiftPicker} ref={(input) => { if (shift.startError || shift.endError) { this.errorElem = input; } }} > <div className={s.shiftLabel}> <span>Shift {shiftIndex + 1}:</span> </div> <TimePicker floatingLabelText="Start Time" value={shift.start} errorText={shift.startError} minutesStep={5} onChange={(event, time) => { changeShift('start', time, dateIndex, shiftIndex); }} className={s.shiftTimePicker} /> <TimePicker floatingLabelText="End Time" value={shift.end} errorText={shift.endError} minutesStep={5} onChange={(event, time) => { changeShift('end', time, dateIndex, shiftIndex); }} className={s.shiftTimePicker} /> </div> {shiftIndex > 0 && ( <div className={s.removeShiftContainer}> <div onClick={(event) => { event.preventDefault(); removeShift(dateIndex, shiftIndex); }} onKeyPress={(event) => { event.preventDefault(); removeShift(dateIndex, shiftIndex); }} role="button" tabIndex="0" className={s.touchIcon} > <RemoveCircle /> Remove Shift </div> </div> )} </div> )); return ( <div className={s.dateWithShiftsContainer}> <div className={s.dateShiftContainer}> <div className={s.textFieldContainer} ref={(input) => { if (shiftDate.dateError) { this.errorElem = input; } }} > <DatePicker value={shiftDate.date} errorText={shiftDate.dateError} onChange={(event, date) => { changeDate(dateIndex, date); }} container="dialog" dialogContainerStyle={dialogStyle} floatingLabelText="Date" formatDate={formatDate} className={s.dateShiftPicker} /> </div> {dateIndex > 0 && ( <div className={s.removeDateContainer}> <div onClick={(event) => { event.preventDefault(); removeDate(dateIndex); }} onKeyPress={(event) => { event.preventDefault(); removeDate(dateIndex); }} role="button" tabIndex="0" className={s.touchIcon} > <RemoveCircle /> Remove Date </div> </div> )} </div> {renderedShifts} <div onClick={(event) => { event.preventDefault(); addShift(dateIndex); }} onKeyPress={(event) => { event.preventDefault(); addShift(dateIndex); }} role="button" tabIndex="0" className={s.touchIcon} > <AddCircle /> Add Shift </div> <Divider /> </div> ); }; const dateForm = shiftDates.map((shiftDate, index) => renderDateForm(shiftDate, index)); return ( <div className={s.outerContainer}> <div className={s.innerContainer}> <div className={s.formContainer}> <form className={s.form} onSubmit={formSubmit}> <div className={s.sectionLabel}>When:</div> {dateForm} <div onClick={(event) => { event.preventDefault(); addDate(); }} onKeyPress={(event) => { event.preventDefault(); addDate(); }} role="button" tabIndex="0" className={s.touchIcon} > <AddCircle /> Add Date </div> </form> </div> </div> </div> ); } } export default ShiftScheduler;
react-flux-mui/js/material-ui/src/svg-icons/image/photo-size-select-large.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImagePhotoSizeSelectLarge = (props) => ( <SvgIcon {...props}> <path d="M21 15h2v2h-2v-2zm0-4h2v2h-2v-2zm2 8h-2v2c1 0 2-1 2-2zM13 3h2v2h-2V3zm8 4h2v2h-2V7zm0-4v2h2c0-1-1-2-2-2zM1 7h2v2H1V7zm16-4h2v2h-2V3zm0 16h2v2h-2v-2zM3 3C2 3 1 4 1 5h2V3zm6 0h2v2H9V3zM5 3h2v2H5V3zm-4 8v8c0 1.1.9 2 2 2h12V11H1zm2 8l2.5-3.21 1.79 2.15 2.5-3.22L13 19H3z"/> </SvgIcon> ); ImagePhotoSizeSelectLarge = pure(ImagePhotoSizeSelectLarge); ImagePhotoSizeSelectLarge.displayName = 'ImagePhotoSizeSelectLarge'; ImagePhotoSizeSelectLarge.muiName = 'SvgIcon'; export default ImagePhotoSizeSelectLarge;
src/svg-icons/toggle/star.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ToggleStar = (props) => ( <SvgIcon {...props}> <path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/> </SvgIcon> ); ToggleStar = pure(ToggleStar); ToggleStar.displayName = 'ToggleStar'; ToggleStar.muiName = 'SvgIcon'; export default ToggleStar;
src/containers/DevTools/DevTools.js
chihungyu1116/perk-saga
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-Q"> <LogMonitor /> </DockMonitor> );
examples/BadgeCollections.js
react-materialize/react-materialize
import React from 'react'; import Badge from '../src/Badge'; import Collection from '../src/Collection'; import CollectionItem from '../src/CollectionItem'; export default <Collection> <CollectionItem href="#!"> Alan <Badge>1</Badge> </CollectionItem> <CollectionItem href="#!"> Alan <Badge newIcon>4</Badge> </CollectionItem> <CollectionItem href="#!"> Alan </CollectionItem> <CollectionItem href="#!"> Alan <Badge>14</Badge> </CollectionItem> </Collection>;
src/app/Steps/Contact/Contact.js
isaacjoh/foreseehome-test
import React from 'react'; import Formsy from 'formsy-react'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import Paper from 'material-ui/Paper'; import RaisedButton from 'material-ui/RaisedButton'; import { FormsyCheckbox, FormsyDate, FormsyRadio, FormsyRadioGroup, FormsySelect, FormsyText, FormsyTime, FormsyToggle, FormsyAutoComplete } from 'formsy-material-ui/lib'; import TextField from 'material-ui/TextField'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; import StepButtons from '../../Components/StepButtons'; const states = ['AA','AE','AL','AK','AP','AZ','AS','AR','CA','CO','CT','DC','DE','FL','FM','GA','GU','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MH','MI','MN','MP','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','PR','PW','RI','SC','SD','TN','TX','UT','VT','VA','VI','WA','WV','WI','WY']; Formsy.addValidationRule('isValidState', (values, value) => { if (value) { value = value.toUpperCase(); } if (states.indexOf(value) !== -1) { return true; } else { return false; } }); let paddingValue = 40; const isMobile = window.innerWidth <= 767; if (isMobile) { paddingValue = 25; } const Contact = React.createClass({ getInitialState() { return { canSubmit: false, shipState: '' }; }, errorMessages: { wordError: "Please use only letters", zipError: "Please provide a valid ZIP code", stateError: "Please provide a valid state", emailError: "Please provide a valid email", phoneError: "Please check the phone number format" }, styles: { paperStyle: { width: 'auto', margin: 'auto', padding: paddingValue, }, inputStyle: { fontSize: '18px', width: '100%' }, shippingSectionStyle: { marginBottom: 0 }, shippingSubsectionStyle: { marginBottom: 15, marginTop: 15 }, contactSectionStyle: { marginBottom: 0, marginTop: 42 }, helperText: { color: '#373D3F', fontFamily: 'acherus_grotesque_regular' } }, handleStateChange(event, index, value){ this.setState({shipState: value}); }, enableButton() { this.setState({ canSubmit: true, }); }, disableButton() { this.setState({ canSubmit: false, }); }, submitForm(data) { alert(JSON.stringify(data, null, 4)); }, notifyFormError(data) { console.error('Form error:', data); }, componentDidMount() { window.scrollTo(0, 0); }, render() { let { paperStyle, inputStyle, contactSectionStyle, shippingSectionStyle, shippingSubsectionStyle, helperText } = this.styles; let { wordError, zipError, stateError, emailError, phoneError } = this.errorMessages; let data = {}; if (this._address) { data = { address: this._address.state.value, city: this._city.state.value, state: this._state.state.value.toUpperCase(), zip: this._zip.state.value, phone: this._phone.state.value, email: this._email.state.value }; } return ( <MuiThemeProvider muiTheme={getMuiTheme()}> <Paper style={paperStyle}> <Formsy.Form onValid={this.enableButton} onInvalid={this.disableButton}> <h2>Step 3: Contact Information</h2> <h3 style={shippingSectionStyle}>Your Shipping Address</h3> <h5 style={shippingSubsectionStyle}> <i>Where can we ship your ForeseeHome device?</i> </h5> <div className="fs-contact-info"> <div> <FormsyText name="address" value={this.props.fieldValues.address} floatingLabelText="Street Address *" hintStyle={helperText} hintText="123 Main St, Apt D8" ref={(address) => {this._address = address}} style={inputStyle} required /> </div> <div> <FormsyText name="city" value={this.props.fieldValues.city} floatingLabelText="City *" validations={{matchRegexp: /^([A-Za-z\- ]+)$/}} validationError={wordError} hintStyle={helperText} hintText="Richmond" ref={(city) => {this._city = city}} style={inputStyle} updateImmediately required /> </div> <div> <FormsyText name="state" value={this.props.fieldValues.state} floatingLabelText="State *" validations="isValidState" validationError={stateError} hintStyle={helperText} hintText="VA" ref={(state) => {this._state = state}} style={inputStyle} required /> </div> <div> <FormsyText name="zip" value={this.props.fieldValues.zip} floatingLabelText="ZIP Code *" validations={{matchRegexp: /^\d{5}(?:[-\s]\d{4})?$/}} validationError={zipError} hintStyle={helperText} hintText="12345" ref={(zip) => {this._zip = zip}} style={inputStyle} required /> </div> <h3 style={contactSectionStyle}>Your Contact Information</h3> <h5 className="phone-subtext"> <i>Please provide the best phone number to reach you.</i> </h5> <div> <FormsyText name="phone" value={this.props.fieldValues.phone} floatingLabelText="Phone Number *" validations={{matchRegexp: /^\(?[\d]{3}\)?[\s-]?[\d]{3}[\s-]?[\d]{4}$/}} validationError={phoneError} hintStyle={helperText} hintText="(555) 555-5555" ref={(phone) => {this._phone = phone}} style={inputStyle} required /> </div> <div> <FormsyText name="email" value={this.props.fieldValues.email} floatingLabelText="Email" validations="isEmail" validationError={emailError} hintStyle={helperText} hintText="[email protected]" ref={(email) => {this._email = email}} style={inputStyle} /> </div> </div> <div className="spacer-medium"></div> <StepButtons data={data} handleEdit={this.props.handleEdit} handleNext={this.props.handleNext} handlePrev={this.props.handlePrev} saveValues={this.props.saveValues} stepIndex={this.props.stepIndex} reviewing={this.props.reviewing} validated={this.state.canSubmit} /> </Formsy.Form> </Paper> </MuiThemeProvider> ); }, }); export default Contact;
src/app/app.js
dpmramesh/cockpit-gluster
import React from 'react' import { render } from 'react-dom' import { Router, useRouterHistory } from 'react-router' import routes from './routes/routes.jsx' import '../../node_modules/patternfly/dist/css/patternfly.css' import '../../node_modules/patternfly/dist/css/patternfly-additions.css' import { createHashHistory } from 'history' require('./styles/wizard.scss'); const appHistory = useRouterHistory(createHashHistory)({queryKey: false}) render(<Router history={appHistory} routes={routes}/>, document.getElementById('app'))
src/desktop/apps/categories/components/FeaturedGene.js
kanaabe/force
import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-components' import { avantgarde } from 'reaction/Assets/Fonts' const propTypes = { title: PropTypes.string, href: PropTypes.string, image: PropTypes.object, } const Container = styled.div` position: relative; width: 95%; overflow: hidden; ` const GeneName = styled.span` position: absolute; left: 1em; bottom: 1em; text-decoration: none; color: white; text-shadow: 0 0 10px rgba(0, 0, 0, 0.7); ${avantgarde('s13')}; font-weight: bold; ` const GeneImage = styled.img` width: 100%; ` const FeaturedGene = ({ title, href, image: { url: imageSrc } }) => { return ( <a href={href}> <Container> <GeneName>{title}</GeneName> <GeneImage src={imageSrc} /> </Container> </a> ) } FeaturedGene.propTypes = propTypes export default FeaturedGene
components/forms/subscribe.js
react-ui-kit/base
import React from 'react'; import PropTypes from 'prop-types'; import Button from 'core/button'; import 'sass/forms/forms'; import 'sass/forms/subscribe'; export default class Subscribe extends React.Component { static displayName = 'Subscribe' static propTypes = { className: PropTypes.string, subscribeText: PropTypes.string, accent: PropTypes.bool, onSubscribe: PropTypes.func } static defaultProps = { className: '', subscribeText: 'Subscribe', onSubscribe: undefined } constructor(props) { super(props); this.renderSubscribeButton = this.renderSubscribeButton.bind(this); } renderSubscribeButton() { const { onSubscribe, subscribeText } = this.props; if (!onSubscribe) return null; return ( <Button className={'active full'} onClick={onSubscribe.bind(this)}> {subscribeText} </Button> ); } render() { let props = Object.assign({}, this.props); delete props.onSubscribe; // remove unwanted props delete props.subscribeText; const {children, className, accent, ...rest} = props; return ( <section className={`forms subscribe ${accent ? 'accent ' : ''}${className}`} {...rest}> <section className={'content'}> {children} </section> <section className={'footer'}> {this.renderSubscribeButton()} </section> </section> ); } }
src/components/article/index.js
timludikar/component-library
import React from 'react'; const Article = ({ children, style = {} }) => ( <article style={{ ...style }} > {children} </article> ); Article.propTypes = { children: React.PropTypes.node.isRequired, style: React.PropTypes.object, }; export default Article;
EvergreenApp/components/Weather/WeatherScreen.js
tr3v0r5/evergreen
import React, { Component } from 'react'; import { ActivityIndicator, AppRegistry, StyleSheet, Text, TextInput, View, Alert, Button,ScrollView, Dimensions ,AsyncStorage} from 'react-native'; import { FormLabel, FormInput,FormValidationMessage } from 'react-native-elements' import Carousel from 'react-native-snap-carousel'; import WidgetComponent from './WidgetComponent.js'; import * as firebase from 'firebase'; import {sliderWidth,itemWidth} from '../../Styles/weatherStyles.js' import styles from '../../Styles/weatherStyles.js' export default class WeatherScreen extends Component{ constructor(props){ super(props); this.state = { viewport: { width: Dimensions.get('window').width }, zip:'', city: '', state:'', infoArray:[], loaded:false, }; } async setZipCode() { try { const UID = await AsyncStorage.getItem('UID'); this.setState({ userID: UID }); } catch (error) { // Error retrieving data console.log(error); } var that = this; firebase.database().ref('/Users/' + this.state.userID + '/UserData').on('value',(snapshot)=> { var zip = snapshot.val().zip let apiKey = 'AIzaSyDnBNddRo5XOIX61hmASkzVIqf05fgw2Dg'; fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=${zip}&key=${apiKey}`) .then((response)=> response.json()) .then((responseData)=> { var cityVal=responseData.results[0].address_components[1].long_name; var stateVal=responseData.results[0].address_components[3].short_name; this.setInfo(cityVal,stateVal,zip); }); }); } /*setCityandState() { let apiKey = 'AIzaSyDnBNddRo5XOIX61hmASkzVIqf05fgw2Dg'; let zipCode = this.state.zipCode; console.warn(zipCode); fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=${zipCode}&key=${apiKey}`) .then((response)=> response.json()) .then((responseData)=> { var cityVal=responseData['results'][0]['address_components'][1]['long_name']; var stateVal=responseData['results'][0]['address_components'][3]['short_name']; this.setState({ city: cityVal, state: stateVal }); }) }*/ setInfo(city,state,zip){ let apiKey='3f766cac24cd2475'; let temporaryArray = []; fetch(`https://api.wunderground.com/api/${apiKey}/forecast10day/q/${zip}.json`) .then((response)=> response.json()) .then((responseData)=> { for(var i = 0; i < 5;i++) { temporaryArray.push({ condition : responseData.forecast.simpleforecast.forecastday[i].conditions.toUpperCase(), day : responseData.forecast.simpleforecast.forecastday[i].date.pretty, pop: responseData.forecast.simpleforecast.forecastday[i].pop, temp: responseData.forecast.simpleforecast.forecastday[i].high.fahrenheit, humidity: responseData.forecast.simpleforecast.forecastday[i].avehumidity, wind : responseData.forecast.simpleforecast.forecastday[i].avewind.mph }); } this.setState({ infoArray:temporaryArray, loaded:true, state:state, city:city, }); }) } componentDidMount(){ this.setZipCode(); //this.setInfo(); /*.then(getLoc =>this.setZipCode()) .then(getLoc =>{ this.setCityandState() .then(getInfo => this.setCityandState()) .then(getInfo =>{ this.setInfo(); }) })*/ } enter(){ if (this.state.zipCode==null ||(this.state.zipCode).length!=5 ){ this.setState({ zipError:'ZipCode needs to be 5 digits' }) } else{ firebase.database().ref('/Users/' + this.state.userID + '/UserData').set({ zip:this.state.zipCode }); } } makeWidgets(){ let cityVar = this.state.city; let stateVar = this.state.state; return this.state.infoArray.map(function(info,i){ return( <WidgetComponent key = {i} city = {cityVar} state = {stateVar} condition = {info.condition} day = {info.day} pop= {info.pop} temp = {info.temp} humidity = {info.humidity} wind = {info.wind}/> ); }); }; render(){ if(this.state.loaded){ return( <View style = {styles.carouselContainer} onLayout={() => { this.setState({ viewport: { width: Dimensions.get('window').width } }); }} > <View style = {styles.headerContainer}> <Text style = {styles.gardenText}> 5 Day Weather Forecast </Text> </View> <Carousel sliderWidth={this.state.viewport.width} itemWidth={itemWidth} inactiveSlideScale={0.94} inactiveSlideOpacity={0.6} enableMomentum={false} > {this.makeWidgets()} </Carousel> </View> ); } else if (this.state.zip==''){ return ( <View style={{flex: 1, paddingTop: 20,justifyContent:'center',alignItems:'center'}}> <Text> Please enter zipcode</Text> <FormLabel>Zip Code</FormLabel> <FormInput onChangeText={(zip) => this.setState({zipCode:''+zip})} value={this.state.zipCode} keyboardType = {'numeric'} placeholder='Required' onEndEditing={()=>this.enter()} /> <FormValidationMessage>{this.state.zipError}</FormValidationMessage> </View> ) } else{ return ( <View style={{flex: 1, paddingTop: 20,justifyContent: 'center'}}> <ActivityIndicator size = 'large' /> </View> ); } } } module.exports = WeatherScreen;
example.js
jainvabhi/PWD
/* eslint new-cap: "off" */ import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { ReactInput, parseDigit } from 'input-format'; import { parse, format, asYouType, isValidNumber } from 'libphonenumber-js'; class DemoComponent extends Component { constructor(props) { super(props); this.onChange = this.onChange.bind(this); // this.parseNumbers = this.parseNumbers.bind(this); this.formatNumber = this.formatNumber.bind(this); this.state = { value: '', parse: '213-373-4253', format: '2133734253', country: 'US', }; } onChange(value) { this.setState({ value }); } formatNumber(value) { const asYouTypes = new asYouType(this.state.country); const text = asYouTypes.input(value); return { text, template: asYouTypes.template }; } render() { // const input_format = window['input-format'] // const ReactInput = input_format.ReactInput // const templateParser = input_format.templateParser // const templateFormatter = input_format.templateFormatter // const parseDigit = input_format.parseDigit const asYouTypes = new asYouType(this.state.country); asYouTypes.input(this.state.value); let parsedNumber = 'Unknown country'; let nationalFormattedNumber = 'Unknown country'; let internationalFormattedNumber = 'Unknown country'; let internationalFormattedNumberInPlaintext = 'Unknown country'; try { parsedNumber = JSON.stringify(parse(this.state.parse, this.state.country)); nationalFormattedNumber = format(parse(this.state.format, this.state.country), 'National'); internationalFormattedNumber = format(parse(this.state.format, this.state.country), 'International'); internationalFormattedNumberInPlaintext = format(parse(this.state.format, this.state.country), 'International_plaintext'); } catch (error) { if (error.message.indexOf('Unknown country code') !== 0) { throw error; } } console.log(parsedNumber); console.log(nationalFormattedNumber); console.log(internationalFormattedNumber); console.log(internationalFormattedNumberInPlaintext); return ( <div> <ReactInput autoFocus value={ this.state.value } onChange={ this.onChange } parse={ (character, value) => { // Leading plus is allowed if (character === '+') { if (!value) { return character; } } // Digits are allowed return parseDigit(character); } } format={ this.formatNumber } /> <div className="section"> <div className="section__line">Value: {this.state.value}</div> <div className="section__line">Default country: <input type="text" value={ this.state.country } onChange={ (event) => this.setState({ country: event.target.value }) } style={ { width: '40px', marginLeft: '6px' } } /> </div> <div className="section__line">Actual country: {asYouTypes.country}</div> <div className="section__line">National: {asYouTypes.country && format(asYouTypes.national_number, asYouTypes.country, 'National')}</div> <div className="section__line">Valid: {String(isValidNumber(this.state.value, asYouTypes.country))}</div> <br /> Note: Phone number validation here is loose because it uses the (default) reduced metadata set. For more precise phone number validation use <code>metadata.full.json</code>. <a href="https://github.com/catamphetamine/libphonenumber-js#isvalidnumberparsed_number">Read more</a> </div> </div> ); } } ReactDOM.render( <DemoComponent />, document.getElementById('root') );
app/javascript/mastodon/features/public_timeline/components/column_settings.js
lynlynlynx/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { injectIntl, FormattedMessage } from 'react-intl'; import SettingToggle from '../../notifications/components/setting_toggle'; export default @injectIntl class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, columnId: PropTypes.string, }; render () { const { settings, onChange } = this.props; return ( <div> <div className='column-settings__row'> <SettingToggle settings={settings} settingPath={['other', 'onlyMedia']} onChange={onChange} label={<FormattedMessage id='community.column_settings.media_only' defaultMessage='Media only' />} /> <SettingToggle settings={settings} settingPath={['other', 'onlyRemote']} onChange={onChange} label={<FormattedMessage id='community.column_settings.remote_only' defaultMessage='Remote only' />} /> </div> </div> ); } }
docs/src/examples/elements/Image/Variations/ImageExampleFloated.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Segment, Image } from 'semantic-ui-react' const src = '/images/wireframe/image-text.png' const ImageExampleFloated = () => ( <Segment> <Image src={src} size='small' floated='left' /> <p> Te eum doming eirmod, nominati pertinacia argumentum ad his. Ex eam alia facete scriptorem, est autem aliquip detraxit at. Usu ocurreret referrentur at, cu epicurei appellantur vix. Cum ea laoreet recteque electram, eos choro alterum definiebas in. Vim dolorum definiebas an. Mei ex natum rebum iisque. </p> <Image src={src} size='small' floated='right' /> <p> Audiam quaerendum eu sea, pro omittam definiebas ex. Te est latine definitiones. Quot wisi nulla ex duo. Vis sint solet expetenda ne, his te phaedrum referrentur consectetuer. Id vix fabulas oporteat, ei quo vide phaedrum, vim vivendum maiestatis in. </p> <p> Eu quo homero blandit intellegebat. Incorrupte consequuntur mei id. Mei ut facer dolores adolescens, no illum aperiri quo, usu odio brute at. Qui te porro electram, ea dico facete utroque quo. Populo quodsi te eam, wisi everti eos ex, eum elitr altera utamur at. Quodsi convenire mnesarchum eu per, quas minimum postulant per id. </p> </Segment> ) export default ImageExampleFloated
webpack/components/WithOrganization/withOrganization.js
Katello/katello
/* eslint-disable react/jsx-indent */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { translate as __ } from 'foremanReact/common/I18n'; import { get } from 'lodash'; import SetOrganization from '../SelectOrg/SetOrganization'; import Header from '../../containers/Application/Headers'; import * as organizationActions from '../../scenes/Organizations/OrganizationActions'; const mapStateToProps = state => ({ organization: state.katello.organization, }); const mapDispatchToProps = dispatch => bindActionCreators({ ...organizationActions }, dispatch); function withOrganization(WrappedComponent) { class CheckOrg extends Component { constructor(props) { super(props); this.state = { orgId: null }; } static getDerivedStateFromProps(newProps, state) { const orgNodeId = document.getElementById('organization-id').dataset.id; if (state.orgId !== orgNodeId) { return { orgId: orgNodeId }; } return null; } componentDidUpdate(prevProps) { const { location } = this.props; const orgTitle = get(location, 'state.orgChanged'); const prevOrgTitle = get(prevProps, 'location.state.orgChanged'); if (orgTitle !== prevOrgTitle) { window.tfm.nav.changeOrganization(orgTitle); } } render() { const { organization, location } = this.props; const newOrgSelected = get(location, 'state.orgChanged'); if (newOrgSelected) { if (!organization.label && !organization.loading) { this.props.loadOrganization(); } return <WrappedComponent {...this.props} />; } else if (this.state.orgId === '') { return ( <> <Header title={__('Select Organization')} /> <SetOrganization /> </>); } return <WrappedComponent {...this.props} />; } } CheckOrg.propTypes = { location: PropTypes.shape({}), loadOrganization: PropTypes.func.isRequired, organization: PropTypes.shape({ label: PropTypes.string, loading: PropTypes.bool, }).isRequired, }; CheckOrg.defaultProps = { location: undefined, }; return connect(mapStateToProps, mapDispatchToProps)(CheckOrg); } export default withOrganization;
src/js/app.js
touchstonejs/touchstonejs-starter
import React from 'react'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import ReactDOM from 'react-dom'; import { Container, createApp, UI, View, ViewManager } from 'touchstonejs'; // App Config // ------------------------------ const PeopleStore = require('./stores/people') const peopleStore = new PeopleStore() var App = React.createClass({ mixins: [createApp()], childContextTypes: { peopleStore: React.PropTypes.object }, getChildContext () { return { peopleStore: peopleStore }; }, componentDidMount () { // Hide the splash screen when the app is mounted if (navigator.splashscreen) { navigator.splashscreen.hide(); } }, render () { let appWrapperClassName = 'app-wrapper device--' + (window.device || {}).platform return ( <div className={appWrapperClassName}> <div className="device-silhouette"> <ViewManager name="app" defaultView="main"> <View name="main" component={MainViewController} /> <View name="transitions-target-over" component={require('./views/transitions-target-over')} /> </ViewManager> </div> </div> ); } }); // Main Controller // ------------------------------ var MainViewController = React.createClass({ render () { return ( <Container> <UI.NavigationBar name="main" /> <ViewManager name="main" defaultView="tabs"> <View name="tabs" component={TabViewController} /> </ViewManager> </Container> ); } }); // Tab Controller // ------------------------------ var lastSelectedTab = 'lists' var TabViewController = React.createClass({ getInitialState () { return { selectedTab: lastSelectedTab }; }, onViewChange (nextView) { lastSelectedTab = nextView this.setState({ selectedTab: nextView }); }, selectTab (value) { let viewProps; this.refs.vm.transitionTo(value, { transition: 'instant', viewProps: viewProps }); this.setState({ selectedTab: value }) }, render () { let selectedTab = this.state.selectedTab let selectedTabSpan = selectedTab if (selectedTab === 'lists' || selectedTab === 'list-simple' || selectedTab === 'list-complex' || selectedTab === 'list-details') { selectedTabSpan = 'lists'; } if (selectedTab === 'transitions' || selectedTab === 'transitions-target') { selectedTabSpan = 'transitions'; } return ( <Container> <ViewManager ref="vm" name="tabs" defaultView={selectedTab} onViewChange={this.onViewChange}> <View name="lists" component={require('./views/lists')} /> <View name="list-simple" component={require('./views/list-simple')} /> <View name="list-complex" component={require('./views/list-complex')} /> <View name="list-details" component={require('./views/list-details')} /> <View name="form" component={require('./views/form')} /> <View name="controls" component={require('./views/controls')} /> <View name="transitions" component={require('./views/transitions')} /> <View name="transitions-target" component={require('./views/transitions-target')} /> </ViewManager> <UI.Tabs.Navigator> <UI.Tabs.Tab onTap={this.selectTab.bind(this, 'lists')} selected={selectedTabSpan === 'lists'}> <span className="Tabs-Icon Tabs-Icon--lists" /> <UI.Tabs.Label>Lists</UI.Tabs.Label> </UI.Tabs.Tab> <UI.Tabs.Tab onTap={this.selectTab.bind(this, 'form')} selected={selectedTabSpan === 'form'}> <span className="Tabs-Icon Tabs-Icon--forms" /> <UI.Tabs.Label>Forms</UI.Tabs.Label> </UI.Tabs.Tab> <UI.Tabs.Tab onTap={this.selectTab.bind(this, 'controls')} selected={selectedTabSpan === 'controls'}> <span className="Tabs-Icon Tabs-Icon--controls" /> <UI.Tabs.Label>Controls</UI.Tabs.Label> </UI.Tabs.Tab> <UI.Tabs.Tab onTap={this.selectTab.bind(this, 'transitions')} selected={selectedTabSpan === 'transitions'}> <span className="Tabs-Icon Tabs-Icon--transitions" /> <UI.Tabs.Label>Transitions</UI.Tabs.Label> </UI.Tabs.Tab> </UI.Tabs.Navigator> </Container> ); } }); function startApp () { if (window.StatusBar) { window.StatusBar.styleDefault(); } ReactDOM.render(<App />, document.getElementById('app')); } if (!window.cordova) { startApp(); } else { document.addEventListener('deviceready', startApp, false); }
SwipComponent/DynamicExample.js
MisterZhouZhou/ReactNativeLearing
import React from 'react'; import { Text, TouchableHighlight, } from 'react-native'; import TimerMixin from 'react-timer-mixin'; import ScrollableTabView, { ScrollableTabBar, } from './ScrollalbeTabComponent'; const Child = React.createClass({ onEnter() { console.log('enter: ' + this.props.i); // eslint-disable-line no-console }, onLeave() { console.log('leave: ' + this.props.i); // eslint-disable-line no-console }, render() { const i = this.props.i; return <Text key={i}>{`tab${i}`}</Text>; }, }); export default React.createClass({ mixins: [TimerMixin, ], children: [], getInitialState() { return { tabs: [1, 2], }; }, componentDidMount() { this.setTimeout( () => { this.setState({ tabs: [1, 2, 3, 4, 5, 6, ], }); }, 100 ); }, handleChangeTab({i, ref, from, }) { this.children[i].onEnter(); this.children[from].onLeave(); }, renderTab(name, page, isTabActive, onPressHandler, onLayoutHandler) { return <TouchableHighlight key={`${name}_${page}`} onPress={() => onPressHandler(page)} onLayout={onLayoutHandler} style={{flex: 1, width: 100, }} underlayColor="#aaaaaa" > <Text>{name}</Text> </TouchableHighlight>; }, render() { return <ScrollableTabView style={{marginTop: 20, }} renderTabBar={() => <ScrollableTabBar renderTab={this.renderTab}/>} onChangeTab={this.handleChangeTab} > {this.state.tabs.map((tab, i) => { return <Child ref={(ref) => (this.children[i] = ref)} tabLabel={`tab${i}`} i={i} key={i} />; })} </ScrollableTabView>; }, });
app/javascript/mastodon/features/getting_started/index.js
ashfurrow/mastodon
import React from 'react'; import Column from '../ui/components/column'; import ColumnLink from '../ui/components/column_link'; import ColumnSubheading from '../ui/components/column_subheading'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { me, showTrends } from '../../initial_state'; import { fetchFollowRequests } from 'mastodon/actions/accounts'; import { List as ImmutableList } from 'immutable'; import NavigationContainer from '../compose/containers/navigation_container'; import Icon from 'mastodon/components/icon'; import LinkFooter from 'mastodon/features/ui/components/link_footer'; import TrendsContainer from './containers/trends_container'; const messages = defineMessages({ home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' }, notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' }, public_timeline: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' }, settings_subheading: { id: 'column_subheading.settings', defaultMessage: 'Settings' }, community_timeline: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' }, explore: { id: 'navigation_bar.explore', defaultMessage: 'Explore' }, direct: { id: 'navigation_bar.direct', defaultMessage: 'Direct messages' }, bookmarks: { id: 'navigation_bar.bookmarks', defaultMessage: 'Bookmarks' }, preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' }, follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' }, favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' }, blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' }, domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' }, mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' }, pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned posts' }, lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' }, discover: { id: 'navigation_bar.discover', defaultMessage: 'Discover' }, personal: { id: 'navigation_bar.personal', defaultMessage: 'Personal' }, security: { id: 'navigation_bar.security', defaultMessage: 'Security' }, menu: { id: 'getting_started.heading', defaultMessage: 'Getting started' }, }); const mapStateToProps = state => ({ myAccount: state.getIn(['accounts', me]), columns: state.getIn(['settings', 'columns']), unreadFollowRequests: state.getIn(['user_lists', 'follow_requests', 'items'], ImmutableList()).size, }); const mapDispatchToProps = dispatch => ({ fetchFollowRequests: () => dispatch(fetchFollowRequests()), }); const badgeDisplay = (number, limit) => { if (number === 0) { return undefined; } else if (limit && number >= limit) { return `${limit}+`; } else { return number; } }; const NAVIGATION_PANEL_BREAKPOINT = 600 + (285 * 2) + (10 * 2); export default @connect(mapStateToProps, mapDispatchToProps) @injectIntl class GettingStarted extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { intl: PropTypes.object.isRequired, myAccount: ImmutablePropTypes.map.isRequired, columns: ImmutablePropTypes.list, multiColumn: PropTypes.bool, fetchFollowRequests: PropTypes.func.isRequired, unreadFollowRequests: PropTypes.number, unreadNotifications: PropTypes.number, }; componentDidMount () { const { fetchFollowRequests, multiColumn } = this.props; if (!multiColumn && window.innerWidth >= NAVIGATION_PANEL_BREAKPOINT) { this.context.router.history.replace('/home'); return; } fetchFollowRequests(); } render () { const { intl, myAccount, columns, multiColumn, unreadFollowRequests } = this.props; const navItems = []; let height = (multiColumn) ? 0 : 60; if (multiColumn) { navItems.push( <ColumnSubheading key='header-discover' text={intl.formatMessage(messages.discover)} />, ); height += 34; } navItems.push( <ColumnLink key='explore' icon='hashtag' text={intl.formatMessage(messages.explore)} to='/explore' />, ); height += 48; if (multiColumn) { navItems.push( <ColumnLink key='community_timeline' icon='users' text={intl.formatMessage(messages.community_timeline)} to='/public/local' />, <ColumnLink key='public_timeline' icon='globe' text={intl.formatMessage(messages.public_timeline)} to='/public' />, ); height += 48*2; navItems.push( <ColumnSubheading key='header-personal' text={intl.formatMessage(messages.personal)} />, ); height += 34; } if (multiColumn && !columns.find(item => item.get('id') === 'HOME')) { navItems.push( <ColumnLink key='home' icon='home' text={intl.formatMessage(messages.home_timeline)} to='/home' />, ); height += 48; } navItems.push( <ColumnLink key='direct' icon='at' text={intl.formatMessage(messages.direct)} to='/conversations' />, <ColumnLink key='bookmark' icon='bookmark' text={intl.formatMessage(messages.bookmarks)} to='/bookmarks' />, <ColumnLink key='favourites' icon='star' text={intl.formatMessage(messages.favourites)} to='/favourites' />, <ColumnLink key='lists' icon='list-ul' text={intl.formatMessage(messages.lists)} to='/lists' />, ); height += 48*4; if (myAccount.get('locked') || unreadFollowRequests > 0) { navItems.push(<ColumnLink key='follow_requests' icon='user-plus' text={intl.formatMessage(messages.follow_requests)} badge={badgeDisplay(unreadFollowRequests, 40)} to='/follow_requests' />); height += 48; } if (!multiColumn) { navItems.push( <ColumnSubheading key='header-settings' text={intl.formatMessage(messages.settings_subheading)} />, <ColumnLink key='preferences' icon='gears' text={intl.formatMessage(messages.preferences)} href='/settings/preferences' />, ); height += 34 + 48; } return ( <Column bindToDocument={!multiColumn} label={intl.formatMessage(messages.menu)}> {multiColumn && <div className='column-header__wrapper'> <h1 className='column-header'> <button> <Icon id='bars' className='column-header__icon' fixedWidth /> <FormattedMessage id='getting_started.heading' defaultMessage='Getting started' /> </button> </h1> </div>} <div className='getting-started'> <div className='getting-started__wrapper' style={{ height }}> {!multiColumn && <NavigationContainer />} {navItems} </div> {!multiColumn && <div className='flex-spacer' />} <LinkFooter withHotkeys={multiColumn} /> </div> {multiColumn && showTrends && <TrendsContainer />} </Column> ); } }
src/svg-icons/editor/insert-link.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorInsertLink = (props) => ( <SvgIcon {...props}> <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"/> </SvgIcon> ); EditorInsertLink = pure(EditorInsertLink); EditorInsertLink.displayName = 'EditorInsertLink'; export default EditorInsertLink;
src/svg-icons/action/touch-app.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTouchApp = (props) => ( <SvgIcon {...props}> <path d="M9 11.24V7.5C9 6.12 10.12 5 11.5 5S14 6.12 14 7.5v3.74c1.21-.81 2-2.18 2-3.74C16 5.01 13.99 3 11.5 3S7 5.01 7 7.5c0 1.56.79 2.93 2 3.74zm9.84 4.63l-4.54-2.26c-.17-.07-.35-.11-.54-.11H13v-6c0-.83-.67-1.5-1.5-1.5S10 6.67 10 7.5v10.74l-3.43-.72c-.08-.01-.15-.03-.24-.03-.31 0-.59.13-.79.33l-.79.8 4.94 4.94c.27.27.65.44 1.06.44h6.79c.75 0 1.33-.55 1.44-1.28l.75-5.27c.01-.07.02-.14.02-.2 0-.62-.38-1.16-.91-1.38z"/> </SvgIcon> ); ActionTouchApp = pure(ActionTouchApp); ActionTouchApp.displayName = 'ActionTouchApp'; ActionTouchApp.muiName = 'SvgIcon'; export default ActionTouchApp;
app/src/App.js
larsthorup/js-fullstack-sandbox
import React from 'react'; import logo from './logo.svg'; import './App.css'; import DreamList from './DreamList'; function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <DreamList /> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); } export default App;
src/svg-icons/action/system-update-alt.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSystemUpdateAlt = (props) => ( <SvgIcon {...props}> <path d="M12 16.5l4-4h-3v-9h-2v9H8l4 4zm9-13h-6v1.99h6v14.03H3V5.49h6V3.5H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2v-14c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ActionSystemUpdateAlt = pure(ActionSystemUpdateAlt); ActionSystemUpdateAlt.displayName = 'ActionSystemUpdateAlt'; ActionSystemUpdateAlt.muiName = 'SvgIcon'; export default ActionSystemUpdateAlt;
src/entypo/FlickrWithCircle.js
cox-auto-kc/react-entypo
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--FlickrWithCircle'; let EntypoFlickrWithCircle = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M10,0.4c-5.302,0-9.6,4.298-9.6,9.6s4.298,9.6,9.6,9.6s9.6-4.298,9.6-9.6S15.302,0.4,10,0.4z M7.436,12c-1.096,0-1.982-0.895-1.982-2c0-1.105,0.887-2,1.982-2c1.094,0,1.982,0.895,1.982,2C9.418,11.105,8.529,12,7.436,12z M12.565,12c-1.095,0-1.983-0.895-1.983-2c0-1.105,0.888-2,1.983-2c1.096,0,1.982,0.895,1.982,2C14.547,11.105,13.66,12,12.565,12z"/> </EntypoIcon> ); export default EntypoFlickrWithCircle;
docs/app/Examples/elements/Label/Variations/LabelExampleCircular.js
clemensw/stardust
import React from 'react' import { Label } from 'semantic-ui-react' const colors = [ 'red', 'orange', 'yellow', 'olive', 'green', 'teal', 'blue', 'violet', 'purple', 'pink', 'brown', 'grey', 'black', ] const LabelExampleCircular = () => ( <div> {colors.map(color => <Label circular color={color} key={color}>2</Label>)} </div> ) export default LabelExampleCircular
src/PageItem.js
yickli/react-bootstrap
import React from 'react'; import classNames from 'classnames'; const PageItem = React.createClass({ propTypes: { href: React.PropTypes.string, target: React.PropTypes.string, title: React.PropTypes.string, disabled: React.PropTypes.bool, previous: React.PropTypes.bool, next: React.PropTypes.bool, onSelect: React.PropTypes.func, eventKey: React.PropTypes.any }, getDefaultProps() { return { href: '#' }; }, render() { let classes = { 'disabled': this.props.disabled, 'previous': this.props.previous, 'next': this.props.next }; return ( <li {...this.props} className={classNames(this.props.className, classes)}> <a href={this.props.href} title={this.props.title} target={this.props.target} onClick={this.handleSelect} ref="anchor"> {this.props.children} </a> </li> ); }, handleSelect(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, this.props.href, this.props.target); } } } }); export default PageItem;
src/react/index.js
gouegd/redux-devtools
import React from 'react'; import createDevTools from '../createDevTools'; export const DevTools = createDevTools(React); export { default as LogMonitor } from './LogMonitor'; export { default as DebugPanel } from './DebugPanel';
app/common/components/ToolbarButtonPopover/index.js
cerebral/cerebral-reference-app
import React from 'react'; import {Decorator as Cerebral} from 'cerebral-view-react'; import ToolbarButton from 'common/components/ToolbarButton'; import classNames from 'classnames'; import styles from './styles.css'; @Cerebral() class ToolbarButtonPopover extends React.Component { onArrowBoxClick(e) { e.stopPropagation(); this.props.signals.course.buttonPopoverClicked({ mousePositionX: e.clientX, mousePositionY: e.clientY }); } renderBox() { return ( <div className={this.props.side === 'right' ? styles.arrowBoxRight : styles.arrowBox} onClick={(e) => this.onArrowBoxClick(e)}> <div className={styles.contentBox}> {this.props.children} </div> </div> ); } render() { return ( <div className={classNames(styles.wrapper, {[this.props.className]: this.props.className})}> <ToolbarButton active={this.props.show} icon={this.props.icon} title={this.props.title} onClick={this.props.onClick}/> {this.props.show ? this.renderBox() : null} </div> ); } } export default ToolbarButtonPopover;
blueocean-dashboard/src/main/js/components/CreatePipelineLink.js
jenkinsci/blueocean-plugin
import React from 'react'; import { Link } from 'react-router'; import { i18nTranslator, AppConfig } from '@jenkins-cd/blueocean-core-js'; import creationUtils from '../creation/creation-status-utils'; const t = i18nTranslator('blueocean-dashboard'); export default function CreatePipelineLink() { if (creationUtils.isHidden()) { return null; } const organization = AppConfig.getOrganizationName(); const link = organization ? `/organizations/${organization}/create-pipeline` : '/create-pipeline'; return ( <Link to={link} className="btn-new-pipeline btn-secondary inverse"> {t('home.header.button.createpipeline')} </Link> ); }
src/routes/about/About.js
jaruesink/ruesinkdds
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './About.css'; import Team from './team'; import Profile from '../../components/Profile'; const Profiles = Team.map(member => (<Profile {...member} />)); class About extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; // <img className={s.team} src={'./team.jpg'} alt={'Donna Ruesink D.D.S. team'} /> render() { return ( <div className={s.root}> <div className={s.container}> <h1>{this.props.title}</h1> {Profiles} </div> </div> ); } } export default withStyles(s)(About);
step7-flux/app/js/config/routes.js
jintoppy/react-training
import React from 'react'; import Main from '../components/Main'; import Home from '../components/Home'; import { Route, IndexRoute } from 'react-router'; export default ( <Route path="/" component={Main}> <IndexRoute component={Home} /> </Route> );
examples/src/ControlledComponent/ControlledComponent.js
brennanerbz/react-autosuggest
require('./ControlledComponent.less'); import React, { Component } from 'react'; import utils from '../utils'; import Autosuggest from '../../../src/Autosuggest'; import SourceCodeLink from '../SourceCodeLink/SourceCodeLink'; import suburbs from 'json!../suburbs.json'; function getSuggestions(input, callback) { const escapedInput = utils.escapeRegexCharacters(input.trim()); const lowercasedInput = input.trim().toLowerCase(); const suburbMatchRegex = new RegExp('\\b' + escapedInput, 'i'); const suggestions = suburbs .filter(suburbObj => suburbMatchRegex.test(suburbObj.suburb + ' VIC ' + suburbObj.postcode)) .sort((suburbObj1, suburbObj2) => suburbObj1.suburb.toLowerCase().indexOf(lowercasedInput) - suburbObj2.suburb.toLowerCase().indexOf(lowercasedInput) ) .slice(0, 7); // 'suggestions' will be an array of objects, e.g.: // [{ suburb: 'Mordialloc', postcode: '3195' }, // { suburb: 'Mentone', postcode: '3194' }, // { suburb: 'Mill Park', postcode: '3082' }] callback(null, suggestions); } function renderSuggestion(suggestionObj, input) { const escapedInput = utils.escapeRegexCharacters(input); const suburbMatchRegex = new RegExp('\\b' + escapedInput, 'i'); const suggestion = suggestionObj.suburb + ' VIC ' + suggestionObj.postcode; const firstMatchIndex = suggestion.search(suburbMatchRegex); if (firstMatchIndex === -1) { return suggestion; } const beforeMatch = suggestion.slice(0, firstMatchIndex); const match = suggestion.slice(firstMatchIndex, firstMatchIndex + input.length); const afterMatch = suggestion.slice(firstMatchIndex + input.length); return ( <span> {beforeMatch}<strong>{match}</strong>{afterMatch} </span> ); } function getSuggestionValue(suggestionObj) { return suggestionObj.suburb + ' VIC ' + suggestionObj.postcode; } export default class ControlledComponent extends Component { constructor() { super(); this.state = { fromValue: '', toValue: '' }; } setFromValue(fromValue) { this.setState({ fromValue }); } setToValue(toValue) { this.setState({ toValue }); } reverseSourceAndDestination() { const fromValue = this.state.toValue; const toValue = this.state.fromValue; this.setState({ fromValue, toValue }); } render() { const inputAttributesFrom = { id: 'controlled-component-from', placeholder: 'Source', onChange: ::this.setFromValue }; const inputAttributesTo = { placeholder: 'Destination', onChange: ::this.setToValue }; return ( <div className="controlled-component-example"> <div className="from-container"> <button onClick={() => this.setFromValue('Home')}>Home</button> <button onClick={() => this.setFromValue('Work')}>Work</button> <Autosuggest suggestions={getSuggestions} suggestionRenderer={renderSuggestion} suggestionValue={getSuggestionValue} inputAttributes={inputAttributesFrom} value={this.state.fromValue} id="from" /> </div> <div className="reverse-container"> <button onClick={::this.reverseSourceAndDestination}>⇅</button> </div> <div className="to-container"> <button onClick={() => this.setToValue('Bank')}>Bank</button> <button onClick={() => this.setToValue('Airport')}>Airport</button> <Autosuggest suggestions={getSuggestions} suggestionRenderer={renderSuggestion} suggestionValue={getSuggestionValue} inputAttributes={inputAttributesTo} value={this.state.toValue} id="to" /> </div> <SourceCodeLink file="examples/src/ControlledComponent/ControlledComponent.js" /> </div> ); } }
src/routes/Products/components/components/DroppableCard/DroppableCard.js
TheModevShop/craft-app
import React from 'react'; import {findDOMNode} from 'react-dom'; import _ from 'lodash'; import { DropTarget } from 'react-dnd'; import {Link} from 'react-router'; const Types = { card: 'card' }; /** * Specifies the drop target contract. * All methods are optional. */ const chessSquareTarget = { canDrop(props, monitor) { // You can disallow drop based on props or item const item = monitor.getItem(); return true; }, hover(props, monitor, component) { // This is fired very often and lets you perform side effects // in response to the hover. You can't handle enter and leave // here—if you need them, put monitor.isOver() into collect() so you // can just use componentWillReceiveProps() to handle enter/leave. // You can access the coordinates if you need them const clientOffset = monitor.getClientOffset(); const componentRect = findDOMNode(component).getBoundingClientRect(); // You can check whether we're over a nested drop target const isJustOverThisOne = monitor.isOver({ shallow: true }); // You will receive hover() even for items for which canDrop() is false const canDrop = monitor.canDrop(); }, drop(props, monitor, component) { if (monitor.didDrop()) { // If you want, you can check whether some nested // target already handled drop return props; } // Obtain the dragged item const item = monitor.getItem(); // You can do something with it // ChessActions.movePiece(item.fromPosition, props.position); // You can also do nothing and return a drop result, // which will be available as monitor.getDropResult() // in the drag source's endDrag() method return { moved: true, item, product: props.product }; } }; function collect(connect, monitor) { return { // Call this function inside render() // to let React DnD handle the drag events: connectDropTarget: connect.dropTarget(), // You can ask the monitor about the current drag state: isOver: monitor.isOver(), isOverCurrent: monitor.isOver({ shallow: true }), canDrop: monitor.canDrop(), itemType: monitor.getItemType() }; } class DroppableCard extends React.Component { constructor(...args) { super(...args); this.state = { }; } componentWillReceiveProps(nextProps) { if (!this.props.isOver && nextProps.isOver) { // You can use this as enter handler console.log('leave') this.setState({over: true}) } if (this.props.isOver && !nextProps.isOver) { // You can use this as leave handler this.setState({over: false}) } if (this.props.isOverCurrent && !nextProps.isOverCurrent) { // You can be more specific and track enter/leave // shallowly, not including nested targets console.log('current OVER') } } render() { // Your component receives its own props as usual const { position } = this.props; // These props are injected by React DnD, // as defined by your `collect` function above: const { isOver, canDrop, connectDropTarget } = this.props; const p = this.props.product; const products = p.products || []; return connectDropTarget( <div className={`card header-card ${this.state.over ? 'over' : ''}`}> <Link className="secondary-link" to={`/admin/products/${p.id}/${encodeURIComponent(p.name || p.display_name)}`}> <div className="image" style={{backgroundImage: `url("${p.image || '/static/missing-image.png'}")`}}></div> <h6 className="bold">{p.name}</h6> { !p.from_vip ? <h6>{products.length || 0} {products.length === 1 ? 'sku' : 'skus'}</h6> : null } </Link> </div> ); } } export default DropTarget('card', chessSquareTarget, collect)(DroppableCard);
src/Index.js
WhiteBlue/bilibili-react
import React from 'react'; import { render } from 'react-dom'; import { Router, Route } from 'react-router'; import App from './components/App'; import Sort from './components/Sort'; import SortList from './components/SortList'; import About from './components/About'; import Video from './components/Video'; import Search from './components/Search'; import SP from './components/SP'; import Rank from './components/Rank'; //dom ready $(document).ready(function () { window.React = React; var Back = React.createClass({ render: function () { history.go(-2); return <div></div> } }); render( (<Router> <Route path="/" component={App}> <Route path="/sort" component={Sort}/> <Route path="/search" component={Search}/> <Route path="/sort/:mid" component={SortList}/> <Route path="/play/:aid" component={Video}/> <Route path="/sp/:spid" component={SP}/> <Route path="/rank" component={Rank}/> <Route path="/back" component={Back}/> </Route> </Router>), document.getElementById('content') ); });
src/containers/hocs/withUser.js
niekert/soundify
import React from 'react'; import PropTypes from 'prop-types'; import { Redirect } from 'react-router-dom'; import { OK, DONE } from 'app-constants'; import { connect } from 'react-redux'; const withUser = (ComposedComponent, { redirect = true } = {}) => { const EnhanceUser = ({ user, status, ...props }) => { if (user && status === OK) { return <ComposedComponent user={user} {...props} />; } if (redirect && DONE.includes(status)) { return <Redirect to="/" />; } return null; }; EnhanceUser.propTypes = { user: PropTypes.object, status: PropTypes.string, }; EnhanceUser.defaultProps = { user: null, status: '', }; const mapStateToProps = state => ({ user: state.auth.user, status: state.auth.status, }); // TODO: Selector return connect(mapStateToProps)(EnhanceUser); }; export default withUser;
.history/src/instacelebs_20170930234329.js
oded-soffrin/gkm_viewer
import React from 'react'; import {render} from 'react-dom'; import { Provider } from 'react-redux'; import configureStore from './store/configureStore'; require('./favicon.ico'); // Tell webpack to load favicon.ico import './styles/styles.scss'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page. import InstaCelebs from './components/InstaCelebs' const store = configureStore(); render( <Provider store={store}> <div> Hello</div> </Provider>, document.getElementById('app') );
src/services/DocumentSelector.js
webcerebrium/ec-react15-lib
// this module is used so far to run // import React from 'react'; // import { Logger } from './Logger'; export const findDocumentElements = (selector, doc) => { if (!selector || !doc) return null; return doc.querySelector(selector); }; export default { findDocumentElements };
app/pages/reservation/reservation-information/ReservationInformationNotification.js
fastmonkeys/respa-ui
import React from 'react'; import PropTypes from 'prop-types'; const ReservationInformationNotification = ({ children, labelText }) => { return ( <div className="hds-notification hds-notification--warning"> <div className="hds-notification__label"> <span aria-hidden="true" className="hds-icon hds-icon--alert-circle" /> <span className="text-md text-bold">{labelText}</span> </div> <div className="hds-notification__body text-body">{children}</div> </div> ); }; ReservationInformationNotification.propTypes = { labelText: PropTypes.string.isRequired, children: PropTypes.node, }; export default ReservationInformationNotification;
webpack/components/Content/Details/ContentDetailInfo.js
Katello/katello
import React from 'react'; import PropTypes from 'prop-types'; import { Table } from 'react-bootstrap'; // using Map to preserve order const createRows = (details, mapping) => { const rows = []; /* eslint-disable no-restricted-syntax, react/jsx-closing-tag-location */ for (const key of mapping.keys()) { rows.push(<tr key={key}> <td><b>{mapping.get(key)}</b></td> <td>{Array.isArray(details[key]) ? details[key].join(', ') : details[key]}</td> </tr>); } /* eslint-enable no-restricted-syntax, react/jsx-closing-tag-location */ return rows; }; const ContentDetailInfo = ({ contentDetails, displayMap }) => ( <Table> <tbody> {createRows(contentDetails, displayMap)} </tbody> </Table> ); ContentDetailInfo.propTypes = { contentDetails: PropTypes.shape({}).isRequired, displayMap: PropTypes.instanceOf(Map).isRequired, }; export default ContentDetailInfo;
client/containers/Utils/Loading.js
Mignon-han/issue-processing
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Loading from '../../components/Utils/Loading'; const mapStateToProps = (state) => ({ loading:state.root.loading }); export default connect( mapStateToProps, null )(Loading);
src/components/device-list/no-devices.js
octoblu/intel-drink-bot
import React from 'react'; const NoDevice = () => ( <div className="NoDevice"> <p>There are currently no devices in your organization.</p> </div> ); export default NoDevice
webpack/components/TemplateSyncResult/components/SyncedTemplate/IconInfoItem.js
mmoll/foreman_templates
import React from 'react'; import { Icon } from 'patternfly-react'; import PropTypes from 'prop-types'; import InfoItem from './InfoItem'; import { itemIteratorId } from './helpers'; const IconInfoItem = ({ template, attr, iconName, tooltipText }) => ( <InfoItem itemId={itemIteratorId(template, attr)} tooltipText={tooltipText}> <Icon type="fa" name={iconName} /> </InfoItem> ); IconInfoItem.propTypes = { template: PropTypes.object.isRequired, attr: PropTypes.string.isRequired, iconName: PropTypes.string.isRequired, tooltipText: PropTypes.string.isRequired, }; export default IconInfoItem;
src/routes/post/index.js
yunqiangwu/kmadmin
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'dva' import { Tabs } from 'antd' import { routerRedux } from 'dva/router' import List from './List' const TabPane = Tabs.TabPane const EnumPostStatus = { UNPUBLISH: 1, PUBLISHED: 2, } const Index = ({ post, dispatch, loading, location }) => { const { list, pagination } = post const { query = {}, pathname } = location const listProps = { pagination, dataSource: list, loading: loading.effects['post/query'], onChange (page) { dispatch(routerRedux.push({ pathname, query: { ...query, page: page.current, pageSize: page.pageSize, }, })) }, } const handleTabClick = (key) => { dispatch(routerRedux.push({ pathname, query: { status: key, }, })) } return (<div className="content-inner"> <Tabs activeKey={query.status === String(EnumPostStatus.UNPUBLISH) ? String(EnumPostStatus.UNPUBLISH) : String(EnumPostStatus.PUBLISHED)} onTabClick={handleTabClick}> <TabPane tab="Publised" key={String(EnumPostStatus.PUBLISHED)}> <List {...listProps} /> </TabPane> <TabPane tab="Unpublish" key={String(EnumPostStatus.UNPUBLISH)}> <List {...listProps} /> </TabPane> </Tabs> </div>) } Index.propTypes = { post: PropTypes.object, loading: PropTypes.object, location: PropTypes.object, dispatch: PropTypes.func, } export default connect(({ post, loading }) => ({ post, loading }))(Index)
src/client/app.js
nemecec/base
'use strict'; import React from 'react'; import Router from 'react-router'; import routes from './routes.js'; function run() { Router.run(routes, Router.HistoryLocation, function (Handler) { React.render(<Handler/>, document.body); }); } Promise.all([ new Promise((resolve) => { if (window.addEventListener) { window.addEventListener('DOMContentLoaded', resolve); } else { window.attachEvent('onload', resolve); } }) ]) .then(run);
example/index.ios.js
shoumma/react-native-off-canvas-menu
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; class OffCanvasMenu 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('OffCanvasMenu', () => OffCanvasMenu);
src/svg-icons/content/filter-list.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentFilterList = (props) => ( <SvgIcon {...props}> <path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"/> </SvgIcon> ); ContentFilterList = pure(ContentFilterList); ContentFilterList.displayName = 'ContentFilterList'; ContentFilterList.muiName = 'SvgIcon'; export default ContentFilterList;
node_modules/generator-react-fullstack/react-starter-kit/src/components/Header/Header.js
jdl031/FHIR-test-app
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component } from 'react'; import s from './Header.scss'; import withStyles from '../../decorators/withStyles'; import Link from '../Link'; import Navigation from '../Navigation'; @withStyles(s) class Header extends Component { render() { return ( <div className={s.root}> <div className={s.container}> <Navigation className={s.nav} /> <a className={s.brand} href="/" onClick={Link.handleClick}> <img src={require('./logo-small.png')} width="38" height="38" alt="React" /> <span className={s.brandTxt}>Your Company</span> </a> <div className={s.banner}> <h1 className={s.bannerTitle}>React</h1> <p className={s.bannerDesc}>Complex web apps made easy</p> </div> </div> </div> ); } } export default Header;
webpack/move_to_foreman/components/common/table/components/TableSelectionCell.js
cfouant/katello
import React from 'react'; import PropTypes from 'prop-types'; import { Table } from 'patternfly-react'; import { noop } from 'foremanReact/common/helpers'; const TableSelectionCell = ({ id, before, after, label, checked, onChange, ...props }) => ( <Table.SelectionCell> {before} <Table.Checkbox id={id} label={label} checked={checked} onChange={onChange} {...props} /> {after} </Table.SelectionCell> ); TableSelectionCell.propTypes = { id: PropTypes.string.isRequired, before: PropTypes.node, after: PropTypes.node, label: PropTypes.string, checked: PropTypes.bool, onChange: PropTypes.func, }; TableSelectionCell.defaultProps = { before: null, after: null, label: __('Select row'), checked: false, onChange: noop, }; export default TableSelectionCell;
src/MenuItem.js
mattBlackDesign/react-materialize
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; // This should be used within any component that has a menu like interface class MenuItem extends Component { render () { const { href, breadcrumbItem, children, className, ...props } = this.props; let classes = { breadcrumb: breadcrumbItem }; return ( <a href={href} {...props} className={cx(classes, className)}>{children}</a> ); } } MenuItem.propTypes = { className: PropTypes.string, children: PropTypes.node, // internal breadcrumbItem: PropTypes.bool, /** * The link for the anchor */ href: PropTypes.string }; export default MenuItem;
fields/types/location/LocationFilter.js
Redmart/keystone
import React from 'react'; import { FormField, FormInput, FormRow, SegmentedControl } from 'elemental'; const TOGGLE_OPTIONS = [ { label: 'Matches', value: false }, { label: 'Does NOT Match', value: true }, ]; function getDefaultValue () { return { inverted: TOGGLE_OPTIONS[0].value, street: undefined, city: undefined, state: undefined, code: undefined, country: undefined, }; } var TextFilter = React.createClass({ statics: { getDefaultValue: getDefaultValue, }, propTypes: { filter: React.PropTypes.shape({ inverted: React.PropTypes.boolean, street: React.PropTypes.string, city: React.PropTypes.string, state: React.PropTypes.string, code: React.PropTypes.string, country: React.PropTypes.string, }) }, getDefaultProps () { return { filter: getDefaultValue(), }; }, updateFilter (key, val) { let update = {}; update[key] = val; this.props.onChange(Object.assign(this.props.filter, update)); }, toggleInverted (value) { this.updateFilter('inverted', value); this.refs.focusTarget.focus(); }, updateValue (e) { this.updateFilter(e.target.name, e.target.value); }, render () { let { filter } = this.props; return ( <div> <FormField> <SegmentedControl equalWidthSegments options={TOGGLE_OPTIONS} value={filter.inverted} onChange={this.toggleInverted} /> </FormField> <FormField> <FormInput autofocus ref="focusTarget" value={filter.street} onChange={this.updateValue} name="street" placeholder="Address" /> </FormField> <FormRow> <FormField width="two-thirds"> <FormInput value={filter.city} onChange={this.updateValue} name="city" placeholder="City" /> </FormField> <FormField width="one-third"> <FormInput value={filter.state} onChange={this.updateValue} name="state" placeholder="State" /> </FormField> <FormField width="one-third" style={{ marginBottom: 0 }}> <FormInput value={filter.code} onChange={this.updateValue} name="code" placeholder="Postcode" /> </FormField> <FormField width="two-thirds" style={{ marginBottom: 0 }}> <FormInput value={filter.country} onChange={this.updateValue} name="country" placeholder="Country" /> </FormField> </FormRow> </div> ); } }); module.exports = TextFilter;
demo/components/DemoHOCItem.js
jasonslyvia/react-anything-sortable
import React from 'react'; import { sortable } from '../../src/index.js'; @sortable class DemoHOCItem extends React.Component { render() { return ( <div {...this.props}> {this.props.children} </div> ); } } export default DemoHOCItem;
assets/jqwidgets/demos/react/app/datatable/pinnedfrozencolumn/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxDataTable from '../../../jqwidgets-react/react_jqxdatatable.js'; class App extends React.Component { render() { let source = { dataType: "xml", dataFields: [ { name: 'ShippedDate', map: 'm\\:properties>d\\:ShippedDate', type: 'date' }, { name: 'Freight', map: 'm\\:properties>d\\:Freight', type: 'float' }, { name: 'ShipName', map: 'm\\:properties>d\\:ShipName' }, { name: 'ShipAddress', map: 'm\\:properties>d\\:ShipAddress' }, { name: 'ShipCity', map: 'm\\:properties>d\\:ShipCity' }, { name: 'ShipCountry', map: 'm\\:properties>d\\:ShipCountry' } ], root: "entry", record: "content", id: 'm\\:properties>d\\:OrderID', url: "../../sampledata/orders.xml", pager: (pagenum, pagesize, oldpagenum) => { // callback called when a page or page size is changed. } }; let dataAdapter = new $.jqx.dataAdapter(source); let columns = [ { text: 'Ship Name', dataField: 'ShipName', pinned: true, width: 300 }, { text: 'Ship City', dataField: 'ShipCity', width: 250 }, { text: 'Ship Address', dataField: 'ShipAddress', width: 350 }, { text: 'Ship Country', dataField: 'ShipCountry', width: 150 }, { text: 'Shipped Date', dataField: 'ShippedDate', width: 250, cellsFormat: 'D' }, { text: 'Freight', dataField: 'Freight', width: 100, cellsFormat: 'f2', cellsalign: 'right' } ]; return ( <JqxDataTable width={850} source={dataAdapter} pagerButtonsCount={10} pageable={true} sortable={true} columnsResize={true} columns={columns} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));