path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
src/components/Widgets/UnknownPreview.js
radekzz/netlify-cms-test
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import previewStyle from './defaultPreviewStyle'; export default function UnknownPreview({ field }) { return <div style={previewStyle}>No preview for widget “{field.get('widget')}”.</div>; } UnknownPreview.propTypes = { field: ImmutablePropTypes.map, };
packages/react-router-native/examples/BasicExample.js
d-oliveros/react-router
import React from 'react' import { StyleSheet, Text, View } from 'react-native' import { NativeRouter, Route, Link } from 'react-router-native' const Home = () => ( <Text style={styles.header}> Home </Text> ) const About = () => ( <Text style={styles.header}> About </Text> ) const Topic = ({ match }) => ( <Text style={styles.topic}> {match.params.topicId} </Text> ) const Topics = ({ match }) => ( <View> <Text style={styles.header}>Topics</Text> <View> <Link to={`${match.url}/rendering`} style={styles.subNavItem} underlayColor='#f0f4f7'> <Text>Rendering with React</Text> </Link> <Link to={`${match.url}/components`} style={styles.subNavItem} underlayColor='#f0f4f7'> <Text>Components</Text> </Link> <Link to={`${match.url}/props-v-state`} style={styles.subNavItem} underlayColor='#f0f4f7'> <Text>Props v. State</Text> </Link> </View> <Route path={`${match.url}/:topicId`} component={Topic}/> <Route exact path={match.url} render={() => ( <Text style={styles.topic}>Please select a topic.</Text> )} /> </View> ) const App = () => ( <NativeRouter> <View style={styles.container}> <View style={styles.nav}> <Link to="/" underlayColor='#f0f4f7' style={styles.navItem}> <Text>Home</Text> </Link> <Link to="/about" underlayColor='#f0f4f7' style={styles.navItem}> <Text>About</Text> </Link> <Link to="/topics" underlayColor='#f0f4f7' style={styles.navItem} > <Text>Topics</Text> </Link> </View> <Route exact path="/" component={Home}/> <Route path="/about" component={About}/> <Route path="/topics" component={Topics}/> </View> </NativeRouter> ) const styles = StyleSheet.create({ container: { marginTop: 25, padding: 10, }, header: { fontSize: 20, }, nav: { flexDirection: 'row', justifyContent: 'space-around' }, navItem: { flex: 1, alignItems: 'center', padding: 10, }, subNavItem: { padding: 5, }, topic: { textAlign: 'center', fontSize: 15, } }) export default App
js/components/LoadingIndicator.react.js
kkka/asd
/** * LoadingIndicator.react.js * * A loading indicator, copied from https://github.com/tobiasahlin/SpinKit * */ import React from 'react'; // Since this component doesn't need any state, make it a stateless component function LoadingIndicator() { return ( <div>Loading <div className="sk-fading-circle"> <div className="sk-circle1 sk-circle"></div> <div className="sk-circle2 sk-circle"></div> <div className="sk-circle3 sk-circle"></div> <div className="sk-circle4 sk-circle"></div> <div className="sk-circle5 sk-circle"></div> <div className="sk-circle6 sk-circle"></div> <div className="sk-circle7 sk-circle"></div> <div className="sk-circle8 sk-circle"></div> <div className="sk-circle9 sk-circle"></div> <div className="sk-circle10 sk-circle"></div> <div className="sk-circle11 sk-circle"></div> <div className="sk-circle12 sk-circle"></div> </div> </div> ) } export default LoadingIndicator;
examples/index.android.js
mayuur/react-native-callout
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, TouchableHighlight, Animated, View, Dimensions, } from 'react-native'; let { screenWidth, screenHeight } = Dimensions.get('window') var MJCallout = require('react-native-callout'); class calloutExample extends Component { constructor(props) { super(props); this.topButton = TouchableHighlight; this.state = { calloutOpacity: new Animated.Value(0), calloutText: 'Sample Callout Text', calloutTop:0, calloutLeft:0, calloutWidth:200, arrowPosition:'up', }; } render() { return ( <View style={styles.container}> <Text style={styles.headerText}> MJCallout Example </Text> <View style = {styles.buttonsView}> <TouchableHighlight ref = {component => this.topButton = component} style={[styles.buttonCallout, styles.buttonTop]} onPress={this.buttonClicked.bind(this,0)}> <Text style={styles.buttonText}> Top </Text> </TouchableHighlight> <TouchableHighlight ref = {component => this.leftButton = component} style={styles.buttonCallout} onPress={this.buttonClicked.bind(this,1)}> <Text style={styles.buttonText}> Left </Text> </TouchableHighlight> <TouchableHighlight ref = {component => this.rightButton = component} style={styles.buttonCallout} onPress={this.buttonClicked.bind(this,2)}> <Text style={styles.buttonText}> Right </Text> </TouchableHighlight> <TouchableHighlight ref = {component => this.downButton = component} style={styles.buttonCallout} onPress={this.buttonClicked.bind(this,3)}> <Text style={styles.buttonText}> Bottom </Text> </TouchableHighlight> </View> {this.renderCallOut()} </View> ); } renderCallOut() { //show callout only when needed if(!this.state.calloutOpacity) { return } //add callout if needed return ( <View style={{position:'absolute', top:this.state.calloutTop, left:this.state.calloutLeft}}> <MJCallout width={this.state.calloutWidth} visibility={this.state.calloutOpacity} calloutText={this.state.calloutText} arrowDirection={this.state.arrowPosition}> </MJCallout> </View> ) } buttonClicked(index) { var calloutX = 0; var calloutY = 0; if(index == 0) { this.topButton.measure( (fx, fy, width, height, px, py) => { this.setState({ calloutText:'Callout at top position', calloutOpacity: new Animated.Value(1), arrowPosition:'down', calloutTop:py-30, calloutLeft:px, calloutWidth:190, }) }) } else if(index == 1) { this.leftButton.measure( (fx, fy, width, height, px, py) => { this.setState({ calloutText:'Left Side Callout', calloutOpacity: new Animated.Value(1), arrowPosition:'right', calloutTop:py+5, calloutLeft:px+115, calloutWidth:170, }) }) } else if(index == 2) { this.rightButton.measure( (fx, fy, width, height, px, py) => { this.setState({ calloutText:'Right Side Callout', calloutOpacity: new Animated.Value(1), arrowPosition:'left', calloutTop:py+5, calloutLeft:px-85, calloutWidth:175, }) }) } else if(index == 3) { this.downButton.measure( (fx, fy, width, height, px, py) => { this.setState({ calloutText:'Callout at down position', calloutOpacity: new Animated.Value(1), arrowPosition:'up', calloutTop:py+55, calloutLeft:px, calloutWidth:200, }) }) } } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', backgroundColor: '#F5FCFF', }, headerText: { marginTop:30, fontSize: 30, fontWeight: '300', height:50, }, buttonsView: { flex:1, alignSelf:'stretch', justifyContent:'center', alignItems:'center', }, buttonCallout: { marginTop:20, justifyContent:'center', alignItems:'center', backgroundColor:'green', width:200, height: 50, borderColor: 'black', borderWidth:2, borderRadius:10, backgroundColor:'green', }, buttonTop : { marginTop:-50, }, buttonText: { textAlign:'center', }, }); AppRegistry.registerComponent('calloutExample', () => calloutExample);
www/imports/component/Namer.js
ucscHexmap/hexagram
// Namer.js // A modal to prompt the user to name something. // If you want something more complex use Modal.js instead. import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Modal from './Modal.js'; export default class Namer extends Component { constructor (props) { super(props); this.state = props; this.handleCloseModal = this.handleCloseModal.bind(this); this.handleTextKeyPress = this.handleTextKeyPress.bind(this); this.handleTextChange = this.handleTextChange.bind(this); this.handleOkButtonClick = this.handleOkButtonClick.bind(this); this.componentDidUpdate = this.componentDidUpdate.bind(this); } handleCloseModal (response) { // We handle the callback here, rather than in Modal, so we can // fix up the response. this.setState({ isOpen: false }); if (this.state.callback) { if (_.isUndefined(response) || typeof response !== 'string') { this.state.callback(); } else { this.state.callback(response); } } } handleOkButtonClick () { this.handleCloseModal(this.state.textInputStr.trim()); } handleTextKeyPress (event) { // Allow an 'Enter' key press to trigger the button. if (event.key === "Enter") { this.handleOkButtonClick(); } } handleTextChange (event) { this.setState({ textInputStr: event.target.value }); } componentDidUpdate () { var self = this; // Set the text value here to force the cursor to the end. setTimeout(function () { if (self.$text) { self.$text.val(self.state.textInputStr).focus(); } }, 300); } renderButton (self) { // Build the button. var button = <button onClick = {self.handleOkButtonClick} className = 'defaultButton' > OK </button> ; return button; } renderTextInput (self) { // Build the text input box. var input = <input type = 'text' onKeyPress = {self.handleTextKeyPress} onChange = {self.handleTextChange} style={{ width: '20em' }} ref={(input) => { this.$text = $(input); }} /> ; return input; } renderPromptStr (self) { // Convert any single string msg to an array of one msg. var msg = self.state.promptStr, msgArray = (typeof msg === 'string') ? [msg] : msg; return msgArray.map((str, i) => <p key = {i} > {str} </p> ); } render () { // Only show when isOpen state is true. if (!this.state.isOpen) { return null; } var self = this; return ( <Modal isOpen = {self.state.isOpen} onRequestClose = {self.handleCloseModal} body = { <div> {this.renderPromptStr(self)} {this.renderTextInput(self)} </div> } buttons = {this.renderButton(self)} /> ); } } Namer.propTypes = { // The text to display as a prompt to the user; either a string // or an array of strings, one per paragraph. promptStr: PropTypes.string.isRequired, // Controls the modal visibility. isOpen: PropTypes.bool, // The default text to display in the text input box. textInputStr: PropTypes.string, // Function to call upon modal close. callback: PropTypes.func, }; Namer.defaultProps = { isOpen: true, textInputStr: '', };
src/Fade.js
cgvarela/react-bootstrap
import React from 'react'; import Transition from 'react-overlays/lib/Transition'; import CustomPropTypes from './utils/CustomPropTypes'; import deprecationWarning from './utils/deprecationWarning'; class Fade extends React.Component { render() { let timeout = this.props.timeout || this.props.duration; return ( <Transition {...this.props} timeout={timeout} className="fade" enteredClassName="in" enteringClassName="in" > {this.props.children} </Transition> ); } } // Explicitly copied from Transition for doc generation. // TODO: Remove duplication once #977 is resolved. Fade.propTypes = { /** * Show the component; triggers the fade in or fade out animation */ in: React.PropTypes.bool, /** * Unmount the component (remove it from the DOM) when it is faded out */ unmountOnExit: React.PropTypes.bool, /** * Run the fade in animation when the component mounts, if it is initially * shown */ transitionAppear: React.PropTypes.bool, /** * Duration of the fade animation in milliseconds, to ensure that finishing * callbacks are fired even if the original browser transition end events are * canceled */ timeout: React.PropTypes.number, /** * duration * @private */ duration: CustomPropTypes.all([ React.PropTypes.number, (props)=> { if (props.duration != null) { deprecationWarning('Fade `duration`', 'the `timeout` prop'); } return null; } ]), /** * Callback fired before the component fades in */ onEnter: React.PropTypes.func, /** * Callback fired after the component starts to fade in */ onEntering: React.PropTypes.func, /** * Callback fired after the has component faded in */ onEntered: React.PropTypes.func, /** * Callback fired before the component fades out */ onExit: React.PropTypes.func, /** * Callback fired after the component starts to fade out */ onExiting: React.PropTypes.func, /** * Callback fired after the component has faded out */ onExited: React.PropTypes.func }; Fade.defaultProps = { in: false, timeout: 300, unmountOnExit: false, transitionAppear: false }; export default Fade;
src/modules/pages/PushLeft.js
lenxeon/react
require('../../css/drawer.less') import React from 'react'; const ReactPropTypes = React.PropTypes; class Drawer extends React.Component { constructor(props) { super(props); this.state = { open: props.open }; this.props.width = 600; } state: { } componentWillUpdate() {} componentWillReceiveProps() { console.log(this.props); console.log(this.state); if (this.state.open) { this.setState({ open: false, }) setTimeout(() => { this.setState({ open: this.props.open, }) }, 230) } else { this.setState({ open: this.props.open, }) } } componentWillMount() {} componentWillUnmount() { this.distoryLayer(); } componentDidUpdate() { this.renderLayer(); } componentDidMount() { this.renderLayer(); } _click() { this.setState({ open: false }) } renderChild() { let cls = 'className'; return ( <div className = {this.props.className}> <div className = "mod-view-in-wrap"> <div className = "mod-view-body-wrap"> { this.props.children } </div> </div> <div className = "foot" onClick = { this._click.bind(this) }> <i className = "fa fa-angle-double-up"> </i> </div> </div> ) } renderLayer() { if (this.state.open) { if (this._target == null) { this._target = document.createElement('div'); document.body.appendChild(this._target); } var height = $(document).height(); var width = $(document).width(); $(this._target).addClass('mod-view').css({ 'transform': 'translate(' + (width) + 'px, 0px)', 'transition': 'transform 0ms', 'width': 600, }); var o = this; var st = 300; setTimeout(function() { $('body').addClass('open-mod'); $(o._target).css({ 'transform': 'translate('+(width-600)+'px, 0px)', 'transition': 'transform 300ms cubic-bezier(0,1,0.5,1)' }) }, st + 100); setTimeout(function() { $(o._target).addClass('shake'); }, st + 400) var tree = o.renderChild(); React.render(tree, o._target); } else { this.distoryLayer(); } } distoryLayer() { if (this._target != null) { var t = this._target; var height = $(t).height(); var width = $(document).width(); $(t).css({ 'transform': 'translate('+width+'px, 0px)', 'transition': 'transform 300ms cubic-bezier(0,1,0.5,1)' }) var o = this; setTimeout(function() { React.unmountComponentAtNode(o._target); $(o._target).remove(); o._target = null; typeof o.unbindWindowEvents === "function" ? o.unbindWindowEvents() : void 0; $('body').removeClass('open-mod'); }, 200); } } render() { return ( <div /> ) } }; export default Drawer;
examples/esp-chat-react-es6/js/app.js
raybooysen/esp-js
import esp from 'esp-js' import espDevTools from 'esp-js-devtools'; import React from 'react'; import ReactDOM from 'react-dom'; import model from './model'; import components from './components'; import services from './services'; // export for http://fb.me/react-devtools window.React = React; espDevTools.registerDevTools(); var router = esp.SingleModelRouter.create(); var messageService = new services.MessageService(); var chatAppModel = new model.ChatApp(messageService, router); router.setModel(chatAppModel); chatAppModel.initialise(); ReactDOM.render( <components.ChatApp router={router} />, document.getElementById('react') ); router.publishEvent("InitEvent", {});
src/parser/priest/shadow/modules/spells/VoidformsTab.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import VoidformGraph from './VoidformGraph'; const VoidformsTab = ({ voidforms = [], insanityEvents, ...modules }) => { if (voidforms.length === 0) { return null; } return ( <div className="voidforms"> {voidforms.map((voidform, i) => ( <VoidformGraph key={i} {...voidform} {...modules} insanityEvents={( insanityEvents.filter(event => event.timestamp >= voidform.start && event.timestamp <= voidform.start + voidform.duration) )} /> ))} </div> ); }; VoidformsTab.propTypes = { voidforms: PropTypes.array.isRequired, fightEnd: PropTypes.number.isRequired, insanityEvents: PropTypes.array, }; export default VoidformsTab;
packages/mineral-ui-icons/src/IconLocalDrink.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconLocalDrink(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M3 2l2.01 18.23C5.13 21.23 5.97 22 7 22h10c1.03 0 1.87-.77 1.99-1.77L21 2H3zm9 17c-1.66 0-3-1.34-3-3 0-2 3-5.4 3-5.4s3 3.4 3 5.4c0 1.66-1.34 3-3 3zm6.33-11H5.67l-.44-4h13.53l-.43 4z"/> </g> </Icon> ); } IconLocalDrink.displayName = 'IconLocalDrink'; IconLocalDrink.category = 'maps';
kit/lib/routing.js
Mahi22/MedTantra
/* eslint-disable no-param-reassign */ // ---------------------- // IMPORTS import React from 'react'; import PropTypes from 'prop-types'; import { Route, Redirect as ReactRouterRedirect } from 'react-router-dom'; // ---------------------- // <Status code="xxx"> component. Updates the context router's context, which // can be used by the server handler to respond to the status on the server. class Status extends React.PureComponent { static propTypes = { code: PropTypes.number.isRequired, children: PropTypes.node, } static defaultProps = { children: null, } render() { const { code, children } = this.props; return ( <Route render={({ staticContext }) => { if (staticContext) { staticContext.status = code; } return children; }} /> ); } } // <NotFound> component. If this renders on the server in development mode, // it will attempt to proxyify the request to the upstream `webpack-dev-server`. // In production, it will issue a hard 404 and render. In the browser, it will // simply render. export class NotFound extends React.PureComponent { static propTypes = { children: PropTypes.node, } static defaultProps = { children: null, } render() { const { children } = this.props; return ( <Status code={404}> {children} </Status> ); } } // <Redirect> component. Mirrors React Router's component by the same name, // except it sets a 301/302 status code for setting server-side HTTP headers. export class Redirect extends React.PureComponent { static propTypes = { to: PropTypes.oneOfType([ PropTypes.string, PropTypes.object, ]).isRequired, from: PropTypes.string, push: PropTypes.bool, permanent: PropTypes.bool, }; static defaultProps = { from: null, push: false, permanent: false, } render() { const { to, from, push, permanent } = this.props; const code = permanent ? 301 : 302; return ( <Status code={code}> <ReactRouterRedirect to={to} from={from} push={push} /> </Status> ); } }
src/views/components/ThermostatCard.js
physiii/open-automation
import React from 'react'; import PropTypes from 'prop-types'; import ServiceCardBase from './ServiceCardBase.js'; import {connect} from 'react-redux'; import './ThermostatCard.css'; export class ThermostatCard extends React.Component { constructor (props) { super(props); const temp = this.props.service.state.get('current_temp') ? this.props.service.state.get('current_temp') : 0, targetTemp = this.props.service.state.get('target_temp') ? this.props.service.state.get('target_temp') : 0, fanMode = this.props.service.state.get('fan_mode') ? this.props.service.state.get('fan_mode') : 'off', schedule = this.props.service.state.get('schedule') ? this.props.service.state.get('schedule') : {}, isPowerOn = this.props.service.state.get('power') ? this.props.service.state.get('power') : false, isHoldOn = this.props.service.state.get('hold_mode') === 'on', currentHour = this.props.service.state.get('current_hour') ? this.props.service.state.get('current_hour') : 0, mode = this.props.service.state.get('mode') ? this.props.service.state.get('mode') : 'off'; this.state = { is_changing: false, temp, targetTemp, fanMode, isPowerOn, isHoldOn, schedule, currentHour, mode }; } getTemp () { return ( this.props.service.state.get('current_temp') ? this.props.service.state.get('current_temp') : '...' ); } getTargetTemp () { return ( this.props.service.state.get('target_temp') ? this.props.service.state.get('target_temp') : '...' ); } getFanMode () { return ( this.props.service.state.get('fan_mode') ? this.props.service.state.get('fan_mode') : '...' ); } getMode () { return ( this.props.service.state.get('mode') ? this.props.service.state.get('mode') : '...' ); } getHoldMode () { return ( this.props.service.state.get('hold_mode') ? this.props.service.state.get('hold_mode') : '...' ); } getHoldTemp () { return ( this.props.service.state.get('hold_temp') ? this.props.service.state.get('hold_temp') : {min: 0, max: 0} ); } getHoldTempMin () { return ( this.props.service.state.get('hold_temp') ? this.props.service.state.get('hold_temp') : {min: 0, max: 0} ); } getStatus () { if (!this.state.isPowerOn) { return 'Off'; } return ( this.state.isHoldOn ? 'Hold ' + this.getHoldTemp().min + ' - ' + this.getHoldTemp().max : 'Schedule ' + this.state.schedule[this.state.currentHour].minTemp + ' - ' + this.state.schedule[this.state.currentHour].maxTemp ); } isOutOfRange () { const mode = this.getMode(), temp = this.getTemp(), targetTemp = this.getTargetTemp(); if (mode === 'cool' && temp <= targetTemp) { return true; } if (mode === 'heat' && temp >= targetTemp) { return true; } if (targetTemp === 0) { return true; } return false; } render () { return ( <ServiceCardBase name={this.props.service.settings.get('name') || 'Thermostat'} status={ this.getStatus() } isConnected={this.props.service.state.get('connected')} {...this.props}> <center> <span styleName="sensorTitle"> {this.getTemp()} &#8457; </span> <span styleName={this.getMode() === 'off' || this.isOutOfRange() ? 'hidden' : 'sensorValues'}> <span styleName="coolValue"> {this.getMode() === 'cool' ? 'Cooling' : ''} </span> <span styleName="heatValue"> {this.getMode() === 'heat' ? 'Heating' : ''} </span> <span styleName="sensorValue"> &nbsp;to {this.getTargetTemp()} </span> </span> </center> </ServiceCardBase> ); } } ThermostatCard.propTypes = { service: PropTypes.object }; const mapDispatchToProps = (stateProps, {dispatch}, ownProps) => ({ ...dispatch, ...ownProps, ...stateProps }); export default connect(null, null, mapDispatchToProps)(ThermostatCard);
project-my-demos/src/downloadList/views/downloadList.js
renhongl/Summary
import React from 'react'; import Card from 'antd/lib/card'; import Icon from 'antd/lib/icon'; import '../style.css'; import Tooltip from 'antd/lib/tooltip'; const downloadList = [ { title: '爱听播放器', url: 'https://renhongl.github.io/other/AiTing.zip', desc: '一个简洁、好看、功能丰富的播放器,相当于音乐播放器和听书软件的结合。', src: 'https://renhongl.github.io/images/aiting1.png' }, { title: 'NodeJS刷票程序', url: 'https://github.com/renhongl/Buy_Ticket', desc: '这是一个脚本程序,运行在NodeJS环境之上,功能类似360抢票王。', src: 'https://renhongl.github.io/images/buyTicket.jpg' }, { title: '网页聊天软件', url: 'https://github.com/renhongl/AP_WEB', desc: '目前平台除了搭建了基本的结构之外,还做了一个简单的一对一聊天应用和简单的博客系统。', src: 'https://renhongl.github.io/images/homeAndRoom.png' }, { title: '桌面聊天室', url: 'https://github.com/renhongl/applicationPlatform', desc: '除了最基本的聊天外,还支持发一些表情,还可以设置字体,背景,以及主题。里面还集成了一个地图,如果是用电脑浏览器打开的,将会在地图上显示自己的位置。', src: 'https://renhongl.github.io/images/chatRoom2.png' } ] export default () => { return ( <div className="download-list-container"> { downloadList.map((v, k) => { return ( <Card key={k} bodyStyle={{ padding: 0 }}> <div className="custom-image"> <img alt="example" width="100%" height="100%" src={v.src} /> </div> <div className="custom-card"> <h3> {v.title} <Tooltip title={'点击下载 [' + v.title + ']'} placement="right"> <a href={v.url}> <Icon type="download" className="download-icon"/> </a> </Tooltip> </h3> <p>{v.desc}</p> </div> </Card> ) }) } </div> ) }
examples/Advanced/__tests__/index.android.js
larsvinter/react-native-awesome-button
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
src/svg-icons/action/http.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionHttp = (props) => ( <SvgIcon {...props}> <path d="M4.5 11h-2V9H1v6h1.5v-2.5h2V15H6V9H4.5v2zm2.5-.5h1.5V15H10v-4.5h1.5V9H7v1.5zm5.5 0H14V15h1.5v-4.5H17V9h-4.5v1.5zm9-1.5H18v6h1.5v-2h2c.8 0 1.5-.7 1.5-1.5v-1c0-.8-.7-1.5-1.5-1.5zm0 2.5h-2v-1h2v1z"/> </SvgIcon> ); ActionHttp = pure(ActionHttp); ActionHttp.displayName = 'ActionHttp'; ActionHttp.muiName = 'SvgIcon'; export default ActionHttp;
src/components/data/DataCreator.js
dherault/Oso
import React from 'react'; import { connect } from 'react-redux'; import definitions from '../../models/'; import ac from '../../state/actionCreators'; import { capitalize } from '../../utils/text'; class DataCreator extends React.Component { constructor() { super(); const inputs = {}; const modelList = []; for (let model in definitions) { modelList.push(model); inputs[model] = {}; } const currentModel = definitions[modelList[0]]; this.state = { modelList, currentModel, inputs, goodToGo: false, }; } handleModelChange(e) { this.setState({ currentModel: definitions[e.currentTarget.value] }, this.validate); } handleInputChange(col, e) { const { inputs, currentModel } = this.state; const newInputs = Object.assign({}, inputs); newInputs[currentModel.name][col] = e.currentTarget.value; this.setState({ inputs: newInputs }, this.validate); } handleSubmit() { const { dispatch } = this.props; const { currentModel: { name }, inputs, goodToGo } = this.state; if (goodToGo) dispatch(ac['create' + capitalize(name)](inputs[name])); } validate() { const { inputs, currentModel: { name, collumns } } = this.state; const params = inputs[name]; for (let col in collumns) { const value = params[col]; const { type, required, computed, min, max } = collumns[col]; if ((!computed && required && !value) || (value && type === 'string' && ((min && min > value.length) || (max && max < value.length)))) return this.setState({ goodToGo: false }); } this.setState({ goodToGo: true }); } renderForm() { const { currentModel: { name, collumns }, inputs } = this.state; const currentInputs = inputs[name]; return Object.keys(collumns).map(col => { const { type, required, computed, min, max, ref } = collumns[col]; if (computed) return; let control; switch (type) { case 'string': case 'string/email': control = <input type='text' value={currentInputs[col]} onChange={this.handleInputChange.bind(this, col)} />; break; case 'string/id': // todo ? break; default: return; } const infoRequired = required ? <span style={{color: 'red'}}> * </span> : undefined; const infoValidation = !min && !max ? undefined : min && max ? <span>{` (min: ${min}, max: ${max})`}</span> : min ? <span>{` (min: ${min})`}</span> : <span>{` (max: ${max})`}</span>; return <div key={col}> <br/> <span>{col + ': '}</span> { control } { infoRequired } { infoValidation } </div>; }); } render() { const { modelList, selectedModel, goodToGo } = this.state; return <div> <h2>Data creator</h2> <div> <span>What do you want to create? </span> <select value={selectedModel} onChange={this.handleModelChange.bind(this)}> { modelList.map(m => <option key= {m} value={m}>{m}</option>) } </select> </div> { this.renderForm() } <br /> <input type='button' onClick={this.handleSubmit.bind(this)} value='Create' disabled={!goodToGo}/> </div>; } } export default connect()(DataCreator);
src/docs/layout/DocumentComponent.js
reactstrap/component-template
import React from 'react'; import { PrismCode } from 'react-prism'; import { dedent } from 'dentist'; const DocumentProptypes = (props) => { const { name, proptypes } = props.component; return ( <div className="docs-component-props mt-5"> <h3>{name} - PropTypes</h3> <pre> <PrismCode className="language-jsx"> {`${name}.propTypes = ${dedent(proptypes)}`} </PrismCode> </pre> </div> ); }; const DocumentExamples = (props) => { const { name, demo, source } = props.component; return ( <div className="docs-component-props mt-5"> <h3>{name}</h3> { demo && ( <div className="docs-example"> {demo} </div> )} { source && ( <pre> <PrismCode className="language-jsx"> {dedent(source)} </PrismCode> </pre> )} </div> ); }; const DocumentComponent = (props) => { const { name, children, components = [], examples = [] } = props; return ( <div className="docs-component-section"> <h1>{name}</h1> {children} { components.map((component,i) => <DocumentProptypes key={i} component={component} />)} { examples.map((example,i) => <DocumentExamples key={i} component={example} />)} </div> ); }; export default DocumentComponent;
src/icons/AndroidArrowDown.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class AndroidArrowDown extends React.Component { render() { if(this.props.bare) { return <g> <g id="Icon_8_"> <g> <path d="M277.375,85v259.704l119.702-119.702L427,256L256,427L85,256l29.924-29.922l119.701,118.626V85H277.375z"></path> </g> </g> </g>; } return <IconBase> <g id="Icon_8_"> <g> <path d="M277.375,85v259.704l119.702-119.702L427,256L256,427L85,256l29.924-29.922l119.701,118.626V85H277.375z"></path> </g> </g> </IconBase>; } };AndroidArrowDown.defaultProps = {bare: false}
rest-ui-scripts/fixtures/kitchensink/src/features/webpack/SvgInclusion.js
RestUI/create-rest-ui-app
/** * 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. */ import React from 'react'; import logo from './assets/logo.svg'; export default () => <img id="feature-svg-inclusion" src={logo} alt="logo" />;
node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/actual.js
vinicius-ov/Livefy
import React from 'react'; const First = React.createNotClass({ displayName: 'First' }); class Second extends React.NotComponent {}
projects/starter/src/index.js
ebemunk/blog
import React from 'react' import ReactDOM from 'react-dom' import 'react-vis/dist/style.css' const render = (component, selector) => ReactDOM.render(component, document.querySelector(selector)) import A from './A' render(<A />, '#hi')
packages/javascript/reactjs/react-getstart/react-contact-manager/src/components/contact-card.js
sharkspeed/dororis
// src/components/contact-card.js import React from 'react' import { Link } from 'react-router-dom' import PropTypes from 'prop-types' // React v15+ 挪到额外模块中了 import { Card, Button, Icon } from 'semantic-ui-react' import { deleteContact } from '../actions/contact-actions' class ContactCard extends React.Component { constructor(props, context) { super(props, context) this.deleteContact = this.deleteContact.bind(this) } deleteContact() { } render() { var contact = this.props.contact return ( <Card> <Card.Content> <Card.Header> <Icon name="user outline" /> {contact.name.first} {contact.name.last} </Card.Header> <Card.Description> <p><Icon name="phone" /> {contact.phone}</p> <p><Icon name="mail outline" /> {contact.email}</p> </Card.Description> </Card.Content> <Card.Content extra> <div className="ui two buttons"> {/* <Button basic color="green">Edit</Button> */} <Link to={`/contacts/edit/${contact._id}`} className="ui basic button green">Edit</Link> <Button basic color="red" onClick={() => deleteContact(contact._id)}>Delete</Button> </div> </Card.Content> </Card> ) } } ContactCard.propTypes = { contact: PropTypes.object.isRequired } export default ContactCard
examples/js/basic/borderless-table.js
AllenFang/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); export default class BorderlessTable extends React.Component { render() { return ( <BootstrapTable data={ products } bordered={ false }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
docs/src/app/components/pages/components/Slider/ExampleStep.js
lawrence-yu/material-ui
import React from 'react'; import Slider from 'material-ui/Slider'; /** * By default, the slider is continuous. * The `step` property causes the slider to move in discrete increments. */ const SliderExampleStep = () => ( <Slider step={0.10} value={0.5} /> ); export default SliderExampleStep;
src/svg-icons/notification/confirmation-number.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationConfirmationNumber = (props) => ( <SvgIcon {...props}> <path d="M22 10V6c0-1.11-.9-2-2-2H4c-1.1 0-1.99.89-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2s.9-2 2-2zm-9 7.5h-2v-2h2v2zm0-4.5h-2v-2h2v2zm0-4.5h-2v-2h2v2z"/> </SvgIcon> ); NotificationConfirmationNumber = pure(NotificationConfirmationNumber); NotificationConfirmationNumber.displayName = 'NotificationConfirmationNumber'; NotificationConfirmationNumber.muiName = 'SvgIcon'; export default NotificationConfirmationNumber;
rest-ui-scripts/template/src/resources/Post/crud/list/Filter.js
RestUI/create-rest-ui-app
import React from 'react'; import { Filter as CrudFilter, TextInput } from 'rest-ui/lib/mui'; import { translate } from 'rest-ui'; import Chip from 'material-ui/Chip'; const QuickFilter = translate(({ label, translate }) => <Chip style={{ marginBottom: 8 }}>{translate(label)}</Chip>); const Filter = ({ ...props }) => ( <CrudFilter {...props}> <TextInput label="post.list.search" source="q" alwaysOn /> <TextInput source="title" defaultValue="Qui tempore rerum et voluptates" /> <QuickFilter label="resources.posts.fields.commentable" source="commentable" defaultValue={true} /> </CrudFilter> ); export default Filter;
src/svg-icons/communication/import-contacts.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationImportContacts = (props) => ( <SvgIcon {...props}> <path d="M21 5c-1.11-.35-2.33-.5-3.5-.5-1.95 0-4.05.4-5.5 1.5-1.45-1.1-3.55-1.5-5.5-1.5S2.45 4.9 1 6v14.65c0 .25.25.5.5.5.1 0 .15-.05.25-.05C3.1 20.45 5.05 20 6.5 20c1.95 0 4.05.4 5.5 1.5 1.35-.85 3.8-1.5 5.5-1.5 1.65 0 3.35.3 4.75 1.05.1.05.15.05.25.05.25 0 .5-.25.5-.5V6c-.6-.45-1.25-.75-2-1zm0 13.5c-1.1-.35-2.3-.5-3.5-.5-1.7 0-4.15.65-5.5 1.5V8c1.35-.85 3.8-1.5 5.5-1.5 1.2 0 2.4.15 3.5.5v11.5z"/> </SvgIcon> ); CommunicationImportContacts = pure(CommunicationImportContacts); CommunicationImportContacts.displayName = 'CommunicationImportContacts'; CommunicationImportContacts.muiName = 'SvgIcon'; export default CommunicationImportContacts;
src/routes/index.js
dfalling/todo
import React from 'react'; import { Route, IndexRoute, Redirect } from 'react-router'; // NOTE: here we're making use of the `resolve.root` configuration // option in webpack, which allows us to specify import paths as if // they were from the root of the ~/src directory. This makes it // very easy to navigate to files regardless of how deeply nested // your current file is. import CoreLayout from 'layouts/CoreLayout/CoreLayout'; import HomeView from 'views/HomeView/HomeView'; import TodosView from 'views/TodosView/TodosView'; import TodoEditView from 'views/TodoEditView/TodoEditView'; import TagsView from 'views/TagsView/TagsView'; import TagEditView from 'views/TagEditView/TagEditView'; import NotFoundView from 'views/NotFoundView/NotFoundView'; import LoginView from 'views/LoginView/LoginView'; import RootView from 'views/RootView/RootView'; export default (store) => ( <Route path='/' component={CoreLayout}> <IndexRoute component={HomeView} /> <RootView component={RootView}> <Route path='/todos' component={TodosView} /> <Route path='/todos/:todoId' component={TodoEditView} /> <Route path='/tags' component={TagsView} /> <Route path='/tags/:tagId' component={TagEditView} /> <Route path='/404' component={NotFoundView} /> <Route path='/login' component={LoginView} /> </RootView> <Redirect from='*' to='/404' /> </Route> );
app/components/Info/index.js
anthonyjillions/anthonyjillions
import React from 'react'; import Icon from '../Icon'; import styles from './styles.css'; export default function Info() { const list = [ 'MERN stack dev', '3rd party API integrations', 'Custom JS/CSS/HTML for tools like Tumblr, Shopify, Square etc.', ]; const list1 = [ 'Full service music production', 'Engineering, production, mixing, sound design', ]; return ( <div className={styles.Info} > <div className={styles.listContainer}> <Icon name="code" size="2x" /> {list.map((value, i) => { const render = ( <div key={i} className={styles.listItem}> {value} </div> ); return render; }) } </div> <div className={styles.listContainer}> <Icon name="music" size="2x" /> {list1.map((value, i) => { const render = ( <div key={i} className={styles.listItem}> {value} </div> ); return render; }) } </div> </div> ); }
src/ActivitySwitcher.js
siiptuo/tiima-spa
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { startActivity } from './actions'; import * as activity from './activity'; export class ActivitySwitcher extends React.Component { static propTypes = { onActivityStart: PropTypes.func.isRequired, loading: PropTypes.bool.isRequired, }; constructor(props) { super(props); this.state = { input: '' }; } handleInputChange = event => { this.setState({ input: event.target.value }); }; handleSubmit = event => { event.preventDefault(); const input = this.state.input.trim(); if (!input) { return; } const { title, tags } = activity.parseInput(input); this.props.onActivityStart(title, tags); this.setState({ input: '' }); }; render() { return ( <form className="start-activity-form" onSubmit={this.handleSubmit}> <input type="text" placeholder="Activity title #tag1 #tag2" value={this.state.input} onChange={this.handleInputChange} disabled={this.props.loading} /> <button type="submit" disabled={this.props.loading}> &#9654; </button> </form> ); } } function mapStateToProps(state) { return { loading: state.activities.isFetching, }; } function mapDispatchToProps(dispatch) { return { onActivityStart(title, tags) { dispatch(startActivity(title, tags)); }, }; } export default connect(mapStateToProps, mapDispatchToProps)(ActivitySwitcher);
pages/blog/test-article-one.js
b1alpha/sdj
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react'; export default class extends Component { render() { return ( <div> <h1>Test Article 1</h1> <p>Coming soon.</p> </div> ); } }
react/react-hn2/src/ItemList/ItemList.js
weaponhe/weaponhe.github.io
import React from 'react' import PropTypes from 'prop-types' import querystring from 'querystring' import ItemStore from '../store/itemStore' import Item from './Item' import Spinner from '../Spinner/Spinner' import Pager from '../pager/pager' import './ItemList.css' export default class ItemList extends React.Component { constructor(props) { super(props) this.state = { ITEMS_PER_PAGE: 10, ids: [], stories: [], limit: props.limit } } componentWillMount() { this.store = new ItemStore(this.props.type) this.store.addListener('update', this.handleUpdate) this.store.start() this.setState(this.store.getState()) } componentWillUnmount() { this.store.removeListener('update', this.handleUpdate) } handleUpdate = (update) => { update.limit = update.ids.length this.setState(update) } render() { let page = pageCalc(this.getPageNumber(), this.state.ITEMS_PER_PAGE, this.props.limit) if (this.state.stories.length === 0 && this.state.ids.length === 0) { let dummyItems = [] for (let i = page.startIndex; i < page.endIndex; i++) { dummyItems.push(<Spinner key={i}/>) } return ( <div> <ol start={page.startIndex + 1}> {dummyItems} </ol> <Pager route={this.props.type} hasNext={page.hasNext} page={page.pageNum}></Pager> </div> ) } return ( <div> <ol start={page.startIndex + 1}> {this.renderItems(page.startIndex, page.endIndex)} </ol> <Pager route={this.props.type} hasNext={page.hasNext} page={page.pageNum}></Pager> </div> ) } renderItems(startIndex, endIndex) { let rendered = [] for (let i = startIndex; i < endIndex; i++) { let id = this.state.ids[i], item = this.state.stories[i] rendered.push(<Item key={id} index={i} id={id} cachedItem={item} store={this.store}/>) } return rendered } getPageNumber(page) { if (typeof page === 'undefined') { let query = querystring.parse(this.props.location.search.slice(1)) page = query.page } return (page && /^\d+$/.test(page) ? Math.max(1, Number(page)) : 1) } } function pageCalc(pageNum, pageSize, numItems) { var startIndex = (pageNum - 1) * pageSize var endIndex = Math.min(numItems, startIndex + pageSize) var hasNext = endIndex < numItems - 1 return {pageNum, startIndex, endIndex, hasNext} } ItemList.propTypes = { type: PropTypes.string.isRequired, limit: PropTypes.number } ItemList.defaultProps = { limit: 200 }
packages/react-scripts/fixtures/kitchensink/template/src/features/webpack/SassModulesInclusion.js
facebookincubator/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import styles from './assets/sass-styles.module.sass'; import indexStyles from './assets/index.module.sass'; const SassModulesInclusion = () => ( <div> <p className={styles.sassModulesInclusion}>SASS Modules are working!</p> <p className={indexStyles.sassModulesIndexInclusion}> SASS Modules with index are working! </p> </div> ); export default SassModulesInclusion;
src/ui/components/EndpointsList.js
BE-Webdesign/wp-rest-api-reference
/** * External dependecies. */ import React from 'react' /** * Internal dependecies. */ import ReferenceEndpoint from './ReferenceEndpoint' const EndpointsList = ( { endpoints } ) => { return ( <div className="endpoints-list"> <h3 className="endpoints-list__title">Endpoints:</h3> <ul> { endpoints.map( ( endpoint, index ) => <ReferenceEndpoint endpoint={ endpoint } key={ index } /> ) } </ul> </div> ) } export default EndpointsList
src/svg-icons/navigation/close.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationClose = (props) => ( <SvgIcon {...props}> <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/> </SvgIcon> ); NavigationClose = pure(NavigationClose); NavigationClose.displayName = 'NavigationClose'; NavigationClose.muiName = 'SvgIcon'; export default NavigationClose;
ui/src/core/components/Navigation.js
erlanglab/erlangpl
// @flow import React from 'react'; import { Link, Route } from 'react-router-dom/'; import './Navigation.css'; const NavigationLink = ({ to, icon }) => ( <Route path={to} exact={false} children={({ match }) => ( <div className={`item ${match ? 'active' : ''}`}> <Link to={to}> {icon} </Link> </div> )} /> ); type Props = { tabs: Array<{ path: string, icon: string }> }; const Navigation = ({ tabs }: Props) => { return ( <div className="Navigation"> {tabs.map((tab, i) => ( <NavigationLink key={i} to={tab.path} icon={<i className={`fa fa-2x fa-${tab.icon}`} />} /> ))} </div> ); }; export default Navigation;
frontend/src/courses/components/header.js
OptimusCrime/youkok2
import React from 'react'; import { HeaderColumn } from './header-column'; import {COLUMN_CODE, COLUMN_NAME} from "../constants"; import {formatNumber} from "../../common/utils"; export const Header = ({ column, order, changeOrder, numCourses }) => ( <div className="course-row course-row__header"> <HeaderColumn id={COLUMN_CODE} text="Emnekode" column={column} order={order} changeOrder={changeOrder} /> <HeaderColumn id={COLUMN_NAME} text={`Emnernavn ${numCourses === 0 ? '' : `(${formatNumber(numCourses)})`}`} column={column} order={order} changeOrder={changeOrder} /> </div> );
04-mybooks-lab4/src/Header.js
iproduct/course-node-express-react
import React from 'react'; export default function Header() { return ( <React.Fragment> <h2 className="header center orange-text">My Library</h2> <div className="row center"> <h5 className="header col s12 light">Bookmark your favourite books</h5> </div> <div className="row center"> <a href="http://materializecss.com/getting-started.html" id="download-button" className="btn waves-effect waves-light orange" > View Favourites </a> </div> </React.Fragment> ); }
pnpm-offline/.pnpm-store-offline/1/registry.npmjs.org/react-bootstrap/0.31.0/es/MediaList.js
Akkuma/npm-cache-benchmark
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var MediaList = function (_React$Component) { _inherits(MediaList, _React$Component); function MediaList() { _classCallCheck(this, MediaList); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } MediaList.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('ul', _extends({}, elementProps, { className: classNames(className, classes) })); }; return MediaList; }(React.Component); export default bsClass('media-list', MediaList);
docs/app/Examples/collections/Message/Variations/MessageExampleInfo.js
aabustamante/Semantic-UI-React
import React from 'react' import { Message } from 'semantic-ui-react' const MessageExampleInfo = () => ( <Message info> <Message.Header>Was this what you wanted?</Message.Header> <p>Did you know it's been a while?</p> </Message> ) export default MessageExampleInfo
docs/client/components/pages/Sticker/gettingStarted.js
koaninc/draft-js-plugins
// It is important to import the Editor which accepts plugins. import Editor from 'draft-js-plugins-editor'; // eslint-disable-line import/no-unresolved import createStickerPlugin from 'draft-js-sticker-plugin'; // eslint-disable-line import/no-unresolved import React from 'react'; import { fromJS } from 'immutable'; // Creates an Instance. Passing in an Immutable.js List of stickers as an // argument. const stickers = fromJS({ data: { 'b3aa388f-b9f4-45b0-bba5-d92cf2caa48b': { id: 'b3aa388f-b9f4-45b0-bba5-d92cf2caa48b', url: '../images/unicorn-4.png', }, 'adec3f13-823c-47c3-b4d1-be4f68dd9d6d': { id: 'adec3f13-823c-47c3-b4d1-be4f68dd9d6d', url: '../images/unicorn-1.png', }, }, }); const stickerPlugin = createStickerPlugin({ stickers }); // The Editor accepts an array of plugins. In this case, only the stickerPlugin // is passed in, although it is possible to pass in multiple plugins. const MyEditor = ({ editorState, onChange }) => ( <Editor editorState={editorState} onChange={onChange} plugins={[stickerPlugin]} /> ); export default MyEditor;
docs/src/pages/blog.js
Gisto/Gisto
import React from 'react'; import { Helmet } from 'react-helmet'; import { graphql, Link } from 'gatsby'; import Header from 'components/header'; import Footer from 'components/footer'; const Blog = ({ data }) => ( <React.Fragment> <Helmet> <title>Blog</title> </Helmet> <Header/> <h1>Blog</h1> <section className="whiter boxes is-page-blog page-docs"> <div className="w-container content-container"> <div className="w-row w-col"> { data.allMarkdownRemark.edges.map((post) => ( <React.Fragment> <h2> <span>{post.node.frontmatter.date}</span> {post.node.frontmatter.title} </h2> <p>{post.node.excerpt}</p> <Link className="more" to={ post.node.frontmatter.path }> Read more <i className="fa fa-chevron-right"/> </Link> </React.Fragment> )) } </div> </div> </section> <Footer/> </React.Fragment> ); export const query = graphql` query { allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) { edges { node { id excerpt(pruneLength: 250) frontmatter { date(formatString: "MMMM DD, YYYY") path title } } } } } `; export default Blog;
threeforce/node_modules/react-bootstrap/es/MediaRight.js
wolfiex/VisACC
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import Media from './Media'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * Align the media to the top, middle, or bottom of the media object. */ align: React.PropTypes.oneOf(['top', 'middle', 'bottom']) }; var MediaRight = function (_React$Component) { _inherits(MediaRight, _React$Component); function MediaRight() { _classCallCheck(this, MediaRight); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } MediaRight.prototype.render = function render() { var _props = this.props; var align = _props.align; var className = _props.className; var props = _objectWithoutProperties(_props, ['align', 'className']); var _splitBsProps = splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); if (align) { // The class is e.g. `media-top`, not `media-right-top`. classes[prefix(Media.defaultProps, align)] = true; } return React.createElement('div', _extends({}, elementProps, { className: classNames(className, classes) })); }; return MediaRight; }(React.Component); MediaRight.propTypes = propTypes; export default bsClass('media-right', MediaRight);
examples/with-url-object-routing/pages/index.js
arunoda/next.js
import React from 'react' import Link from 'next/link' const href = { pathname: '/about', query: { name: 'next' } } const as = { pathname: '/about/next', hash: 'title-1' } export default () => ( <div> <h1>Home page</h1> <Link href={href} as={as}> <a>Go to /about/next</a> </Link> </div> )
src/svg-icons/notification/tap-and-play.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationTapAndPlay = (props) => ( <SvgIcon {...props}> <path d="M2 16v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm0 4v3h3c0-1.66-1.34-3-3-3zm0-8v2c4.97 0 9 4.03 9 9h2c0-6.08-4.92-11-11-11zM17 1.01L7 1c-1.1 0-2 .9-2 2v7.37c.69.16 1.36.37 2 .64V5h10v13h-3.03c.52 1.25.84 2.59.95 4H17c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99z"/> </SvgIcon> ); NotificationTapAndPlay = pure(NotificationTapAndPlay); NotificationTapAndPlay.displayName = 'NotificationTapAndPlay'; export default NotificationTapAndPlay;
src/views/pages/home/index.js
raycent/ARWM_Exercise_Redux
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Loader } from 'semantic-ui-react'; import { stockActions } from 'core/stock'; import { Dashboard } from 'views/components/Dashboard'; import { NotFound } from 'views/components/notFound'; class StockPage extends Component { constructor(props) { super(props); this.body = this.body.bind(this); } componentDidMount() { const ticker = this.props.ticker ? this.props.ticker : 'AAPL'; if (ticker.length > 5) { this.props.fetchStockDataFailure(); } else { this.props.fetchStockDataRequest(ticker); } } body() { const {stock} = this.props; if (stock.data) { return <Dashboard stock={stock} />; } else if (stock.error) { return <NotFound error={stock.error} />; } else { return <Loader size="massive" content="Loading..." active />; } } render() { return ( <div> {this.body()} </div> ); } } StockPage.propTypes = { fetchStockDataFailure: React.PropTypes.func, fetchStockDataRequest: React.PropTypes.func, stock: React.PropTypes.object, ticker: React.PropTypes.string }; const mapStateToProps = (state, props) => ({ stock: state.stock, ticker: props.location.pathname.split('/')[1] }); const mapDispatchToProps = { fetchStockDataRequest: stockActions.fetchStockDataRequest, fetchStockDataFailure: stockActions.fetchStockDataFailure }; export default connect( mapStateToProps, mapDispatchToProps )(StockPage);
app/components/Dash.js
scalegray/scalegray
import React from 'react'; import AuthenticatedComponent from './AuthenticatedComponent' export default AuthenticatedComponent(class Dash extends React.Component { render() { return (<h1>Hello user!!</h1>); } });
test/specs/elements/Button/Button-test.js
clemensw/stardust
import React from 'react' import Button from 'src/elements/Button/Button' import ButtonContent from 'src/elements/Button/ButtonContent' import ButtonGroup from 'src/elements/Button/ButtonGroup' import ButtonOr from 'src/elements/Button/ButtonOr' import * as common from 'test/specs/commonTests' import { sandbox } from 'test/utils' const syntheticEvent = { preventDefault: () => undefined } describe('Button', () => { common.isConformant(Button) common.hasUIClassName(Button) common.hasSubComponents(Button, [ButtonContent, ButtonGroup, ButtonOr]) common.implementsCreateMethod(Button) common.implementsIconProp(Button) common.implementsLabelProp(Button, { shorthandDefaultProps: { basic: true, pointing: 'left', }, }) common.propKeyOnlyToClassName(Button, 'active') common.propKeyOrValueAndKeyToClassName(Button, 'animated') common.propKeyOrValueAndKeyToClassName(Button, 'attached') common.propKeyOnlyToClassName(Button, 'basic') common.propKeyOnlyToClassName(Button, 'circular') common.propValueOnlyToClassName(Button, 'color') common.propKeyOnlyToClassName(Button, 'compact') common.propKeyOnlyToClassName(Button, 'disabled') common.propKeyAndValueToClassName(Button, 'floated') common.propKeyOnlyToClassName(Button, 'fluid') common.propKeyOnlyToClassName(Button, 'inverted') common.propKeyOrValueAndKeyToClassName(Button, 'labelPosition', { className: 'labeled', }) common.propKeyOnlyToClassName(Button, 'loading') common.propKeyOnlyToClassName(Button, 'primary') common.propKeyOnlyToClassName(Button, 'negative') common.propKeyOnlyToClassName(Button, 'positive') common.propKeyOnlyToClassName(Button, 'secondary') common.propValueOnlyToClassName(Button, 'size') common.rendersChildren(Button) it('renders a button by default', () => { shallow(<Button />) .first() .should.have.tagName('button') }) describe('attached', () => { it('renders a div', () => { shallow(<Button attached />) .should.have.tagName('div') }) }) describe('icon', () => { it('adds className icon', () => { shallow(<Button icon='user' />) .should.have.className('icon') }) it('does not add className icon when there is content', () => { shallow(<Button icon='user' content='Yo' />) .should.not.have.className('icon') }) it('adds className icon given labelPosition and content', () => { shallow(<Button labelPosition='left' icon='user' content='My Account' />) .should.have.className('icon') shallow(<Button labelPosition='right' icon='user' content='My Account' />) .should.have.className('icon') }) }) describe('label', () => { it('renders as a div', () => { shallow(<Button label='http' />) .should.have.tagName('div') }) it('renders a div with a button and Label child', () => { const wrapper = shallow(<Button label='hi' />) wrapper.should.have.tagName('div') wrapper.should.have.exactly(1).descendants('button') wrapper.should.have.exactly(1).descendants('Label') }) it('adds the labeled className to the root element', () => { shallow(<Button label='hi' />) .should.have.className('labeled') }) it('creates a basic pointing label', () => { shallow(<Button label='foo' />) .should.have.exactly(1).descendants('Label[basic][pointing]') }) it('is before the button and pointing="right" when labelPosition="left"', () => { const wrapper = shallow(<Button labelPosition='left' label='foo' />) wrapper.should.have.exactly(1).descendants('Label[pointing="right"]') wrapper.children().at(0).shallow().should.match('.ui.label') wrapper.children().at(1).should.match('button') }) it('is after the button and pointing="left" when labelPosition="right"', () => { const wrapper = shallow(<Button labelPosition='right' label='foo' />) wrapper.should.have.exactly(1).descendants('Label[pointing="left"]') wrapper.children().at(0).should.match('button') wrapper.children().at(1).shallow().should.match('.ui.label') }) it('is after the button and pointing="left" by default', () => { const wrapper = shallow(<Button label='foo' />) wrapper.should.have.exactly(1).descendants('Label[pointing="left"]') wrapper.children().at(0).should.match('button') wrapper.children().at(1).shallow().should.match('.ui.label') }) }) describe('labelPosition', () => { it('renders as a button when given an icon', () => { shallow(<Button labelPosition='left' icon='user' />) .should.have.tagName('button') shallow(<Button labelPosition='right' icon='user' />) .should.have.tagName('button') }) }) describe('onClick', () => { it('is called when clicked', () => { const handleClick = sandbox.spy() shallow(<Button type='submit' onClick={handleClick} />) .simulate('click', syntheticEvent) handleClick.should.have.been.calledOnce() }) it('is not called when button is disabled', () => { const handleClick = sandbox.spy() shallow(<Button type='submit' disabled onClick={handleClick} />) .simulate('click', syntheticEvent) handleClick.should.not.have.been.calledOnce() }) }) describe('tabIndex', () => { it('is not set by default', () => { shallow(<Button />) .should.not.have.prop('tabIndex') }) it('defaults to 0 as div', () => { shallow(<Button as='div' />) .should.have.prop('tabIndex', 0) }) it('defaults to -1 when disabled', () => { shallow(<Button disabled />) .should.have.prop('tabIndex', -1) }) it('can be set explicitly', () => { shallow(<Button tabIndex={123} />) .should.have.prop('tabIndex', 123) }) it('can be set explicitly when disabled', () => { shallow(<Button tabIndex={123} disabled />) .should.have.prop('tabIndex', 123) }) }) })
frontend/scripts/components/common/TextInput.js
jakubzloczewski/react-exercise
import React from 'react'; class TextInput extends React.Component { render() { const {onChange, placeholder} = this.props; const style = this.getStyle(); return (<input style={style} type="text" placeholder={placeholder} onChange={onChange}/>); } getStyle() { return { padding: '0.5em 1em', margin: '0.5em', fontSize: '0.7em' }; } } export default TextInput;
src/pages/home/index.js
joefraley/ratticusscript
'use strict' import Helmet from 'react-helmet' import { ListOfPosts } from '../../components/blog/list-of-posts' import Path from 'path-browserify' import { ProfilePhoto } from '../../components/profile-photo' import React from 'react' import { getPosts } from '../../utilities' export const HomePage = props => { return <section className="home"> <Helmet title="Home | RatticusScript" meta={[{ content: `The internet home base of Joe Fraley. That's me. You get what you pay for (you didn't pay anything...check yourself!)`, name: 'description' }]} /> <header> <ProfilePhoto /> <div role="introduction"> <h1>Joe Fraley</h1> <p>Just hoping to leave the world a little better than I found it.</p> </div> </header> <ListOfPosts posts={ getPosts() }/> </section> }
internals/templates/homePage/homePage.js
adoveil/max
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class HomePage extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
generators/component/templates/4/components/StatelessCssModules.js
react-webpack-generators/generator-react-webpack
import React from 'react'; import cssmodules from 'react-css-modules'; import styles from '<%= style.webpackPath %>'; const <%= component.className %> = () => ( <div className="<%= style.className %>" styleName="<%= style.className %>"> Please edit <%= component.path %><%= component.fileName %> to update this component! </div> ); <%= component.className %>.displayName = '<%= component.displayName %>'; <%= component.className %>.propTypes = {}; <%= component.className %>.defaultProps = {}; export default cssmodules(<%= component.className %>, styles);
app/javascript/mastodon/components/__tests__/autosuggest_emoji-test.js
cobodo/mastodon
import React from 'react'; import renderer from 'react-test-renderer'; import AutosuggestEmoji from '../autosuggest_emoji'; describe('<AutosuggestEmoji />', () => { it('renders native emoji', () => { const emoji = { native: '💙', colons: ':foobar:', }; const component = renderer.create(<AutosuggestEmoji emoji={emoji} />); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); it('renders emoji with custom url', () => { const emoji = { custom: true, imageUrl: 'http://example.com/emoji.png', native: 'foobar', colons: ':foobar:', }; const component = renderer.create(<AutosuggestEmoji emoji={emoji} />); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); });
src/components/Markdown/Markdown.js
nolawi/champs-dialog-sg
/** * Copyright 2017 dialog LLC <info@dlg.im> * @flow */ import React, { Component } from 'react'; import classNames from 'classnames'; import { parse, parseInline, decorators } from '@dlghq/markdown'; import { renderBlocks, renderText } from './render'; import styles from './Markdown.css'; export type Props = { className?: string, text: string, inline?: boolean, tagName?: string, decorators: typeof decorators, renderText: typeof renderText, renderBlocks: typeof renderBlocks, emojiSize: number }; class Markdown extends Component { props: Props; static defaultProps = { decorators, renderText, renderBlocks, emojiSize: 18 }; shouldComponentUpdate(nextProps: Props): boolean { return nextProps.text !== this.props.text || nextProps.className !== this.props.className; } render() { if (this.props.inline) { const TagName = this.props.tagName || 'span'; const tokens = parseInline(this.props.text, this.props.decorators); const inlineClassName = classNames(styles.inline, this.props.className); return ( <TagName className={inlineClassName}> {this.props.renderText(tokens, this.props.emojiSize, true)} </TagName> ); } const TagName = this.props.tagName || 'div'; const className = classNames(styles.container, this.props.className); const tokens = parse(this.props.text, this.props.decorators); return ( <TagName className={className}> {this.props.renderBlocks(tokens)} </TagName> ); } } export default Markdown;
src/entypo/ChevronSmallRight.js
cox-auto-kc/react-entypo
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--ChevronSmallRight'; let EntypoChevronSmallRight = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M11,10L7.859,6.58c-0.268-0.27-0.268-0.707,0-0.978c0.268-0.27,0.701-0.27,0.969,0l3.83,3.908c0.268,0.271,0.268,0.709,0,0.979l-3.83,3.908c-0.267,0.272-0.701,0.27-0.969,0c-0.268-0.269-0.268-0.707,0-0.978L11,10z"/> </EntypoIcon> ); export default EntypoChevronSmallRight;
public/components/tehtPage/tabsComponents/tehtava/Kohdekortti.js
City-of-Vantaa-SmartLab/kupela
import React from 'react'; import Showcase from '../reusables/templates/Showcase'; import { connect } from 'react-redux'; const Kohdekortti = (props) => ( <div className="kohdekortti"> <h2>Kohdekortti:</h2> {props.kohdekortit.map((card) => <Showcase src={card.url}/> )} </div> ); const mapStateToProps = ({ kohdekortit }) => ({ kohdekortit }); export default connect(mapStateToProps, null)(Kohdekortti);
src/index.js
udfalkso/react-redux
import React from 'react'; import createAll from './components/createAll'; export const { Provider, connect } = createAll(React);
website/src/AppFrame.js
kkamperschroer/react-navigation
import React from 'react'; import Link from './Link'; import Footer from './Footer'; import { addNavigationHelpers, } from 'react-navigation'; const NavigationLinks = ({navigation, className, reverse}) => { let links = [ ...navigation.state.routes.map((route, i) => { if (route.routeName === 'Home' || route.routeName === 'NotFound') { return null; } return ( <Link to={route.routeName} className={i === navigation.state.index ? 'active':''} key={route.routeName}> {route.routeName} </Link> ); }), <a href="https://github.com/react-community/react-navigation" key="github"> GitHub </a>, ]; if (reverse) { links = links.reverse(); } return ( <div className={className}> {links} </div> ); } class AppFrame extends React.Component { state = {isMobileMenuOpen: false}; componentWillReceiveProps(props) { if (this.props.navigation.state !== props.navigation.state) { this.setState({isMobileMenuOpen: false}); window.scrollTo(0,0); } } render() { const {navigation, router} = this.props; const {isMobileMenuOpen} = this.state; const childNavigation = addNavigationHelpers({ ...navigation, state: navigation.state.routes[navigation.state.index], }); const {state} = navigation; const ScreenView = router.getComponentForRouteName(state.routes[state.index].routeName); const {routes, index} = state; const route = routes[index]; const hasChildNavigation = !!route.routes; return ( <div className={`main-app ${isMobileMenuOpen ? 'mobileMenuActive' : ''}`}> <nav className="pt-navbar" id="navbar"><div className="inner-navbar"> <Link className="pt-navbar-group pt-align-left project-title" to="Home"> <img src="/assets/react-nav-logo.svg" role="presentation" className="logo" /> <h1 className="pt-navbar-heading"> React Navigation </h1> </Link> <NavigationLinks navigation={navigation} className="navbuttons" /> {hasChildNavigation && ( <span className={`pt-icon-properties openMenuButton ${isMobileMenuOpen ? 'active' : ''}`} onClick={() => { this.setState(s => ({ isMobileMenuOpen: !s.isMobileMenuOpen})); window.scrollTo(0,0); }} /> )} </div></nav> <NavigationLinks navigation={navigation} className="mobile-navbuttons" reverse /> <ScreenView navigation={childNavigation} /> <Footer /> </div> ); } } export default AppFrame;
src/svg-icons/notification/phone-paused.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationPhonePaused = (props) => ( <SvgIcon {...props}> <path d="M17 3h-2v7h2V3zm3 12.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 3v7h2V3h-2z"/> </SvgIcon> ); NotificationPhonePaused = pure(NotificationPhonePaused); NotificationPhonePaused.displayName = 'NotificationPhonePaused'; NotificationPhonePaused.muiName = 'SvgIcon'; export default NotificationPhonePaused;
CompositeUi/src/views/component/__tests__/CardExtended.js
kreta/kreta
/* * This file is part of the Kreta package. * * (c) Beñat Espiña <benatespina@gmail.com> * (c) Gorka Laucirica <gorka.lauzirika@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import React from 'react'; import {shallow} from 'enzyme'; import CardExtended from './../CardExtended'; import Thumbnail from './../Thumbnail'; describe('<CardExtended />', () => { it('renders basic component', () => { const wrapper = shallow(<CardExtended title="Example card" />); expect(wrapper.find('.card-extended__header').text()).toBe('Example card'); expect(wrapper.find('.card-extended__thumbnail')).toHaveLength(0); expect(wrapper.find('.card-extended__sub-header')).toHaveLength(0); expect(wrapper.find('.card-extended__actions').children()).toHaveLength(0); }); it('renders title with thumbnail', () => { const wrapper = shallow( <CardExtended thumbnail={<Thumbnail text="me" />} title="Example card" />, ); expect(wrapper.find('.card-extended__header').text()).toBe('Example card'); expect( wrapper .find('.card-extended__thumbnail') .contains(<Thumbnail text="me" />), ).toBe(true); expect(wrapper.find('.card-extended__sub-header')).toHaveLength(0); expect(wrapper.find('.card-extended__actions').children()).toHaveLength(0); }); it('renders title and subtitle with thumbnail', () => { const wrapper = shallow( <CardExtended subtitle="Example subtitle" thumbnail={<Thumbnail text="me" />} title="Example card" />, ); expect(wrapper.find('.card-extended__header').text()).toBe('Example card'); expect( wrapper .find('.card-extended__thumbnail') .contains(<Thumbnail text="me" />), ).toBe(true); expect(wrapper.find('.card-extended__sub-header').text()).toBe( 'Example subtitle', ); expect(wrapper.find('.card-extended__actions').children()).toHaveLength(0); }); it('renders children as actions', () => { const wrapper = shallow( <CardExtended title="Example card"> <a href="#">Add</a> </CardExtended>, ); expect(wrapper.find('.card-extended__header').text()).toBe('Example card'); expect(wrapper.find('.card-extended__thumbnail')).toHaveLength(0); expect(wrapper.find('.card-extended__sub-header')).toHaveLength(0); expect( wrapper.find('.card-extended__actions').contains(<a href="#">Add</a>), ).toBe(true); }); });
collect-webapp/frontend/src/datamanagement/components/NewRecordParametersDialog.js
openforis/collect
import React from 'react' import PropTypes from 'prop-types' import { Button, Dialog, DialogTitle, DialogActions, Table, TableBody, TableCell, TableHead, TableRow, } from '@mui/material' import L from 'utils/Labels' import Dates from 'utils/Dates' const NewRecordParametersDialog = (props) => { const { onClose, onOk, versions, open } = props return ( <Dialog onClose={onClose} aria-labelledby="new-record-parameters-dialog-title" open={open}> <DialogTitle id="new-record-parameters-dialog-title"> {L.l('dataManagement.formVersioning.selectFormVersion')} </DialogTitle> <div> <Table> <TableHead> <TableRow> <TableCell>{L.l('common.name')}</TableCell> <TableCell>{L.l('common.label')}</TableCell> <TableCell>{L.l('common.date')}</TableCell> </TableRow> </TableHead> <TableBody> {versions.map((v) => ( <TableRow key={v.id} hover onClick={() => onOk(v.id)}> <TableCell>{v.name}</TableCell> <TableCell>{v.label}</TableCell> <TableCell>{Dates.convertFromISOToStandard(v.date)}</TableCell> </TableRow> ))} </TableBody> </Table> </div> <DialogActions> <Button onClick={onClose}>{L.l('general.cancel')}</Button> </DialogActions> </Dialog> ) } NewRecordParametersDialog.propTypes = { onClose: PropTypes.func.isRequired, onOk: PropTypes.func.isRequired, open: PropTypes.bool, versions: PropTypes.array.isRequired, } NewRecordParametersDialog.defaultProps = { open: false, } export default NewRecordParametersDialog
src/parser/deathknight/unholy/modules/features/ClawingShadowsEfficiency.js
fyruna/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import Analyzer from 'parser/core/Analyzer'; import Enemies from 'parser/shared/modules/Enemies'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import { encodeTargetString } from 'parser/shared/modules/EnemyInstances'; class ClawingShadowsEfficiency extends Analyzer { static dependencies = { enemies: Enemies, }; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.CLAWING_SHADOWS_TALENT.id); } // used to track how many stacks a target has targets = {}; totalClawingShadowsCasts = 0; clawingShadowCastsZeroWounds = 0; on_byPlayer_applydebuffstack(event){ const spellId = event.ability.guid; if(spellId === SPELLS.FESTERING_WOUND.id){ this.targets[encodeTargetString(event.targetID, event.targetInstance)] = event.stack; } } on_byPlayer_removedebuffstack(event){ const spellId = event.ability.guid; if(spellId === SPELLS.FESTERING_WOUND.id){ this.targets[encodeTargetString(event.targetID, event.targetInstance)] = event.stack; } } on_byPlayer_removedebuff(event){ const spellId = event.ability.guid; if(spellId === SPELLS.FESTERING_WOUND.id){ this.targets[encodeTargetString(event.targetID, event.targetInstance)] = 0; } } on_byPlayer_cast(event){ const spellId = event.ability.guid; if(spellId === SPELLS.CLAWING_SHADOWS_TALENT.id){ this.totalClawingShadowsCasts++; if(this.targets.hasOwnProperty(encodeTargetString(event.targetID, event.targetInstance))){ const currentTargetWounds = this.targets[encodeTargetString(event.targetID, event.targetInstance)]; if(currentTargetWounds < 1){ this.clawingShadowCastsZeroWounds++; } } else { this.clawingShadowCastsZeroWounds++; } } } suggestions(when) { const percentCastZeroWounds = this.clawingShadowCastsZeroWounds/this.totalClawingShadowsCasts; const strikeEfficiency = 1 - percentCastZeroWounds; when(strikeEfficiency).isLessThan(0.80) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>You are casting <SpellLink id={SPELLS.CLAWING_SHADOWS_TALENT.id} /> too often. When spending runes remember to cast <SpellLink id={SPELLS.FESTERING_STRIKE.id} /> instead on targets with no stacks of <SpellLink id={SPELLS.FESTERING_WOUND.id} /></span>) .icon(SPELLS.CLAWING_SHADOWS_TALENT.icon) .actual(`${formatPercentage(actual)}% of Clawing Shadows were used with Wounds on the target`) .recommended(`>${formatPercentage(recommended)}% is recommended`) .regular(recommended - 0.20).major(recommended - 0.40); }); } statistic() { const percentCastZeroWounds = this.clawingShadowCastsZeroWounds/this.totalClawingShadowsCasts; const strikeEfficiency = 1 - percentCastZeroWounds; return ( <StatisticBox icon={<SpellIcon id={SPELLS.CLAWING_SHADOWS_TALENT.id} />} value={`${formatPercentage(strikeEfficiency)} %`} label="Clawing Shadows Efficiency" tooltip={`${this.clawingShadowCastsZeroWounds} out of ${this.totalClawingShadowsCasts} Clawing Shadows were used with no Festering Wounds on the target.`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(3); } export default ClawingShadowsEfficiency;
src/svg-icons/action/backup.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionBackup = (props) => ( <SvgIcon {...props}> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z"/> </SvgIcon> ); ActionBackup = pure(ActionBackup); ActionBackup.displayName = 'ActionBackup'; ActionBackup.muiName = 'SvgIcon'; export default ActionBackup;
components/page-title.js
bukinoshita/open-source
import React from 'react' const PageTitle = () => ( <div> <h1 className="page__title">Embrace Open Source</h1> <h2 className="page__subtitle">A list of GitHub issues to help beginners make their first pull request.</h2> <style jsx>{` .page__title { color: #3d4752; font-weight: 400; text-align: center; font-size: 32px; margin-top: 100px; letter-spacing: 2px; } .page__subtitle { margin-bottom: 100px; color: #5a646f; font-weight: 300; text-align: center; font-size: 18px; margin-top: 15px; } `}</style> </div> ) export default PageTitle
src/components/MaterialPicker.js
JedWatson/react-color
'use strict' /* @flow */ import React from 'react' import ReactCSS from 'reactcss' import merge from 'merge' import isPlainObject from 'lodash.isplainobject' import debounce from 'lodash.debounce' import color from '../helpers/color' import Material from './material/Material' class ColorPicker extends ReactCSS.Component { constructor(props: any) { super() this.state = merge(color.toState(props.color, 0), { visible: props.display, }) this.debounce = debounce(function(fn: any, data: any) { fn(data) }, 100) this.handleChange = this.handleChange.bind(this) this.handleHide = this.handleHide.bind(this) this.handleAccept = this.handleAccept.bind(this) this.handleCancel = this.handleCancel.bind(this) } classes(): any { return { 'show': { wrap: { zIndex: '999', position: 'absolute', display: 'block', }, picker: { zIndex: '2', position: 'relative', }, cover: { position: 'fixed', top: '0', bottom: '0', left: '0', right: '0', }, }, 'hide': { wrap: { zIndex: '999', position: 'absolute', display: 'none', }, }, 'right': { wrap: { left: '100%', marginLeft: '20px', top: '0', }, }, 'left': { wrap: { right: '100%', marginRight: '20px', top: '0', }, }, 'below': { wrap: { left: '0', marginLeft: '0', top: '100%', marginTop: '20px', }, }, 'override': { wrap: this.props.positionCSS, }, } } styles(): any { return this.css({ 'below': this.props.position === 'below' && this.props.display !== null, 'right': this.props.position === 'right' && this.props.display !== null, 'left': this.props.position === 'left' && this.props.display !== null, 'show': this.state.visible === true, 'hide': this.state.visible === false, 'override': isPlainObject(this.props.positionCSS), }) } handleHide() { if (this.state.visible === true) { this.setState({ visible: false, }) this.props.onClose && this.props.onClose({ hex: this.state.hex, hsl: this.state.hsl, rgb: this.state.rgb, }) } } handleAccept() { this.handleHide() } handleCancel() { if (this.state.visible === true) { this.setState({ visible: false, }) } } handleChange(data: any) { data = color.simpleCheckForValidColor(data) if (data) { var colors = color.toState(data, data.h || this.state.oldHue) this.setState(colors) this.props.onChangeComplete && this.debounce(this.props.onChangeComplete, colors) this.props.onChange && this.props.onChange(colors) } } componentWillReceiveProps(nextProps: any) { this.setState(merge(color.toState(nextProps.color, this.state.oldHue), { visible: nextProps.display, })) } render(): any { return ( <div is="wrap"> <div is="picker"> <Material {...this.props} {...this.state} onChange={ this.handleChange } onAccept={ this.handleAccept } onCancel={ this.handleCancel } /> </div> <div is="cover" onClick={ this.handleHide }/> </div> ) } } ColorPicker.defaultProps = { color: { h: 250, s: .50, l: .20, a: 1, }, display: null, type: 'sketch', position: 'right', positionCSS: {}, } export default ColorPicker
src/Input/Input.spec.js
nirhart/wix-style-react
import React from 'react'; import ReactTestUtils from 'react-addons-test-utils'; import inputDriverFactory from './Input.driver'; import Input from './Input'; import sinon from 'sinon'; import {createDriverFactory} from '../test-common'; import {inputTestkitFactory} from '../../testkit'; import {inputTestkitFactory as enzymeInputTestkitFactory} from '../../testkit/enzyme'; import {mount} from 'enzyme'; describe('Input', () => { const createDriver = createDriverFactory(inputDriverFactory); describe('value attribute', () => { it('should pass down to the wrapped input', () => { const props = { value: 'hello', onChange: () => {} }; const driver = createDriver(<Input {...props}/>); expect(driver.getValue()).toEqual(props.value); }); }); describe('defaultValue attribute', () => { it('should pass down to the wrapped input', () => { const defaultValue = 'hello'; const driver = createDriver(<Input defaultValue={defaultValue}/>); expect(driver.getDefaultValue()).toEqual(defaultValue); }); }); describe('tabIndex attribute', () => { it('should pass down to the wrapped input', () => { const tabIndex = 1; const driver = createDriver(<Input tabIndex={tabIndex}/>); expect(driver.getTabIndex()).toEqual(tabIndex); }); }); describe('readOnly attribute', () => { it('should pass down to the wrapped input', () => { const driver = createDriver(<Input readOnly/>); expect(driver.getReadOnly()).toBeTruthy(); }); it('should pass down to the wrapped input with default false value', () => { const driver = createDriver(<Input/>); expect(driver.getReadOnly()).toBeFalsy(); }); }); describe('type attribute', () => { it('should set the type attribute', () => { const driver = createDriver(<Input type="number"/>); expect(driver.getType()).toBe('number'); }); }); describe('error attribute', () => { it('should display an error icon if error is true', () => { const driver = createDriver(<Input error/>); expect(driver.hasExclamation()).toBeTruthy(); expect(driver.hasError()).toBeTruthy(); }); }); describe('unit attribute', () => { it('should the unit text if passed', () => { const unit = '$'; const driver = createDriver(<Input unit={unit}/>); expect(driver.getUnit()).toEqual(unit); }); }); describe('magnifyingGlass attribute', () => { it('should display a magnifying glass icon if magnifyingGlass is true', () => { const driver = createDriver(<Input magnifyingGlass/>); expect(driver.hasMagnifyingGlass()).toBeTruthy(); }); it('should not display a magnifying glass icon if magnifyingGlass is false', () => { const driver = createDriver(<Input magnifyingGlass={false}/>); expect(driver.hasMagnifyingGlass()).toBeFalsy(); }); it('should not display a magnifying glass icon if error is true', () => { const driver = createDriver(<Input magnifyingGlass error/>); expect(driver.hasMagnifyingGlass()).toBeFalsy(); }); }); describe('menuArrow attribute', () => { it('should display a menu arrow icon if menuArrow is true', () => { const driver = createDriver(<Input menuArrow/>); expect(driver.hasMenuArrow()).toBeTruthy(); }); it('should not display a menu arrow icon if menuArrow is false', () => { const driver = createDriver(<Input menuArrow={false}/>); expect(driver.hasMenuArrow()).toBeFalsy(); }); it('should not display a menu arrow icon if error is true', () => { const driver = createDriver(<Input menuArrow error/>); expect(driver.hasMenuArrow()).toBeFalsy(); }); it('should not display a menu arrow icon if magnifyingGlass is true', () => { const driver = createDriver(<Input menuArrow magnifyingGlass/>); expect(driver.hasMenuArrow()).toBeFalsy(); }); }); describe('rtl attribute', () => { it('should have rtl if rtl prop is true', () => { const driver = createDriver(<Input rtl/>); expect(driver.isRTL()).toBeTruthy(); }); it('should not have rtl if rtl prop is false', () => { const driver = createDriver(<Input rtl={false}/>); expect(driver.isRTL()).toBeFalsy(); }); }); describe('onChange attribute', () => { it('should be called when text is entered to the input', () => { const onChange = jest.fn(); const event = {target: {value: 'world'}}; const driver = createDriver(<Input onChange={onChange}/>); driver.trigger('change', event); expect(onChange).toBeCalled(); }); }); describe('onKeyUp attribute', () => { it('should be called after keybord key got pressed and then released', () => { const onKeyUp = jest.fn(); const event = {target: {value: 'world'}}; const driver = createDriver(<Input onKeyUp={onKeyUp}/>); driver.trigger('keyUp', event); expect(onKeyUp).toBeCalled(); }); }); describe('onFocus attribute', () => { it('should be called when the input gets focused', () => { const onFocus = jest.fn(); const driver = createDriver(<Input onFocus={onFocus}/>); driver.trigger('focus'); expect(onFocus).toBeCalled(); }); }); describe('onBlur attribute', () => { it('should be called when the input gets blured', () => { const onBlur = jest.fn(); const driver = createDriver(<Input onBlur={onBlur}/>); driver.trigger('blur'); expect(onBlur).toBeCalled(); }); }); describe('onKeyDown attribute', () => { it('should be called when text is entered to the wrapped input', () => { const onKeyDown = jest.fn(); const event = {keyCode: 40}; const driver = createDriver(<Input onKeyDown={onKeyDown}/>); driver.trigger('keyDown', event); expect(onKeyDown).toBeCalled(); }); }); describe('forceFocus attribute', () => { it('should have focus class on input if forceFocus is true', () => { const driver = createDriver(<Input forceFocus/>); expect(driver.isFocusedStyle()).toBeTruthy(); }); }); describe('forceHover attribute', () => { it('should have hover class on input if forceHover is true', () => { const driver = createDriver(<Input forceHover/>); expect(driver.isHoveredStyle()).toBeTruthy(); }); it('should be hovered if forceFocus is false and forceHover is true', () => { const driver = createDriver(<Input forceHover forceFocus={false}/>); expect(driver.isHoveredStyle()).toBeTruthy(); }); }); describe('disable attribute', () => { it('should have disabled class on input if disabled is true', () => { const driver = createDriver(<Input disabled/>); expect(driver.isDisabled()).toBeTruthy(); }); }); describe('autoFocus attribute', () => { it('Mounting an input element with autoFocus=false, should give it the focus', () => { let autoFocus = false; const driver = createDriver(<Input autoFocus={false}/>); expect(driver.isFocus()).toBeFalsy(); autoFocus = true; driver.setProps({autoFocus}); expect(driver.isFocus()).toBeFalsy(); }); it('Mounting an input element with autoFocus=true, gives it the focus', () => { const driver = createDriver(<Input autoFocus/>); expect(driver.isFocus()).toBeTruthy(); }); }); describe('focus function', () => { it('calling focus should give focus to the input', () => { const driver = createDriver(<Input autoFocus={false}/>); expect(driver.isFocus()).toBeFalsy(); driver.focus(); expect(driver.isFocus()).toBeTruthy(); }); }); describe('theme attribute', () => { it('should set the theme by default to "normal"', () => { const driver = createDriver(<Input/>); expect(driver.isOfStyle('normal')).toBeTruthy(); }); it('should allowing setting the theme to "paneltitle"', () => { const driver = createDriver(<Input theme="paneltitle"/>); expect(driver.isOfStyle('paneltitle')).toBeTruthy(); }); it('should allow setting the theme to "material"', () => { const driver = createDriver(<Input theme="material"/>); expect(driver.isOfStyle('material')).toBeTruthy(); }); }); describe('onClear attribute', () => { it('should not be displayed when text is empty', () => { const onClear = () => {}; const onChange = () => {}; const driver = createDriver(<Input onClear={onClear} value="" onChange={onChange}/>); expect(driver.hasClearButton()).toBeFalsy(); }); it('should display a X when text is not null, and be clickable', () => { const onClear = sinon.spy(); const onChange = () => {}; const driver = createDriver(<Input onClear={onClear} value={'some value'} onChange={onChange}/>); expect(driver.hasClearButton()).toBeTruthy(); driver.clickClear(); expect(onClear.calledOnce).toBeTruthy(); }); it('should display a left icon when one is passed', () => { const driver = createDriver(<Input iconLeft={<div/>}/>); expect(driver.hasIconLeft()).toBeTruthy(); }); }); describe('size attribute', () => { it('should use "normal" size by default', () => { const driver = createDriver(<Input/>); expect(driver.isOfSize('normal')).toBeTruthy(); }); it('should use "small" size', () => { const driver = createDriver(<Input size="small"/>); expect(driver.isOfSize('small')).toBeTruthy(); }); it('should use "large" size', () => { const driver = createDriver(<Input size="large"/>); expect(driver.isOfSize('large')).toBeTruthy(); }); }); describe('prefix attribute', () => { it('should allow adding a custom prefix component', () => { const driver = createDriver(<Input prefix={<div className="my-button"/>}/>); expect(driver.hasPrefix()).toBeTruthy(); expect(driver.prefixComponentExists('.my-button')).toBeTruthy(); }); it('should add `withPrefix` classname to input', () => { const driver = createDriver(<Input prefix="hello"/>); expect(driver.hasPrefixClass()).toBeTruthy(); }); }); describe('suffix attribute', () => { it('should allow adding a custom suffix component', () => { const driver = createDriver(<Input suffix={<div className="my-button"/>}/>); expect(driver.hasSuffix()).toBeTruthy(); expect(driver.suffixComponentExists('.my-button')).toBeTruthy(); }); it('should add `withSuffix` classname to input', () => { const driver = createDriver(<Input suffix="hello"/>); expect(driver.hasSuffixClass()).toBeTruthy(); }); it('should add `withSuffixes` classname to input when more than 1 suffix applied', () => { const driver = createDriver(<Input suffix="hello" magnifyingGlass/>); expect(driver.hasSuffixesClass()).toBeTruthy(); }); }); }); describe('testkit', () => { it('should exist', () => { const div = document.createElement('div'); const value = 'hello'; const onChange = () => {}; const dataHook = 'myDataHook'; const wrapper = div.appendChild(ReactTestUtils.renderIntoDocument(<div><Input value={value} onChange={onChange} dataHook={dataHook}/></div>)); const inputTestkit = inputTestkitFactory({wrapper, dataHook}); expect(inputTestkit.exists()).toBeTruthy(); }); }); describe('enzyme testkit', () => { it('should exist', () => { const value = 'hello'; const onChange = () => {}; const dataHook = 'myDataHook'; const wrapper = mount(<Input value={value} onChange={onChange} dataHook={dataHook}/>); const inputTestkit = enzymeInputTestkitFactory({wrapper, dataHook}); expect(inputTestkit.exists()).toBeTruthy(); }); });
src/containers/Asians/Published/_AppBar/SmallAppBar/BreakRoundsButtons/index.js
westoncolemanl/tabbr-web
import React from 'react' import { connect } from 'react-redux' import Instance from './Instance' export default connect(mapStateToProps)(({ breakCategories, toggle }) => { return ( <div> {breakCategories.sort((a, b) => b.default).map(breakCategory => <Instance key={breakCategory._id} breakCategory={breakCategory} toggle={toggle} /> )} </div> ) }) function mapStateToProps (state, ownProps) { return { breakCategories: Object.values(state.breakCategories.data) } }
src/svg-icons/hardware/tv.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareTv = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.1-.9-2-2-2zm0 14H3V5h18v12z"/> </SvgIcon> ); HardwareTv = pure(HardwareTv); HardwareTv.displayName = 'HardwareTv'; HardwareTv.muiName = 'SvgIcon'; export default HardwareTv;
src/views/HeaderTitle.js
Steviey/win-react-navigation
/* @flow */ import React from 'react'; import { Platform, StyleSheet, Text, } from 'react-native'; import type { Style, } from '../TypeDefinition'; type Props = { tintColor?: ?string; style?: Style, }; const HeaderTitle = ({ style, ...rest }: Props) => ( <Text numberOfLines={1} {...rest} style={[styles.title, style]} /> ); const styles = StyleSheet.create({ title: { fontSize: Platform.OS === 'ios' ? 17 : 18, fontWeight: Platform.OS === 'ios' ? '600' : '500', color: 'rgba(0, 0, 0, .9)', textAlign: Platform.OS === 'ios' ? 'center' : 'left', marginHorizontal: 16, }, }); HeaderTitle.propTypes = { style: Text.propTypes.style, }; export default HeaderTitle;
client/src/components/Join/Join.js
jenovs/bears-team-14
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import api from '../../api'; import './style.css'; import Flash from '../Flash'; class Join extends Component { state = { errorStatus: '', busy: false, }; componentDidMount() { if (this.props.loggedIn) { this.props.history.replace('/'); } } componentWillReceiveProps(nextProps) { if (nextProps.loggedIn) { this.props.history.replace(`/`); } } handleChange = e => { this.setState(() => ({ errorStatus: '', })); }; registerUser = e => { e.preventDefault(); this.setState(() => ({ busy: true, })); const username = this.username.value; const password = this.password.value; api.registerNewUser(username, password).then(json => { if (json.error) { return this.setState(() => ({ errorStatus: json.error.text, busy: false, })); } this.props.handleLogin(json.username, json.isAdmin); }); }; render() { const { busy, errorStatus } = this.state; return ( <div className="join"> {errorStatus && <Flash danger>{errorStatus}</Flash>} <div className="columns"> <div className="column is-10 is-offset-1"> <div className="columns"> <div className="column is-one-third"> <h2 className="title">Join the adventure on Jobbatical!</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi natus aliquam, voluptatum iure pariatur vero. </p> <div className="has-text-centered"> <img src="http://via.placeholder.com/180x265" alt="Jobbatical-Dude" /> </div> </div> <div className="column is-two-thirds"> <div className="box"> <div className="field has-addons"> <a href="https://web.facebook.com" className="button is-large is-fullwidth facebook-btn" > <span className="icon is-medium"> <i className="fa fa-facebook-square" /> </span> <span>Sign up with Facebook</span> </a> </div> <div className="field has-addons"> <a href="https://google.com" className="button is-large is-fullwidth google-btn" > <span className="icon is-medium"> <i className="fa fa-google" /> </span> <span>Sign up with Google</span> </a> </div> <div className="divider line">OR</div> <form onSubmit={this.registerUser}> <div className="columns"> <div className="column"> <div className="field"> <label className="label" htmlFor="fname"> First Name </label> <div className="control has-icons-left"> <input className="input is-large" type="text" placeholder="first name" name="fname" /> <span className="icon is-medium is-left"> <i className="fa fa-user" /> </span> </div> </div> </div> <div className="column"> <div className="field"> <label className="label" htmlFor="lname"> Last name </label> <div className="control has-icons-left"> <input className="input is-large" type="tex" placeholder="last name" name="lname" /> <span className="icon is-medium is-left"> <i className="fa fa-user" /> </span> </div> </div> </div> </div> <div className="field"> <label className="label" htmlFor="text"> Username </label> <div className="control has-icons-left"> <input onChange={this.handleChange} autoFocus className="input is-large" type="text" placeholder="username" name="username" ref={el => (this.username = el)} required /> </div> </div> <div className="field"> <label className="label" htmlFor="password"> Password </label> <div className="control has-icons-left"> <input className="input is-large" type="password" placeholder="password" name="password" ref={el => (this.password = el)} required /> <span className="icon is-medium is-left"> <i className="fa fa-lock" /> </span> </div> </div> <div className="columns sign-up"> <div className="column is-size-12"> By signing up, you agree to Jobbatical’s{' '} <Link to="/">Terms of Service</Link> and{' '} <Link to="/">Privacy Policy</Link>. </div> <div className="column"> <div className="field has-addons"> <button type="submit" className="button is-fullwidth is-large is-primary" disabled={busy} > <span>SIGN UP</span> <span className="icon is-medium"> <i className="fa fa-sign-in" /> </span> </button> </div> </div> </div> </form> <hr /> <div className="is-size-12"> Already have an account?{' '} <Link to="/login">Log in here!</Link> </div> </div> </div> </div> </div> </div> </div> ); } } export default Join;
client/index.js
BostonGlobe/elections-2017
// This is the app's client-side entry point. Webpack starts here when // bundling the entire codebase. /* eslint-disable global-require, no-unused-vars */ import React from 'react' import ReactDOM from 'react-dom' import { browserHistory } from 'react-router' import configureStore from './../common/store/configureStore.js' import css from './../common/styles/config.styl' import critical from './../common/appUtils/critical.js' import setPathCookie from './../common/appUtils/setPathCookie.js' import removeMobileHover from './../common/appUtils/removeMobileHover.js' import 'picturefill' // These two calls are apps boilerplate. removeMobileHover() setPathCookie() // Grab the initial Redux state (a JSON string created by the server). const initialState = window.REDUX__INITIALSTATE // Hydrate the Redux store with `initialState`. const store = configureStore(initialState) // Get the DOM element that will house our app. const rootElement = document.getElementById('root') // Setup a `render` function that we will overwrite for hot module // reloading - see https://github.com/reactjs/redux/pull/1455. let render = () => { const Root = require('./../common/components/Root.js').default // Render React app to `rootElement`. ReactDOM.render( <Root history={browserHistory} store={store} />, rootElement) } // If HMR is enabled, if (module.hot) { const renderRoot = render // and we have an error, const renderError = (error) => { const RedBox = require('redbox-react').default // render error with `RedBox` styling. ReactDOM.render(<RedBox error={error} />, rootElement) } // Otherwise try to render app normally. render = () => { try { renderRoot() } catch (error) { renderError(error) } } module.hot.accept('./../common/components/Root.js', () => { setTimeout(render) }) } render()
app/containers/HomePage/index.js
tarioto/Portfolio
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; // import Img from './Img'; // import Headshot from './headshot.png'; export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <div className="container"> <div className="row"> <div className="col-xs-12"> <div className="page-header"> <h1><FormattedMessage {...messages.name} /> <small><FormattedMessage {...messages.title} /></small></h1> <FormattedMessage {...messages.header} /> </div> </div> </div> {/* <div className="row"> <div className="col-xs-12"> <div className="panel panel-primary"> <div className="panel-body"> <FormattedMessage {...messages.header} /> </div> </div> </div> </div> */} </div> ); } }
packages/material-ui-icons/src/Filter6.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Filter6 = props => <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zm-8-2h2c1.1 0 2-.89 2-2v-2c0-1.11-.9-2-2-2h-2V7h4V5h-4c-1.1 0-2 .89-2 2v6c0 1.11.9 2 2 2zm0-4h2v2h-2v-2z" /> </SvgIcon>; Filter6 = pure(Filter6); Filter6.muiName = 'SvgIcon'; export default Filter6;
docs/src/app/components/pages/components/Card/ExampleControlled.js
verdan/material-ui
import React from 'react'; import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card'; import FlatButton from 'material-ui/FlatButton'; import Toggle from 'material-ui/Toggle'; export default class CardExampleControlled extends React.Component { constructor(props) { super(props); this.state = { expanded: false, }; } handleExpandChange = (expanded) => { this.setState({expanded: expanded}); }; handleToggle = (event, toggle) => { this.setState({expanded: toggle}); }; handleExpand = () => { this.setState({expanded: true}); }; handleReduce = () => { this.setState({expanded: false}); }; render() { return ( <Card expanded={this.state.expanded} onExpandChange={this.handleExpandChange}> <CardHeader title="URL Avatar" subtitle="Subtitle" avatar="images/ok-128.jpg" actAsExpander={true} showExpandableButton={true} /> <CardText> <Toggle toggled={this.state.expanded} onToggle={this.handleToggle} labelPosition="right" label="This toggle controls the expanded state of the component." /> </CardText> <CardMedia expandable={true} overlay={<CardTitle title="Overlay title" subtitle="Overlay subtitle" />} > <img src="images/nature-600-337.jpg" /> </CardMedia> <CardTitle title="Card title" subtitle="Card subtitle" expandable={true} /> <CardText expandable={true}> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi. Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque. Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. </CardText> <CardActions> <FlatButton label="Expand" onTouchTap={this.handleExpand} /> <FlatButton label="Reduce" onTouchTap={this.handleReduce} /> </CardActions> </Card> ); } }
app/components/Log.js
L-A/Little-Jekyll
import React, { Component } from 'react'; var Log = React.createClass({ render: function () { return ( <li className={this.props.log.logType}><p className="log-data">{this.props.log.logData}</p></li> ); } }) module.exports = Log;
src/SvgIcon/SvgIcon.spec.js
kittyjumbalaya/material-components-web
/* eslint-env mocha */ import React from 'react'; import {spy} from 'sinon'; import {shallow} from 'enzyme'; import {assert} from 'chai'; import SvgIcon from './SvgIcon'; import getMuiTheme from '../styles/getMuiTheme'; describe('<SvgIcon />', () => { const muiTheme = getMuiTheme(); const shallowWithContext = (node) => shallow(node, {context: {muiTheme}}); const path = <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />; it('renders children by default', () => { const wrapper = shallowWithContext( <SvgIcon>{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); }); it('renders children and color', () => { const wrapper = shallowWithContext( <SvgIcon color="red">{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); assert.equal(wrapper.node.props.style.fill, 'red', 'should have color set to red'); }); it('renders children and hoverColor when mouseEnter', () => { const onMouseEnter = spy(); const wrapper = shallowWithContext( <SvgIcon className="material-icons" color="red" hoverColor="green" onMouseEnter={onMouseEnter} > {path} </SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); assert.equal(wrapper.node.props.style.fill, 'red', 'should have color set to red'); wrapper.simulate('mouseEnter'); assert.equal(wrapper.node.props.style.fill, 'green', 'should have color set to green after hover'); assert.equal(onMouseEnter.calledOnce, true, 'should have called onMouseEnter callback function'); }); it('renders children and call onMouseEnter callback', () => { const onMouseEnter = spy(); const wrapper = shallowWithContext( <SvgIcon onMouseEnter={onMouseEnter} hoverColor="green">{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); wrapper.simulate('mouseEnter'); assert.equal(onMouseEnter.calledOnce, true, 'should have called onMouseEnter callback function'); }); it('renders children and call onMouseEnter callback even when hoverColor is not set', () => { const onMouseEnter = spy(); const wrapper = shallowWithContext( <SvgIcon onMouseEnter={onMouseEnter}>{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); wrapper.simulate('mouseEnter'); assert.equal(onMouseEnter.calledOnce, true, 'should have called onMouseEnter callback function'); }); it('renders children and call onMouseLeave callback', () => { const onMouseLeave = spy(); const wrapper = shallowWithContext( <SvgIcon onMouseLeave={onMouseLeave} hoverColor="green">{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); wrapper.simulate('mouseLeave'); assert.equal(onMouseLeave.calledOnce, true, 'should have called onMouseLeave callback function'); }); it('renders children and call onMouseLeave callback even when hoverColor is not set', () => { const onMouseLeave = spy(); const wrapper = shallowWithContext( <SvgIcon onMouseLeave={onMouseLeave}>{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); wrapper.simulate('mouseLeave'); assert.equal(onMouseLeave.calledOnce, true, 'should have called onMouseLeave callback function'); }); it('renders children and overwrite styles', () => { const style = { backgroundColor: 'red', }; const wrapper = shallowWithContext( <SvgIcon style={style}>{path}</SvgIcon> ); assert.equal(wrapper.get(0).props.style.backgroundColor, style.backgroundColor, 'should have backgroundColor to red'); }); });
examples/huge-apps/routes/Course/routes/Grades/components/Grades.js
RobertKielty/react-router
import React from 'react'; class Grades extends React.Component { render () { var assignments = COURSES[this.props.params.courseId].assignments; return ( <div> <h3>Grades</h3> <ul> {assignments.map(assignment => ( <li key={assignment.id}>{assignment.grade} - {assignment.title}</li> ))} </ul> </div> ); } } export default Grades;
example/TestLibQuickblox/ContactList.js
ttdat89/react-native-video-quickblox
/** * Created by Dat Tran on 9/27/17. */ import React from 'react'; import { StyleSheet, Text, TextInput, View, LayoutAnimation, TouchableOpacity, FlatList } from 'react-native'; import QuickbloxManager from './QuickbloxManager'; export default class ContactList extends React.Component { constructor() { super() this.state = { user: 'null', users: [] } this.quickbloxManager = new QuickbloxManager() } componentDidMount() { this.quickbloxManager.getUsers(users => { if (typeof (users) === 'string') this.setState({users: JSON.parse(users)}) else if (typeof (users) === 'object' && Array.isArray(users)) this.setState({users: users}) }) } renderListItem(item) { return <TouchableOpacity onPress={() => { this.quickbloxManager.callUsers([item.id], 1, 'Dat Tran', 'https://qph.ec.quoracdn.net/main-qimg-7ea75331d55c74f7e3c0815cca3e8b4a-c') this.props.callSuccess() }}> <View style={{flexDirection: 'row', height: 44, alignItems: 'center'}}> <Text>{item.id}</Text> <View style={{width: 40}}/> <Text>{item.login}</Text> </View> </TouchableOpacity> } render() { return <View> <Text>{`userId: ${this.props.currentUser}`}</Text> <Text>Click to call</Text> <FlatList keyboardShouldPersistTaps='always' style={{backgroundColor: 'white'}} data={this.state.users} keyExtractor={(item, index) => index} renderItem={({item, index}) => this.renderListItem(item, index)}/> </View> } }
react-src/catalog/components/FilterTheme.js
gabzon/experiensa
import React from 'react'; import CatalogFilterButton from './filters/CatalogFilterButton' export default class FilterTheme extends React.Component { constructor(){ super() } renderThemesButtons(){ if(this.props.themes) { return this.props.themes.map((theme) => { return ( <CatalogFilterButton key={theme.id} id={theme.id} name={theme.name} filter_type="FILTER_THEME" options={this.props.options}/> ) }) }else{ return (<h3>No Theme Filters</h3>) } } render() { return ( <div className="column"> <h3 className="ui header"> <i className="soccer icon"/> <div className="content catalog-title">Theme</div> </h3> <div className="ui items" style={{"display": "block"}}> {this.renderThemesButtons()} </div> </div> ); } }
app/Resources/js/index.js
shempignon/podcast-api
import React from 'react' import ReactDOM from 'react-dom' import { AppContainer } from 'react-hot-loader' import routes from './routes' import injectTapEventPlugin from 'react-tap-event-plugin' injectTapEventPlugin() const render = (Component) => { ReactDOM.render( <AppContainer> <Component/> </AppContainer>, document.getElementById('root') ) } render(routes) // Hot Module Replacement API if (module.hot) { module.hot.accept('./routes', () => { render(routes) }) }
src/routes/system/Role/ModalForm.js
daizhen256/i5xwxdoctor-web
import React from 'react' import PropTypes from 'prop-types' import { Form, Input, Modal, Icon } from 'antd' import UserPower from './UserPower' import styles from './ModalForm.less' const FormItem = Form.Item const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } } const ModalForm = ({ modal: { curItem, type, visible }, loading, form: { getFieldDecorator, validateFields, resetFields }, onOk, onCancel }) => { if(!curItem.power) { curItem.power = {} } function handleOk () { validateFields((errors, values) => { if (errors) { return } const data = { ...values, id: curItem.id, power: curItem.power } onOk(data) }) } const modalFormOpts = { title: type === 'create' ? <div><Icon type="plus-circle-o" /> 新建角色</div> : <div><Icon type="edit" /> 修改角色</div>, visible, wrapClassName: 'vertical-center-modal', className: styles.modalWidth, confirmLoading: loading, onOk: handleOk, onCancel, afterClose() { resetFields() //必须项,编辑后如未确认保存,关闭时必须重置数据 } } const UserPowerGen = () => <UserPower powerList={curItem.power}/> return ( <Modal {...modalFormOpts}> <Form> <FormItem label='角色名称:' hasFeedback {...formItemLayout}> {getFieldDecorator('name', { initialValue: curItem.name, rules: [ { required: true, message: '角色名称不能为空' } ] })(<Input />)} </FormItem> <FormItem> <UserPowerGen/> </FormItem> </Form> </Modal> ) } ModalForm.propTypes = { modal: PropTypes.object, form: PropTypes.object } export default Form.create()(ModalForm)
src/components/secure/show_book.js
haki-projects/mapping-feminism-v2
import React, { Component } from 'react'; import { fetchBooks } from '../../actions/books'; import { connect } from 'react-redux'; import { Link } from 'react-router'; class BookShow extends Component { constructor(props) { super(props); } componentDidMount() { this.props.fetchBooks(); } render() { if(!this.props.book){ return <div className='container text-center'> loading....</div> } const { book } = this.props; return( <div className='container'> <div className='card'> <h3 className='card-header'> Title: {book.original_title} <br /> </h3> <div className='card-block'> <div className='card-text'> Author: {book.author_first_name + ' ' + book.author_last_name} <br /> Original Title: {book.original_title} <br /> Translation Title: {book.translation_title} <br /> Original Language: {book.original_lang} <br /> Translator: {book.translator} <br /> Translation Publication Date: {book.translation_pub_date} <br /> original Publication Date: {book.original_pub_date} <br /> </div> </div> <div className='card-footer'><Link className='btn btn-primary' to='/dashboard'>Back </Link> </div> </div> </div> ) }; } function mapStateToProps({ books }, ownProps){ const id = ownProps.params.id; return { books, book: books[id] }; } export default connect(mapStateToProps, { fetchBooks} )(BookShow);
index.ios.js
jokunhe/react-native-ee-camera
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class chuanzhang 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('chuanzhang', () => chuanzhang);
src/components/ControllerUnit.js
budunwang/React-Gallery
import React from 'react'; class ControllerUnit extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } //索引点击事件 handleClick(e) { if(this.props.arrange.isCenter) { this.props.inverse(); } else { this.props.center(); } e.stopPropagation(); e.preventDefault(); } render() { //根据图片状态加载索引条 let controllerUnitClassName = 'controller-unit'; controllerUnitClassName = this.props.arrange.isCenter? controllerUnitClassName + ' is-center':controllerUnitClassName; controllerUnitClassName = this.props.arrange.isInverse? controllerUnitClassName + ' is-inverse':controllerUnitClassName; return ( <span className={controllerUnitClassName} onClick={this.handleClick}></span> ) } } export default ControllerUnit;
src/components/RevealAuction/RevealAuctionInfo.js
PhyrexTsai/ens-bid-dapp
import React from 'react'; import {shortFormatHash, momentFromNow} from '../../lib/util'; import Button from 'material-ui/Button'; import Card from 'material-ui/Card'; import Divider from 'material-ui/Divider'; import './RevealAuctionInfo.css'; const FinalizeAuctionOn = (props) => <div className='FinalizeAuctionOn'> <h4>Finalize Auction On:</h4> <p>{props.registratesAt}</p> <p>{props.endsMomentFromNow}</p> <Divider /> </div>; const InfoItem = (props) => { let classes = ''; if (props.title === 'ENS') classes = 'eth-item'; if (props.title === 'TxHash') classes = 'eth-txhash'; if (props.title === 'JSON') classes = 'eth-json'; return ( <div className='RevealAuctionInfo-info-item'> <p> <span>{props.title}:</span> <span className={classes}>{props.children}</span> </p> <Divider /> </div> ) } export const RevealAuctionInfo = (props) => { const endsMomentFromNow = momentFromNow(props.registratesAt); const hidden = (props.registratesAt.year() - 1970) <= 0; const ethersacnUrl = process.env.REACT_APP_ETHERSCAN_URL || 'https://ropsten.etherscan.io/tx/'; const txHashUrl = ethersacnUrl + props.revealTXHash; const finalizeAuctionOn = !hidden && <FinalizeAuctionOn registratesAt={props.registratesAt.toString()} endsMomentFromNow={endsMomentFromNow.toString()} />; const {ethBid, secret} = props.formResult const shorterTxHash = shortFormatHash(props.revealTXHash); const itemTitleValue = [ {title: 'ENS', value: `${props.searchResult.searchName}.eth`}, {title: 'ETH Bid', value: ethBid}, {title: 'Secret', value: secret}, {title: 'TxHash', value: <a target='_blank' href={txHashUrl}>{shorterTxHash}</a>}, {title: 'JSON', value: JSON.parse(props.exportJson)} ]; const infoItems = itemTitleValue.map(({title, value}, index) => <InfoItem key={`infoItem-${index}`} title={title}>{value}</InfoItem> ); return ( <Card raised> <div className='RevealAuctionInfo'> {finalizeAuctionOn} {infoItems} <div className='RevealAuctionInfo-actions'> <Button raised onClick={() => props.backToSearch()}>BACK TO SEARCH</Button> {/*<Button raised>MY ENS LIST</Button>*/} </div> </div> </Card> ); };
pootle/static/js/admin/components/Language/LanguageController.js
pavels/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; import Search from '../Search'; import LanguageAdd from './LanguageAdd'; import LanguageEdit from './LanguageEdit'; const LanguageController = React.createClass({ propTypes: { items: React.PropTypes.object.isRequired, model: React.PropTypes.func.isRequired, onAdd: React.PropTypes.func.isRequired, onCancel: React.PropTypes.func.isRequired, onDelete: React.PropTypes.func.isRequired, onSearch: React.PropTypes.func.isRequired, onSelectItem: React.PropTypes.func.isRequired, onSuccess: React.PropTypes.func.isRequired, searchQuery: React.PropTypes.string.isRequired, selectedItem: React.PropTypes.object, view: React.PropTypes.string.isRequired, }, render() { const viewsMap = { add: ( <LanguageAdd model={this.props.model} collection={this.props.items} onSuccess={this.props.onSuccess} onCancel={this.props.onCancel} /> ), edit: ( <LanguageEdit model={this.props.selectedItem} collection={this.props.items} onAdd={this.props.onAdd} onSuccess={this.props.onSuccess} onDelete={this.props.onDelete} /> ), }; const args = { count: this.props.items.count, }; let msg; if (this.props.searchQuery) { msg = ngettext('%(count)s language matches your query.', '%(count)s languages match your query.', args.count); } else { msg = ngettext( 'There is %(count)s language.', 'There are %(count)s languages. Below are the most recently added ones.', args.count ); } const resultsCaption = interpolate(msg, args, true); return ( <div className="admin-app-languages"> <div className="module first"> <Search fields={['index', 'code', 'fullname']} onSearch={this.props.onSearch} onSelectItem={this.props.onSelectItem} items={this.props.items} selectedItem={this.props.selectedItem} searchLabel={gettext('Search Languages')} searchPlaceholder={gettext('Find language by name, code')} resultsCaption={resultsCaption} searchQuery={this.props.searchQuery} /> </div> <div className="module admin-content"> {viewsMap[this.props.view]} </div> </div> ); }, }); export default LanguageController;
src/svg-icons/image/add-to-photos.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageAddToPhotos = (props) => ( <SvgIcon {...props}> <path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9h-4v4h-2v-4H9V9h4V5h2v4h4v2z"/> </SvgIcon> ); ImageAddToPhotos = pure(ImageAddToPhotos); ImageAddToPhotos.displayName = 'ImageAddToPhotos'; ImageAddToPhotos.muiName = 'SvgIcon'; export default ImageAddToPhotos;
docs/index.js
casesandberg/reactcss
'use strict' import ReactDOM from 'react-dom' import React from 'react' import '../node_modules/normalize.css/normalize.css' import Docs from './components/docs/Docs' ReactDOM.render( React.createElement(Docs), document.getElementById('root') )
src/svg-icons/av/shuffle.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvShuffle = (props) => ( <SvgIcon {...props}> <path d="M10.59 9.17L5.41 4 4 5.41l5.17 5.17 1.42-1.41zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4h-5.5zm.33 9.41l-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04-3.13-3.13z"/> </SvgIcon> ); AvShuffle = pure(AvShuffle); AvShuffle.displayName = 'AvShuffle'; AvShuffle.muiName = 'SvgIcon'; export default AvShuffle;
test/NavbarSpec.js
andrew-d/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Navbar from '../src/Navbar'; import Nav from '../src/Nav'; describe('Nav', function () { it('Should create nav element', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar /> ); let nav = React.findDOMNode(instance); assert.equal(nav.nodeName, 'NAV'); assert.ok(nav.className.match(/\bnavbar\b/)); assert.ok(nav.getAttribute('role'), 'navigation'); }); it('Should add fixedTop variation class', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar fixedTop /> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-fixed-top')); }); it('Should add fixedBottom variation class', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar fixedBottom /> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-fixed-bottom')); }); it('Should add staticTop variation class', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar staticTop /> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-static-top')); }); it('Should add inverse variation class', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar inverse /> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-inverse')); }); it('Should add fluid variation class', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar fluid /> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'container-fluid')); }); it('Should override role attribute', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar role="banner"/> ); assert.ok(React.findDOMNode(instance).getAttribute('role'), 'banner'); }); it('Should override node class', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar componentClass={'header'}/> ); assert.equal(React.findDOMNode(instance).nodeName, 'HEADER'); }); it('Should add header with brand', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar brand="Brand" /> ); let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header'); assert.ok(header); let brand = ReactTestUtils.findRenderedDOMComponentWithClass(header, 'navbar-brand'); assert.ok(brand); assert.equal(React.findDOMNode(brand).innerText, 'Brand'); }); it('Should add header with brand component', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar brand={<a>Brand</a>} /> ); let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header'); assert.ok(header); let brand = ReactTestUtils.findRenderedDOMComponentWithClass(header, 'navbar-brand'); assert.ok(brand); assert.equal(React.findDOMNode(brand).nodeName, 'A'); assert.equal(React.findDOMNode(brand).innerText, 'Brand'); }); it('Should pass navbar prop to navs', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar brand="Brand"> <Nav /> </Navbar> ); let nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav); assert.ok(nav.props.navbar); }); it('Should pass nav prop to ul', function () { let instance = ReactTestUtils.renderIntoDocument( <Nav /> ); let navNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'nav')); assert.ok(navNode); assert.equal(navNode.nodeName, 'UL'); assert.equal(navNode.parentNode.nodeName, 'NAV'); instance.setProps({navbar: true}); navNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'nav')); assert.ok(navNode); assert.equal(navNode.nodeName, 'UL'); assert.equal(navNode.parentNode.nodeName, 'DIV'); }); it('Should add header when toggleNavKey is 0', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar toggleNavKey={0}> <Nav eventKey={0} /> </Navbar> ); let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header'); assert.ok(header); }); it('Should add header when toggleNavKey is 1', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar toggleNavKey={1}> <Nav eventKey={1} /> </Navbar> ); let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header'); assert.ok(header); }); it('Should add header when toggleNavKey is string', function () { let instance = ReactTestUtils.renderIntoDocument( <Navbar toggleNavKey={'string'}> <Nav eventKey={'string'} /> </Navbar> ); let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header'); assert.ok(header); }); });
src/components/GameListItemComponent.js
noraeb/tictactoe
import React from 'react'; const containerStyle = { fontFamily: "Roboto" } class GameListItemComponent extends React.Component { selectGame() { this.props.onClick(this.props.game); } render() { return ( <li style={containerStyle} onClick={this.selectGame.bind(this)}>Game by {this.props.game.playerOne}</li> ); } } export default GameListItemComponent;
src/index.js
raghu666/Reactapp
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import ReduxPromise from 'redux-promise'; import App from './components/app'; import reducers from './reducers'; import { BrowserRouter } from 'react-router-dom'; const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <BrowserRouter> <App /> </BrowserRouter> </Provider> , document.querySelector('.container'));
docs/app/Examples/collections/Grid/ResponsiveVariations/GridExampleReversedComputer.js
vageeshb/Semantic-UI-React
import React from 'react' import { Grid } from 'semantic-ui-react' const GridExampleReversedComputer = () => ( <Grid reversed='computer' columns='equal'> <Grid.Row> <Grid.Column>Computer A Fourth</Grid.Column> <Grid.Column>Computer A Third</Grid.Column> <Grid.Column>Computer A Second</Grid.Column> <Grid.Column>Computer A First</Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column>Computer B Fourth</Grid.Column> <Grid.Column>Computer B Third</Grid.Column> <Grid.Column>Computer B Second</Grid.Column> <Grid.Column>Computer B First</Grid.Column> </Grid.Row> </Grid> ) export default GridExampleReversedComputer
react/components-test/src/App.js
MarioCodes/Desarrollo_Proyectos_Clase
import React, { Component } from 'react'; import './App.css'; import HelloWorld from './component/HelloWorld' class App extends Component { render() { return ( <div className="App"> <HelloWorld/> </div> ); } } export default App;
src/app.js
dahtuska/tekstiilit
import React from 'react'; import ReactDOM from 'react-dom'; import {Router, useRouterHistory} from 'react-router'; import injectTapEventPlugin from 'react-tap-event-plugin'; import {createHashHistory} from 'history'; import AppRoutes from './AppRoutes'; // Helpers for debugging window.React = React; window.Perf = require('react-addons-perf'); // Needed for onTouchTap // Can go away when react 1.0 release // Check this repo: // https://github.com/zilverline/react-tap-event-plugin injectTapEventPlugin(); /** * Render the main app component. You can read more about the react-router here: * https://github.com/rackt/react-router/blob/master/docs/guides/overview.md */ ReactDOM.render( <Router history={useRouterHistory(createHashHistory)({queryKey: false})} onUpdate={() => window.scrollTo(0, 0)} > {AppRoutes} </Router>, document.getElementById('app'));
src/router.js
Arinono/uReflect_POC_Electron01
import React from 'react'; import { Router, Route, browserHistory, IndexRoute } from 'react-router'; // Pages import App from './containers/App'; var routes = ( <Route path="/" component={App}> </Route> ); export default routes;
src/js/components/icons/base/BrandGrommetPath.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-brand-grommet-path`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'brand-grommet-path'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 48 48" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#865CD6" strokeWidth="5" d="M24,42 C33.9411255,42 42,33.9411255 42,24 C42,14.0588745 33.9411255,6 24,6 C14.0588745,6 6,14.0588745 6,24 C6,33.9411255 14.0588745,42 24,42 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'BrandGrommetPath'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
app/src/containers/Services/SectionOne/ServicesSectionOne.js
RyanCCollins/ryancollins.io
import React from 'react'; import './ServicesSectionOne.scss'; import { Column, Row, Button } from 'react-foundation'; import { Divider } from '../../../components'; const paragraph1P1 = `Through the `; const paragraph1P2 = ` platform, we have proven that working collaboratively on meaningful open sources projects together is an incredible way to improve skills.`; const paragraph2 = `If you are interested in working with us on a meaningful project with a social impact, we can pair you with a mentor who will work with you to get you up to speed with React and the rest of our stack.`; const paragraph3 = `You'll get an oppurtunity to work with a real-life distributed agile team, working towards a common goal of social good.`; const ServicesSectionOne = () => ( <section className="services-section-one"> <div className="section-title">Mentoring</div> <Divider /> <Row> <Column large={8} medium={10} small={12} isColumn centerOnSmall className="services--paragraph-wrapper" > <p>{paragraph1P1}<a href="https://hacksmiths.io">Hacksmiths.io</a> {paragraph1P2}</p> <p>{paragraph2}</p> <p>{paragraph3}</p> </Column> <Column large={8} medium={10} small={12} isColumn centerOnSmall className="services__button-wrapper" > <Button size={'large'} className="button__contact"> <a href="mailto:admin@ryancollins.io">Contact Me</a> </Button> </Column> </Row> </section> ); export default ServicesSectionOne;
web/src/routes.js
doeg/plantly-graphql
import makeRouteConfig from 'found/lib/makeRouteConfig' import Route from 'found/lib/Route' import React from 'react' import AllSpeciesPage from './components/AllSpeciesPage' import App from './components/App' import AuthCallback from './components/AuthCallback' import AuthRenewCallback from './components/AuthRenewCallback' import Home from './components/Home' import PlantPage from './components/PlantPage' import Root from './components/Root' export default makeRouteConfig( <Route Component={Root} path="/"> <Route Component={AuthCallback} path="/auth/callback" /> <Route Component={AuthRenewCallback} path="/auth/renew" /> <Route Component={App}> <Route Component={Home} /> <Route Component={PlantPage} path="/plant/:plantId/:view?" /> <Route Component={AllSpeciesPage} path="/species" /> </Route> </Route> )
src/TimePicker/TimePicker.spec.js
owencm/material-ui
/* eslint-env mocha */ import React from 'react'; import {shallow} from 'enzyme'; import {assert} from 'chai'; import TimePicker from './TimePicker'; import {addHours, formatTime} from './timeUtils'; import getMuiTheme from '../styles/getMuiTheme'; import TextField from '../TextField'; describe('<TimePicker />', () => { const muiTheme = getMuiTheme(); const shallowWithContext = (node) => shallow(node, {context: {muiTheme}}); it('has to give value prop precedence over defaultTime', () => { const initialTime = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT const valueTime = addHours(initialTime, 2); const wrapper = shallowWithContext( <TimePicker value={valueTime} format="ampm" locale="en-US" initialTime={initialTime} /> ); assert.strictEqual(wrapper.find(TextField).props().value, formatTime(valueTime)); }); it('takes defaulTime prop to set first value when value prop is missing', () => { const initialTime = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT const wrapper = shallowWithContext( <TimePicker format="ampm" locale="en-US" defaultTime={initialTime} /> ); assert.strictEqual(wrapper.find(TextField).props().value, formatTime(initialTime)); }); it('shows value prop if defaultTime is missing', () => { const initialTime = null; const valueTime = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GM const wrapper = shallowWithContext( <TimePicker value={valueTime} format="ampm" locale="en-US" defaultTime={initialTime} /> ); assert.strictEqual(wrapper.find(TextField).props().value, formatTime(valueTime)); }); });