path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/components/react-native-calendars/src/calendar/header/index.js
airingursb/two-life
import React, { Component } from 'react'; import { ActivityIndicator } from 'react-native'; import { View, Text, TouchableOpacity, Image } from 'react-native'; import XDate from 'xdate'; import PropTypes from 'prop-types'; import styleConstructor from './style'; import { weekDayNames } from '../../dateutils'; class CalendarHeader extends Component { static propTypes = { theme: PropTypes.object, hideArrows: PropTypes.bool, month: PropTypes.instanceOf(XDate), addMonth: PropTypes.func, showIndicator: PropTypes.bool, firstDay: PropTypes.number, renderArrow: PropTypes.func, hideDayNames: PropTypes.bool, weekNumbers: PropTypes.bool, onPressArrowLeft: PropTypes.func, onPressArrowRight: PropTypes.func }; constructor(props) { super(props); this.style = styleConstructor(props.theme); this.addMonth = this.addMonth.bind(this); this.substractMonth = this.substractMonth.bind(this); this.onPressLeft = this.onPressLeft.bind(this); this.onPressRight = this.onPressRight.bind(this); } addMonth() { this.props.addMonth(1); } substractMonth() { this.props.addMonth(-1); } shouldComponentUpdate(nextProps) { if ( nextProps.month.toString('yyyy MM') !== this.props.month.toString('yyyy MM') ) { return true; } if (nextProps.showIndicator !== this.props.showIndicator) { return true; } if (nextProps.hideDayNames !== this.props.hideDayNames) { return true; } return false; } onPressLeft() { const {onPressArrowLeft} = this.props; if(typeof onPressArrowLeft === 'function') { return onPressArrowLeft(this.substractMonth); } return this.substractMonth(); } onPressRight() { console.log('??') const {onPressArrowRight} = this.props; if(typeof onPressArrowRight === 'function') { return onPressArrowRight(this.addMonth); } return this.addMonth(); } render() { let leftArrow = <View />; let rightArrow = <View />; let weekDaysNames = weekDayNames(this.props.firstDay); if (!this.props.hideArrows) { leftArrow = ( <TouchableOpacity onPress={this.onPressLeft} style={this.style.arrow} hitSlop={{left: 20, right: 20, top: 20, bottom: 20}} > {this.props.renderArrow ? this.props.renderArrow('left') : <Image source={require('../img/previous.png')} style={this.style.arrowImage} />} </TouchableOpacity> ); rightArrow = ( <TouchableOpacity onPress={this.onPressRight} style={this.style.arrow} hitSlop={{left: 20, right: 20, top: 20, bottom: 20}} > {this.props.renderArrow ? this.props.renderArrow('right') : <Image source={require('../img/next.png')} style={this.style.arrowImage} />} </TouchableOpacity> ); } let indicator; if (this.props.showIndicator) { indicator = <ActivityIndicator />; } return ( <View> {/* <View style={this.style.header}> {leftArrow} <View style={{ flexDirection: 'row' }}> <Text allowFontScaling={false} style={this.style.monthText} accessibilityTraits='header'> {this.props.month.toString(this.props.monthFormat ? this.props.monthFormat : 'MMMM yyyy')} </Text> {indicator} </View> {rightArrow} </View> */} { !this.props.hideDayNames && <View style={this.style.week}> {this.props.weekNumbers && <Text allowFontScaling={false} style={this.style.dayHeader}></Text>} {weekDaysNames.map((day, idx) => ( <Text allowFontScaling={false} key={idx} accessible={false} style={this.style.dayHeader} numberOfLines={1} importantForAccessibility='no'>{day}</Text> ))} </View> } </View> ); } } export default CalendarHeader;
app/react-icons/fa/street-view.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaStreetView extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m35.9 34.3q0 1.4-1.3 2.5t-3.7 1.8-5 1.1-5.7 0.3-5.6-0.3-5.1-1.1-3.6-1.8-1.4-2.5q0-1.1 0.7-2t2.1-1.5 2.6-1 2.9-0.6q0.6-0.1 1.1 0.2t0.6 0.9q0.1 0.6-0.3 1.1t-0.9 0.6q-1.3 0.2-2.3 0.5t-1.8 0.6-1 0.5-0.7 0.4-0.1 0.3q0 0.3 0.6 0.6t1.6 0.7 2.5 0.8 3.6 0.5 4.5 0.2 4.5-0.2 3.6-0.5 2.5-0.8 1.7-0.7 0.6-0.6q0-0.1-0.2-0.3t-0.6-0.4-1.1-0.5-1.7-0.6-2.4-0.5q-0.6-0.1-0.9-0.6t-0.2-1.1q0-0.5 0.5-0.9t1.1-0.2q1.6 0.2 2.9 0.6t2.7 1 2 1.5 0.7 2z m-8.5-20v8.6q0 0.5-0.5 1t-1 0.4h-1.4v8.6q0 0.5-0.4 1t-1 0.4h-5.7q-0.6 0-1-0.4t-0.5-1v-8.6h-1.4q-0.6 0-1-0.4t-0.4-1v-8.6q0-1.2 0.8-2t2-0.9h8.6q1.2 0 2 0.9t0.9 2z m-2.2-8.6q0 2.1-1.4 3.6t-3.6 1.4-3.5-1.4-1.5-3.6 1.5-3.5 3.5-1.5 3.6 1.5 1.4 3.5z"/></g> </IconBase> ); } }
docs/src/@primer/gatsby-theme-doctocat/components/live-preview-wrapper.js
primer/primer-css
import primerStyles from '!!raw-loader!postcss-loader!../../../../../src/docs.scss' import {Flex} from '@primer/components' import {Frame} from '@primer/gatsby-theme-doctocat' import {MoonIcon, SunIcon} from '@primer/octicons-react' import React from 'react' function LivePreviewWrapper({children}) { const [colorMode, setColorModeState] = React.useState('light') const setColorMode = mode => { window.dispatchEvent(new CustomEvent('color-mode-change', {detail: {mode}})) } React.useEffect(() => { const callback = e => setColorModeState(e.detail.mode) window.addEventListener('color-mode-change', callback) return () => { window.removeEventListener('color-mode-change', callback) } }, [setColorModeState]) return ( <Frame> <link rel="stylesheet" href="https://github.com/site/assets/styleguide.css" /> <style>{primerStyles}</style> <div data-color-mode={colorMode} data-light-theme="light" data-dark-theme="dark"> <Flex pt={2} px={2} justifyContent="flex-end"> <button className="btn" aria-label={colorMode === 'light' ? 'Activate dark mode' : 'Activate light mode'} onClick={() => setColorMode(colorMode === 'light' ? 'dark' : 'light')} > {colorMode === 'light' ? <MoonIcon /> : <SunIcon />} </button> </Flex> <div className="frame-example p-3">{children}</div> </div> </Frame> ) } export default LivePreviewWrapper
js/components/Player/Player.js
remypar5/mtg-lifecounter
import React from 'react'; import PropTypes from 'prop-types'; import { View } from 'react-native'; import styles from './styles'; import NumberSpinner from '../NumberSpinner'; import Text from '../Text'; import { flattenStyles } from '../../utils'; import { PlayerPropType } from '../../types'; export default class Player extends React.Component { constructor(props) { super(props); this.state = { life: props.player.life, gameOver: props.player.life <= 0, }; this.onLifeChange = this.onLifeChange.bind(this); } onLifeChange(life) { const gameOver = life <= 0; this.setState({ gameOver, }); this.props.onGameOver(gameOver); } render() { const { size, player } = this.props; const { color, name } = player; const { gameOver, life } = this.state; const { tile, playerName, playerNameSmall, playerNameLarge, gameOver: gameOverStyle, } = styles; const playerNameSizeStyle = size === 'small' ? playerNameSmall : playerNameLarge; const containerStyle = flattenStyles(tile, gameOver ? gameOverStyle : null); const textStyles = flattenStyles(playerName, playerNameSizeStyle, { color }); return ( <View style={containerStyle}> <NumberSpinner value={life} step={1} stepLarge={10} size={size} onChange={this.onLifeChange} /> <Text type="label" style={textStyles} > {name} </Text> </View> ); } } Player.propTypes = { player: PlayerPropType.isRequired, size: PropTypes.oneOf(['small', 'large']).isRequired, onGameOver: PropTypes.func, }; Player.defaultProps = { onGameOver: () => {}, };
imports/client/ui/pages/Home/FirstSection/index.js
mordka/fl-events
import React from 'react' import { Meteor } from 'meteor/meteor' import { withTracker } from 'meteor/react-meteor-data' import { Container } from 'reactstrap' import Find from './Find' import i18n from '/imports/both/i18n/en' import './styles.scss' const { Home } = i18n let color let titleColor = {color: color} const FirstSection = ({ user }) => ( <section id='first-section'> <Container> <div className='first-title' style={ (window.__mapType === 'gatherings') ? titleColor = {color: 'rgba(0,0,0,.75)'} : titleColor = {color: '#ffffff'}} >{Home.first_title}</div> <Find user={user} /> </Container> </section> ) export default withTracker(() => { return { user: Meteor.user() } })(FirstSection)
src/containers/DevTools/DevTools.js
golgistudio/website
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-H" changePositionKey="ctrl-Q"> <LogMonitor /> </DockMonitor> );
lib/containers/hyper.js
KunalKene1797/hyper
/* eslint-disable react/no-danger */ import React from 'react'; import Mousetrap from 'mousetrap'; import {PureComponent} from '../base-components'; import {connect} from '../utils/plugins'; import * as uiActions from '../actions/ui'; import {getRegisteredKeys, getCommandHandler, shouldPreventDefault} from '../command-registry'; import HeaderContainer from './header'; import TermsContainer from './terms'; import NotificationsContainer from './notifications'; const isMac = /Mac/.test(navigator.userAgent); class Hyper extends PureComponent { constructor(props) { super(props); this.handleFocusActive = this.handleFocusActive.bind(this); this.onTermsRef = this.onTermsRef.bind(this); this.mousetrap = null; } componentWillReceiveProps(next) { if (this.props.backgroundColor !== next.backgroundColor) { // this can be removed when `setBackgroundColor` in electron // starts working again document.body.style.backgroundColor = next.backgroundColor; } } handleFocusActive() { const term = this.terms.getActiveTerm(); if (term) { term.focus(); } } attachKeyListeners() { if (!this.mousetrap) { this.mousetrap = new Mousetrap(window, true); this.mousetrap.stopCallback = () => { // All events should be intercepted even if focus is in an input/textarea return false; }; } else { this.mousetrap.reset(); } const keys = getRegisteredKeys(); Object.keys(keys).forEach(commandKeys => { this.mousetrap.bind( commandKeys, e => { const command = keys[commandKeys]; // We should tell to xterm that it should ignore this event. e.catched = true; this.props.execCommand(command, getCommandHandler(command), e); shouldPreventDefault(command) && e.preventDefault(); }, 'keydown' ); }); } componentDidMount() { this.attachKeyListeners(); } onTermsRef(terms) { this.terms = terms; } componentDidUpdate(prev) { if (prev.activeSession !== this.props.activeSession) { this.handleFocusActive(); } } componentWillUnmount() { document.body.style.backgroundColor = 'inherit'; } template(css) { const {isMac: isMac_, customCSS, uiFontFamily, borderColor, maximized} = this.props; const borderWidth = isMac_ ? '' : `${maximized ? '0' : '1'}px`; return ( <div> <div style={{fontFamily: uiFontFamily, borderColor, borderWidth}} className={css('main', isMac_ && 'mainRounded')} > <HeaderContainer /> <TermsContainer ref_={this.onTermsRef} /> {this.props.customInnerChildren} </div> <NotificationsContainer /> <style dangerouslySetInnerHTML={{__html: customCSS}} /> {this.props.customChildren} </div> ); } styles() { return { main: { position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, // can be overridden by inline style above border: '1px solid #333' }, mainRounded: { borderRadius: '5px' } }; } } const HyperContainer = connect( state => { return { isMac, customCSS: state.ui.css, uiFontFamily: state.ui.uiFontFamily, borderColor: state.ui.borderColor, activeSession: state.sessions.activeUid, backgroundColor: state.ui.backgroundColor, maximized: state.ui.maximized }; }, dispatch => { return { execCommand: (command, fn, e) => { dispatch(uiActions.execCommand(command, fn, e)); } }; }, null, {withRef: true} )(Hyper, 'Hyper'); export default HyperContainer;
src/svg-icons/action/account-circle.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAccountCircle = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"/> </SvgIcon> ); ActionAccountCircle = pure(ActionAccountCircle); ActionAccountCircle.displayName = 'ActionAccountCircle'; ActionAccountCircle.muiName = 'SvgIcon'; export default ActionAccountCircle;
ui/src/stories/MapView.stories.js
damianmoore/photo-manager
import React from 'react' import MapView from '../components/MapView' export default { title: 'Photonix/Photo List/Map', component: MapView, } const Template = (args) => ( <div style={{ position: 'absolute', top: 0, left: 0, width: '100%' }}> <MapView {...args} /> </div> ) export const DefaultMap = Template.bind({}) DefaultMap.args = { location: [64.039132, -16.173093], }
generators/app/templates/src/components/Search/Search.js
chenkaixia/generator-zcy-front-starter-kit
import React from 'react'; import { Form, Row, Col, Input, Button, Icon } from 'antd'; const FormItem = Form.Item; class AdvancedSearchForm extends React.Component { state = { expand: false, }; handleSearch = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { console.log('Received values of form: ', values); if(this.props.search){ this.props.search(values); } }); } handleReset = () => { this.props.form.resetFields(); this.props.reset() } toggle = () => { const { expand } = this.state; this.setState({ expand: !expand }); } render() { const { getFieldDecorator} = this.props.form; const formItemLayout = { labelCol: { span: 5 }, wrapperCol: { span: 19 }, }; // To generate mock Form.Item const children = []; for (let i = 0; i < 10; i++) { children.push( <Col span={8} key={i}> <FormItem {...formItemLayout} label={`Field ${i}`}> {getFieldDecorator(`field-${i}`)( <Input placeholder="placeholder" /> )} </FormItem> </Col> ); } const expand = this.state.expand; const shownCount = expand ? children.length : 6; return ( <Form className="ant-advanced-search-form" id="components-form-demo-advanced-search" onSubmit={this.handleSearch} > <Row gutter={40}> {children.slice(0, shownCount)} </Row> <Row> <Col span={24} style={{ textAlign: 'right' }}> <Button type="primary" htmlType="submit">Search</Button> <Button style={{ marginLeft: 8 }} onClick={this.handleReset}> Clear </Button> <a style={{ marginLeft: 8, fontSize: 12 }} onClick={this.toggle}> Collapse <Icon type={expand ? 'up' : 'down'} /> </a> </Col> </Row> </Form> ); } } const WrappedAdvancedSearchForm = Form.create()(AdvancedSearchForm); export default WrappedAdvancedSearchForm
pages/sass.js
karolklp/slonecznikowe2
import React from 'react' import './example.scss' import Helmet from 'react-helmet' import { config } from 'config' export default class Sass extends React.Component { render () { return ( <div> <Helmet title={`${config.siteTitle} | Hi sassy friends`} /> <h1 className="the-sass-class" > Hi sassy friends </h1> <div className="sass-nav-example"> <h2>Nav example</h2> <ul> <li> <a href="#">Store</a> </li> <li> <a href="#">Help</a> </li> <li> <a href="#">Logout</a> </li> </ul> </div> </div> ) } }
test/integration/scss-fixtures/multi-global/pages/_app.js
JeromeFitz/next.js
import React from 'react' import App from 'next/app' import '../styles/global1.scss' import '../styles/global2.scss' class MyApp extends App { render() { const { Component, pageProps } = this.props return <Component {...pageProps} /> } } export default MyApp
stories/decorator/invert.js
all3dp/printing-engine-client
import React from 'react' export default story => ( <div className="u-invert" style={{width: '100%', minHeight: '100vh'}}> {story()} </div> )
src/svg-icons/action/pets.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPets = (props) => ( <SvgIcon {...props}> <circle cx="4.5" cy="9.5" r="2.5"/><circle cx="9" cy="5.5" r="2.5"/><circle cx="15" cy="5.5" r="2.5"/><circle cx="19.5" cy="9.5" r="2.5"/><path d="M17.34 14.86c-.87-1.02-1.6-1.89-2.48-2.91-.46-.54-1.05-1.08-1.75-1.32-.11-.04-.22-.07-.33-.09-.25-.04-.52-.04-.78-.04s-.53 0-.79.05c-.11.02-.22.05-.33.09-.7.24-1.28.78-1.75 1.32-.87 1.02-1.6 1.89-2.48 2.91-1.31 1.31-2.92 2.76-2.62 4.79.29 1.02 1.02 2.03 2.33 2.32.73.15 3.06-.44 5.54-.44h.18c2.48 0 4.81.58 5.54.44 1.31-.29 2.04-1.31 2.33-2.32.31-2.04-1.3-3.49-2.61-4.8z"/> </SvgIcon> ); ActionPets = pure(ActionPets); ActionPets.displayName = 'ActionPets'; ActionPets.muiName = 'SvgIcon'; export default ActionPets;
app/javascript/mastodon/features/ui/components/navigation_panel.js
koba-lab/mastodon
import React from 'react'; import { NavLink, withRouter } from 'react-router-dom'; import { FormattedMessage } from 'react-intl'; import Icon from 'mastodon/components/icon'; import { showTrends } from 'mastodon/initial_state'; import NotificationsCounterIcon from './notifications_counter_icon'; import FollowRequestsNavLink from './follow_requests_nav_link'; import ListPanel from './list_panel'; import TrendsContainer from 'mastodon/features/getting_started/containers/trends_container'; const NavigationPanel = () => ( <div className='navigation-panel'> <NavLink className='column-link column-link--transparent' to='/home' data-preview-title-id='column.home' data-preview-icon='home' ><Icon className='column-link__icon' id='home' fixedWidth /><FormattedMessage id='tabs_bar.home' defaultMessage='Home' /></NavLink> <NavLink className='column-link column-link--transparent' to='/notifications' data-preview-title-id='column.notifications' data-preview-icon='bell' ><NotificationsCounterIcon className='column-link__icon' /><FormattedMessage id='tabs_bar.notifications' defaultMessage='Notifications' /></NavLink> <FollowRequestsNavLink /> <NavLink className='column-link column-link--transparent' to='/explore' data-preview-title-id='explore.title' data-preview-icon='hashtag'><Icon className='column-link__icon' id='hashtag' fixedWidth /><FormattedMessage id='explore.title' defaultMessage='Explore' /></NavLink> <NavLink className='column-link column-link--transparent' to='/public/local' data-preview-title-id='column.community' data-preview-icon='users' ><Icon className='column-link__icon' id='users' fixedWidth /><FormattedMessage id='tabs_bar.local_timeline' defaultMessage='Local' /></NavLink> <NavLink className='column-link column-link--transparent' exact to='/public' data-preview-title-id='column.public' data-preview-icon='globe' ><Icon className='column-link__icon' id='globe' fixedWidth /><FormattedMessage id='tabs_bar.federated_timeline' defaultMessage='Federated' /></NavLink> <NavLink className='column-link column-link--transparent' to='/conversations'><Icon className='column-link__icon' id='envelope' fixedWidth /><FormattedMessage id='navigation_bar.direct' defaultMessage='Direct messages' /></NavLink> <NavLink className='column-link column-link--transparent' to='/favourites'><Icon className='column-link__icon' id='star' fixedWidth /><FormattedMessage id='navigation_bar.favourites' defaultMessage='Favourites' /></NavLink> <NavLink className='column-link column-link--transparent' to='/bookmarks'><Icon className='column-link__icon' id='bookmark' fixedWidth /><FormattedMessage id='navigation_bar.bookmarks' defaultMessage='Bookmarks' /></NavLink> <NavLink className='column-link column-link--transparent' to='/lists'><Icon className='column-link__icon' id='list-ul' fixedWidth /><FormattedMessage id='navigation_bar.lists' defaultMessage='Lists' /></NavLink> <ListPanel /> <hr /> <a className='column-link column-link--transparent' href='/settings/preferences'><Icon className='column-link__icon' id='cog' fixedWidth /><FormattedMessage id='navigation_bar.preferences' defaultMessage='Preferences' /></a> <a className='column-link column-link--transparent' href='/relationships'><Icon className='column-link__icon' id='users' fixedWidth /><FormattedMessage id='navigation_bar.follows_and_followers' defaultMessage='Follows and followers' /></a> {showTrends && <div className='flex-spacer' />} {showTrends && <TrendsContainer />} </div> ); export default withRouter(NavigationPanel);
examples/parent.js
threepointone/glamor
import React from 'react' import { css, parent } from 'glamor' const styles = { root: css({ backgroundColor: '#fff', ':hover': { backgroundColor: '#000' } }), child: css( { color: '#000' }, parent(':hover >', { color: '#fff' }) ) } export function App() { return ( <div {...styles.root}> <div {...styles.child}>Hover me</div> </div> ) }
src/widgets/FormInputs/FormDateInput.js
sussol/mobile
/* eslint-disable react/forbid-prop-types */ /** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import React from 'react'; import { StyleSheet, TextInput } from 'react-native'; import moment from 'moment'; import DateTimePicker from '@react-native-community/datetimepicker'; import PropTypes from 'prop-types'; import { FlexColumn } from '../FlexColumn'; import { FlexRow } from '../FlexRow'; import { APP_FONT_FAMILY, SUSSOL_ORANGE, DARKER_GREY } from '../../globalStyles'; import { CalendarIcon } from '../icons'; import { CircleButton } from '../CircleButton'; import { FormLabel } from './FormLabel'; import { FormInvalidMessage } from './FormInvalidMessage'; import { DATE_FORMAT } from '../../utilities/constants'; /** * Form input for entering dates. Renders a TextInput as well as a button, opening a * native Date picker. * * @prop {Date} value A date or moment - The initial date. * @prop {Bool} isRequired Indicator whether this date is required. * @prop {Bool} isDisabled Indicator whether this input is disabled. * @prop {Func} onValidate Callback to validate the input. * @prop {Func} onChangeDate Callback for date changes[called only with a valid date]. * @prop {Func} onSubmit Callback after submitting a date from text. * @prop {String} label Label for the input * @prop {String} placeholder Placeholder text for the text input. * @prop {String} placeholderTextColor Color of the placeholder text. * @prop {String} underlineColorAndroid Underline color of the text input. * @prop {String} invalidMessage Message to the user when the current input is invalid. * @prop {Object} textInputStyle Style object to override the underlying text input. */ export const FormDateInput = React.forwardRef( ( { value, isRequired, onValidate, onChangeDate, label, invalidMessage, textInputStyle, placeholder, placeholderTextColor, underlineColorAndroid, onSubmit, isDisabled, autoFocus, }, ref ) => { let initialValue = moment(value); if (onValidate(value)) { initialValue = moment(value); } else if (typeof value === 'number' && onValidate(value)) { initialValue = moment(new Date(), DATE_FORMAT.DD_MM_YYYY); } const [inputState, setInputState] = React.useState({ isValid: true, inputValue: initialValue.isValid() ? moment(initialValue).format(DATE_FORMAT.DD_MM_YYYY) : '', pickerSeedValue: initialValue.isValid() ? initialValue.toDate() : new Date(), datePickerOpen: false, }); const { inputValue, isValid, pickerSeedValue, datePickerOpen } = inputState; const onUpdate = (newValue, validity = true, pickerVisibility = false) => { const newDate = moment(newValue, DATE_FORMAT.DD_MM_YYYY); const newValidity = onValidate(newValue); const updatedIsValid = validity && newValidity; const updatedDate = newValue && updatedIsValid ? newDate.toDate() : null; // if invalid, return the raw value to allow the caller to validate correctly const returnValue = updatedDate || newValue; const updatedState = { isValid: updatedIsValid, inputValue: newValue, datePickerOpen: pickerVisibility, pickerSeedValue: updatedDate, }; setInputState(updatedState); onChangeDate(returnValue); }; // When changing the value of the input, check the new validity and set the new input. // Do not restrict input, but provide feedback to the user. const onChangeTextCallback = React.useCallback( newValue => { const newValueIsValid = onValidate ? onValidate(newValue) : true; onUpdate(newValue, newValueIsValid); }, [onValidate] ); const onChangeDates = ({ nativeEvent }) => { const { timestamp } = nativeEvent; if (!timestamp) { setInputState(state => ({ ...state, datePickerOpen: false })); } else { const newDate = moment(new Date(timestamp)).format(DATE_FORMAT.DD_MM_YYYY); onUpdate(newDate, true); } }; const openDatePicker = () => setInputState(state => ({ ...state, datePickerOpen: true })); const onSubmitEditing = React.useCallback( event => { /* eslint-disable no-unused-expressions */ onSubmit?.(event.nativeEvent.text); onUpdate?.(event.nativeEvent.text); }, [onUpdate, onSubmit] ); return ( <FlexRow flex={1}> <FlexColumn flex={1}> <FormLabel value={label} isRequired={isRequired} /> <FlexRow flex={1}> <TextInput ref={ref} style={textInputStyle} value={inputValue} placeholderTextColor={placeholderTextColor} underlineColorAndroid={underlineColorAndroid} placeholder={placeholder} selectTextOnFocus returnKeyType="next" autoCapitalize="none" autoCorrect={false} onChangeText={onChangeTextCallback} onSubmitEditing={onSubmitEditing} editable={!isDisabled} autoFocus={autoFocus} /> <CircleButton IconComponent={CalendarIcon} onPress={openDatePicker} isDisabled={isDisabled} /> </FlexRow> {!!datePickerOpen && ( <DateTimePicker onChange={onChangeDates} mode="date" display="spinner" value={pickerSeedValue ?? new Date()} maximumDate={new Date()} /> )} <FormInvalidMessage isValid={isValid} message={invalidMessage} /> </FlexColumn> </FlexRow> ); } ); const localStyles = StyleSheet.create({ labelStyle: { marginTop: 15, fontSize: 16, fontFamily: APP_FONT_FAMILY }, isRequiredStyle: { fontSize: 12, color: SUSSOL_ORANGE, fontFamily: APP_FONT_FAMILY }, textInputStyle: { flex: 1, fontFamily: APP_FONT_FAMILY }, }); FormDateInput.defaultProps = { placeholder: '', placeholderTextColor: SUSSOL_ORANGE, underlineColorAndroid: DARKER_GREY, textInputStyle: localStyles.textInputStyle, isRequired: false, onValidate: null, invalidMessage: '', onSubmit: null, isDisabled: false, autoFocus: false, }; FormDateInput.propTypes = { textInputStyle: PropTypes.object, value: PropTypes.oneOfType([PropTypes.string, PropTypes.object, PropTypes.number]).isRequired, isRequired: PropTypes.bool, onValidate: PropTypes.func, onChangeDate: PropTypes.func.isRequired, label: PropTypes.string.isRequired, invalidMessage: PropTypes.string, placeholder: PropTypes.string, placeholderTextColor: PropTypes.string, underlineColorAndroid: PropTypes.string, onSubmit: PropTypes.func, isDisabled: PropTypes.bool, autoFocus: PropTypes.bool, };
src/main/resources/public/js/pages/organization-search.js
ozwillo/ozwillo-portal
import React from 'react'; import {Link} from 'react-router-dom'; import { i18n } from "../config/i18n-config" import { t } from "@lingui/macro" import UpdateTitle from '../components/update-title'; import OrganizationAutoSuggest from "../components/autosuggests/organization-autosuggest"; import OrganizationCard from "../components/organization-card" import {Redirect} from "react-router"; import UserOrganizationHistoryService from '../util/user-organization-history-service'; class OrganizationSearch extends React.Component { constructor(props) { super(props); this.state = { userOrganizationsFilter: '', isLoading: true, inputValue: '', organizationSelected: {}, organizationsHistory: [], organizationHistoryMessage: '' }; this._userOrganizationHistory = new UserOrganizationHistoryService(); } componentDidMount() { this._handleOrganizationsHistory(); } _handleOrganizationsHistory = async () => { try { let res = await this._userOrganizationHistory.getOrganizationHistory(); if(res && res.length >0){ this._sortOrganizationHistoryByDate(res); this.setState({organizationsHistory: res, organizationHistoryMessage: ''}); } else { this.setState({organizationHistoryMessage: i18n._(t`organization.search.history.empty`)}); } }catch(err){ console.error(err); } }; _sortOrganizationHistoryByDate = (array) =>{ array.sort(function(a,b){ return new Date(b.date) - new Date(a.date); }); }; _handleOrganizationCardError = async (error, dcOrganizationId) => { try { let res = await this._userOrganizationHistory.deleteOrganizationHistoryEntry(dcOrganizationId); if(res && res.length > 0) { this.setState({organizationsHistory: res, organizationHistoryMessage: ''}) }else{ this._handleOrganizationsHistory() } }catch(err){ console.error(err); } }; _displayOrganizationsHistory = () => { const {organizationsHistory, organizationHistoryMessage} = this.state; if (organizationsHistory.length > 0) { let result = []; organizationsHistory.map(organization => { let dcOrganizationId = organization.dcOrganizationId; let organizationCard = ( <OrganizationCard key={dcOrganizationId} organization={organization} callBackError={this._handleOrganizationCardError}/>); result.push(organizationCard) }); return result; }else{ return organizationHistoryMessage; } }; render() { const {organization_id} = this.state.organizationSelected; if (organization_id) { return <Redirect to={`/my/organization/${organization_id}/`}/> } return <section className="organization-search oz-body wrapper flex-col"> <UpdateTitle title={i18n._(t`organization.search.title`)}/> <section> <header className="title"> <span>{i18n._(t`organization.search.title`)}</span> </header> <form className="search oz-form"> <OrganizationAutoSuggest className={"field"} value={this.state.inputValue} name={"orga-auto-suggest"} onChange={(event, value) => this.setState({inputValue: value})} onOrganizationSelected={(value) => { this.setState({organizationSelected: value}) }} placeholder={i18n._(t`search.organization.search-organization`)} /> </form> <div className={"organization-create-new"}> <span>{i18n._(t`organization.search.create`)}</span> <Link to="/my/organization/create" className="btn btn-submit" style={{ 'marginLeft': '1em' }}> {i18n._(t`organization.search.new`)} </Link> </div> <div className={"container-organization-history"}> <p className={"history-title"}> <i className={"fa fa-star"}/> {i18n._(t`organization.search.history.description`)} : </p> <div className={"content-card-history"}> {this._displayOrganizationsHistory()} </div> </div> </section> </section>; } } export default OrganizationSearch;
templates/rubix/laravel/laravel-example/src/components/Todo.js
jeffthemaximum/jeffline
import React from 'react'; import { withRouter } from 'react-router'; import { Col, Row, Grid, Icon, Button, Checkbox, ButtonGroup, } from '@sketchpixy/rubix'; import client from '@sketchpixy/rubix/lib/utils/HttpClient'; @withRouter export default class Todo extends React.Component { constructor(props) { super(props); let { todo } = props; this.state = { deleted: false, todo: todo.todo, completed: parseInt(todo.completed), }; } toggleCompletion() { let completed = this.input.checked ? 1 : 0; client.put(`/api/todos/${this.props.todo.id}`, { completed, }).then((result) => { this.setState({ todo: result.data.todo.todo, completed: parseInt(result.data.todo.completed), }); }); } removeTodo() { client.delete(`/api/todos/${this.props.todo.id}`) .then(() => { this.setState({ deleted: true }); }); } editTodo() { this.props.router.push(`/todos/${this.props.todo.id}`); } render() { if (this.state.deleted) return null; let { todo, completed } = this.state; let style = { textDecoration: completed ? 'line-through' : null }; return ( <Grid> <Row className='todo-item'> <Col sm={8}> <Checkbox onChange={::this.toggleCompletion} style={style} inputRef={(input) => { this.input = input; }} checked={completed} > {todo} </Checkbox> </Col> <Col sm={4} className='text-right'> <Button bsStyle='red' className='remove-sm' onClick={::this.removeTodo} style={{marginRight: 12.5}}>Remove</Button> <Button bsStyle='green' className='remove-sm' onlyOnHover onClick={::this.editTodo}>Edit</Button> </Col> </Row> </Grid> ); } }
Console/app/node_modules/rc-form/es/createBaseForm.js
RisenEsports/RisenEsports.github.io
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _extends from 'babel-runtime/helpers/extends'; import _toConsumableArray from 'babel-runtime/helpers/toConsumableArray'; import React from 'react'; import createReactClass from 'create-react-class'; import AsyncValidator from 'async-validator'; import warning from 'warning'; import get from 'lodash/get'; import has from 'lodash/has'; import set from 'lodash/set'; import createFieldsStore from './createFieldsStore'; import { argumentContainer, mirror, getValueFromEvent, hasRules, getParams, isEmptyObject, flattenArray, getNameIfNested, flatFieldNames, clearVirtualField, getVirtualPaths, normalizeValidateRules } from './utils'; var DEFAULT_TRIGGER = 'onChange'; function createBaseForm() { var option = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var mixins = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var mapPropsToFields = option.mapPropsToFields, onFieldsChange = option.onFieldsChange, onValuesChange = option.onValuesChange, fieldNameProp = option.fieldNameProp, fieldMetaProp = option.fieldMetaProp, validateMessages = option.validateMessages, _option$mapProps = option.mapProps, mapProps = _option$mapProps === undefined ? mirror : _option$mapProps, _option$formPropName = option.formPropName, formPropName = _option$formPropName === undefined ? 'form' : _option$formPropName, withRef = option.withRef; function decorate(WrappedComponent) { var Form = createReactClass({ displayName: 'Form', mixins: mixins, getInitialState: function getInitialState() { var _this = this; var fields = mapPropsToFields && mapPropsToFields(this.props); this.fieldsStore = createFieldsStore(fields || {}); this.instances = {}; this.cachedBind = {}; // HACK: https://github.com/ant-design/ant-design/issues/6406 ['getFieldsValue', 'getFieldValue', 'setFieldsInitialValue', 'getFieldsError', 'getFieldError', 'isFieldValidating', 'isFieldsValidating', 'isFieldsTouched', 'isFieldTouched'].forEach(function (key) { return _this[key] = function () { var _fieldsStore; warning(false, 'you should not use `ref` on enhanced form, please use `wrappedComponentRef`. ' + 'See: https://github.com/react-component/form#note-use-wrappedcomponentref-instead-of-withref-after-rc-form140'); return (_fieldsStore = _this.fieldsStore)[key].apply(_fieldsStore, arguments); }; }); return { submitting: false }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (mapPropsToFields) { this.fieldsStore.replaceFields(mapPropsToFields(nextProps)); } }, onCollectCommon: function onCollectCommon(name_, action, args) { var name = name_; var fieldMeta = this.fieldsStore.getFieldMeta(name); if (fieldMeta[action]) { fieldMeta[action].apply(fieldMeta, _toConsumableArray(args)); } else if (fieldMeta.originalProps && fieldMeta.originalProps[action]) { var _fieldMeta$originalPr; (_fieldMeta$originalPr = fieldMeta.originalProps)[action].apply(_fieldMeta$originalPr, _toConsumableArray(args)); } var value = fieldMeta.getValueFromEvent ? fieldMeta.getValueFromEvent.apply(fieldMeta, _toConsumableArray(args)) : getValueFromEvent.apply(undefined, _toConsumableArray(args)); if (onValuesChange && value !== this.fieldsStore.getFieldValue(name)) { onValuesChange(this.props, set({}, name, value)); } var nameKeyObj = getNameIfNested(name); if (this.fieldsStore.getFieldMeta(nameKeyObj.name).exclusive) { name = nameKeyObj.name; } var field = this.fieldsStore.getField(name); return { name: name, field: _extends({}, field, { value: value, touched: true }), fieldMeta: fieldMeta }; }, onCollect: function onCollect(name_, action) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } var _onCollectCommon = this.onCollectCommon(name_, action, args), name = _onCollectCommon.name, field = _onCollectCommon.field, fieldMeta = _onCollectCommon.fieldMeta; var validate = fieldMeta.validate; var fieldContent = _extends({}, field, { dirty: hasRules(validate) }); this.setFields(_defineProperty({}, name, fieldContent)); }, onCollectValidate: function onCollectValidate(name_, action) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } var _onCollectCommon2 = this.onCollectCommon(name_, action, args), field = _onCollectCommon2.field, fieldMeta = _onCollectCommon2.fieldMeta; var fieldContent = _extends({}, field, { dirty: true }); this.validateFieldsInternal([fieldContent], { action: action, options: { firstFields: !!fieldMeta.validateFirst } }); }, getCacheBind: function getCacheBind(name, action, fn) { var cache = this.cachedBind[name] = this.cachedBind[name] || {}; if (!cache[action]) { cache[action] = fn.bind(this, name, action); } return cache[action]; }, getFieldDecorator: function getFieldDecorator(name, fieldOption) { var _this2 = this; var props = this.getFieldProps(name, fieldOption); return function (fieldElem) { var fieldMeta = _this2.fieldsStore.getFieldMeta(name); var originalProps = fieldElem.props; if (process.env.NODE_ENV !== 'production') { var valuePropName = fieldMeta.valuePropName; warning(!(valuePropName in originalProps), '`getFieldDecorator` will override `' + valuePropName + '`, ' + ('so please don\'t set `' + valuePropName + '` directly ') + 'and use `setFieldsValue` to set it.'); var defaultValuePropName = 'default' + valuePropName[0].toUpperCase() + valuePropName.slice(1); warning(!(defaultValuePropName in originalProps), '`' + defaultValuePropName + '` is invalid ' + ('for `getFieldDecorator` will set `' + valuePropName + '`,') + ' please use `option.initialValue` instead.'); } fieldMeta.originalProps = originalProps; fieldMeta.ref = fieldElem.ref; return React.cloneElement(fieldElem, _extends({}, props, _this2.fieldsStore.getFieldValuePropValue(fieldMeta))); }; }, getFieldProps: function getFieldProps(name) { var _this3 = this; var usersFieldOption = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (!name) { throw new Error('Must call `getFieldProps` with valid name string!'); } var nameIfNested = getNameIfNested(name); var leadingName = nameIfNested.name; var fieldOption = _extends({ valuePropName: 'value', validate: [], trigger: DEFAULT_TRIGGER, leadingName: leadingName, name: name }, usersFieldOption); var rules = fieldOption.rules, trigger = fieldOption.trigger, _fieldOption$validate = fieldOption.validateTrigger, validateTrigger = _fieldOption$validate === undefined ? trigger : _fieldOption$validate, exclusive = fieldOption.exclusive, validate = fieldOption.validate; var fieldMeta = this.fieldsStore.getFieldMeta(name); if ('initialValue' in fieldOption) { fieldMeta.initialValue = fieldOption.initialValue; } var leadingFieldMeta = this.fieldsStore.getFieldMeta(leadingName); if (nameIfNested.isNested) { leadingFieldMeta.virtual = !exclusive; // exclusive allow getFieldProps('x', {initialValue}) // non-exclusive does not allow getFieldProps('x', {initialValue}) leadingFieldMeta.hidden = !exclusive; leadingFieldMeta.exclusive = exclusive; } var inputProps = _extends({}, this.fieldsStore.getFieldValuePropValue(fieldOption), { ref: this.getCacheBind(name, name + '__ref', this.saveRef) }); if (fieldNameProp) { inputProps[fieldNameProp] = name; } var validateRules = normalizeValidateRules(validate, rules, validateTrigger); var validateTriggers = validateRules.filter(function (item) { return !!item.rules && item.rules.length; }).map(function (item) { return item.trigger; }).reduce(function (pre, curr) { return pre.concat(curr); }, []); validateTriggers.forEach(function (action) { if (inputProps[action]) return; inputProps[action] = _this3.getCacheBind(name, action, _this3.onCollectValidate); }); // make sure that the value will be collect if (trigger && validateTriggers.indexOf(trigger) === -1) { inputProps[trigger] = this.getCacheBind(name, trigger, this.onCollect); } var meta = _extends({}, fieldMeta, fieldOption, { validate: validateRules }); this.fieldsStore.setFieldMeta(name, meta); if (fieldMetaProp) { inputProps[fieldMetaProp] = meta; } return inputProps; }, getFieldInstance: function getFieldInstance(name) { return this.instances[name]; }, getRules: function getRules(fieldMeta, action) { var actionRules = fieldMeta.validate.filter(function (item) { return !action || item.trigger.indexOf(action) >= 0; }).map(function (item) { return item.rules; }); return flattenArray(actionRules); }, setFields: function setFields(fields) { var _this4 = this; this.fieldsStore.setFields(fields); if (onFieldsChange) { var changedFields = {}; Object.keys(fields).forEach(function (f) { changedFields[f] = _this4.fieldsStore.getField(f); }); onFieldsChange(this.props, changedFields); } this.forceUpdate(); }, resetFields: function resetFields(ns) { var newFields = this.fieldsStore.resetFields(ns); if (Object.keys(newFields).length > 0) { this.setFields(newFields); } }, setFieldsValue: function setFieldsValue(fieldsValue) { if (onValuesChange) { onValuesChange(this.props, fieldsValue); } var newFields = {}; var _fieldsStore2 = this.fieldsStore, fieldsMeta = _fieldsStore2.fieldsMeta, fields = _fieldsStore2.fields; var virtualPaths = getVirtualPaths(fieldsMeta); Object.keys(fieldsValue).forEach(function (name) { var value = fieldsValue[name]; if (fieldsMeta[name] && fieldsMeta[name].virtual) { clearVirtualField(name, fields, fieldsMeta); for (var i = 0, len = virtualPaths[name].length; i < len; i++) { var path = virtualPaths[name][i]; if (has(fieldsValue, path)) { newFields[path] = { name: path, value: get(fieldsValue, path) }; } } } else if (fieldsMeta[name]) { newFields[name] = { name: name, value: value }; } else { warning(false, 'Cannot use `setFieldsValue` until ' + 'you use `getFieldDecorator` or `getFieldProps` to register it.'); } }); this.setFields(newFields); }, saveRef: function saveRef(name, _, component) { if (!component) { // after destroy, delete data this.fieldsStore.clearField(name); delete this.instances[name]; delete this.cachedBind[name]; return; } var fieldMeta = this.fieldsStore.getFieldMeta(name); if (fieldMeta) { var ref = fieldMeta.ref; if (ref) { if (typeof ref === 'string') { throw new Error('can not set ref string for ' + name); } ref(component); } } this.instances[name] = component; }, validateFieldsInternal: function validateFieldsInternal(fields, _ref, callback) { var _this5 = this; var fieldNames = _ref.fieldNames, action = _ref.action, _ref$options = _ref.options, options = _ref$options === undefined ? {} : _ref$options; var allRules = {}; var allValues = {}; var allFields = {}; var alreadyErrors = {}; fields.forEach(function (field) { var name = field.name; if (options.force !== true && field.dirty === false) { if (field.errors) { set(alreadyErrors, name, { errors: field.errors }); } return; } var fieldMeta = _this5.fieldsStore.getFieldMeta(name); var newField = _extends({}, field); newField.errors = undefined; newField.validating = true; newField.dirty = true; allRules[name] = _this5.getRules(fieldMeta, action); allValues[name] = newField.value; allFields[name] = newField; }); this.setFields(allFields); // in case normalize Object.keys(allValues).forEach(function (f) { allValues[f] = _this5.fieldsStore.getFieldValue(f); }); if (callback && isEmptyObject(allFields)) { callback(isEmptyObject(alreadyErrors) ? null : alreadyErrors, this.fieldsStore.getFieldsValue(flatFieldNames(fieldNames))); return; } var validator = new AsyncValidator(allRules); if (validateMessages) { validator.messages(validateMessages); } validator.validate(allValues, options, function (errors) { var errorsGroup = _extends({}, alreadyErrors); if (errors && errors.length) { errors.forEach(function (e) { var fieldName = e.field; if (!has(errorsGroup, fieldName)) { set(errorsGroup, fieldName, { errors: [] }); } var fieldErrors = get(errorsGroup, fieldName.concat('.errors')); fieldErrors.push(e); }); } var expired = []; var nowAllFields = {}; Object.keys(allRules).forEach(function (name) { var fieldErrors = get(errorsGroup, name); var nowField = _this5.fieldsStore.getField(name); // avoid concurrency problems if (nowField.value !== allValues[name]) { expired.push({ name: name }); } else { nowField.errors = fieldErrors && fieldErrors.errors; nowField.value = allValues[name]; nowField.validating = false; nowField.dirty = false; nowAllFields[name] = nowField; } }); _this5.setFields(nowAllFields); if (callback) { if (expired.length) { expired.forEach(function (_ref2) { var name = _ref2.name; var fieldErrors = [{ message: name + ' need to revalidate', field: name }]; set(errorsGroup, name, { expired: true, errors: fieldErrors }); }); } callback(isEmptyObject(errorsGroup) ? null : errorsGroup, _this5.fieldsStore.getFieldsValue(flatFieldNames(fieldNames))); } }); }, validateFields: function validateFields(ns, opt, cb) { var _this6 = this; var _getParams = getParams(ns, opt, cb), names = _getParams.names, callback = _getParams.callback, options = _getParams.options; var fieldNames = names || this.fieldsStore.getValidFieldsName(); var fields = fieldNames.filter(function (name) { var fieldMeta = _this6.fieldsStore.getFieldMeta(name); return hasRules(fieldMeta.validate); }).map(function (name) { var field = _this6.fieldsStore.getField(name); field.value = _this6.fieldsStore.getFieldValue(name); return field; }); if (!fields.length) { if (callback) { callback(null, this.fieldsStore.getFieldsValue(flatFieldNames(fieldNames))); } return; } if (!('firstFields' in options)) { options.firstFields = fieldNames.filter(function (name) { var fieldMeta = _this6.fieldsStore.getFieldMeta(name); return !!fieldMeta.validateFirst; }); } this.validateFieldsInternal(fields, { fieldNames: fieldNames, options: options }, callback); }, isSubmitting: function isSubmitting() { return this.state.submitting; }, submit: function submit(callback) { var _this7 = this; var fn = function fn() { _this7.setState({ submitting: false }); }; this.setState({ submitting: true }); callback(fn); }, render: function render() { var _props = this.props, wrappedComponentRef = _props.wrappedComponentRef, restProps = _objectWithoutProperties(_props, ['wrappedComponentRef']); var formProps = _defineProperty({}, formPropName, this.getForm()); function innerestWrappedComponentRef() { if (wrappedComponentRef && !innerestWrappedComponentRef.called) { wrappedComponentRef.apply(undefined, arguments); innerestWrappedComponentRef.called = true; } } if (withRef) { warning(false, '`withRef` is deprecated, please use `wrappedComponentRef` instead. ' + 'See: https://github.com/react-component/form#note-use-wrappedcomponentref-instead-of-withref-after-rc-form140'); formProps.ref = 'wrappedComponent'; } else if (wrappedComponentRef) { formProps.ref = innerestWrappedComponentRef; } var props = mapProps.call(this, _extends({}, formProps, restProps, { wrappedComponentRef: innerestWrappedComponentRef })); return React.createElement(WrappedComponent, props); } }); return argumentContainer(Form, WrappedComponent); } return decorate; } export default createBaseForm;
src/@ui/Icon/icons/Share.js
NewSpring/Apollos
import React from 'react'; import PropTypes from 'prop-types'; import { Svg } from '../../Svg'; import makeIcon from './makeIcon'; const Icon = makeIcon(({ size = 32, fill, ...otherProps } = {}) => ( <Svg width={size} height={size} viewBox="0 0 24 24" {...otherProps}> <Svg.Path d="M12.8 3.621v8.6568h-1.6V3.5545L8.6046 6.224c-.3037.3124-.7962.3124-1.1 0-.3037-.3124-.3037-.819 0-1.1314l3.826-3.9352c.174-.179.41-.2554.637-.2293.227-.026.463.0505.637.2295l3.826 3.9352c.3037.3125.3037.819 0 1.1314-.3038.3125-.7963.3125-1.1 0L12.8 3.621zM8.0338 8v1.5556H6.4012c-.4785 0-.8012.2822-.8012.544v9.8007c0 .2617.3228.544.7997.544h11.2006c.477 0 .7997-.2823.7997-.544v-9.8006c0-.2623-.3216-.544-.796-.544h-1.623V8h1.623C18.927 8 20 8.9403 20 10.0997v9.8006C20 21.06 18.9254 22 17.6003 22H6.3997C5.0744 22 4 21.0597 4 19.9003v-9.8006C4 8.94 5.0743 8 6.4012 8h1.6326z" fill={fill} /> </Svg> )); Icon.propTypes = { size: PropTypes.number, fill: PropTypes.string, }; export default Icon;
src/mui/form/SimpleForm.js
matteolc/admin-on-rest
import React from 'react'; import PropTypes from 'prop-types'; import { reduxForm } from 'redux-form'; import { connect } from 'react-redux'; import compose from 'recompose/compose'; import getDefaultValues from './getDefaultValues'; import FormField from './FormField'; import Toolbar from './Toolbar'; const noop = () => {}; export const SimpleForm = ({ children, handleSubmit, invalid, record, resource, basePath, submitOnEnter }) => { return ( <form onSubmit={ submitOnEnter ? handleSubmit : noop } className="simple-form"> <div style={{ padding: '0 1em 1em 1em' }}> {React.Children.map(children, input => input && ( <div key={input.props.source} className={`aor-input-${input.props.source}`} style={input.props.style}> <FormField input={input} resource={resource} record={record} basePath={basePath} /> </div> ))} </div> <Toolbar invalid={invalid} submitOnEnter={submitOnEnter} /> </form> ); }; SimpleForm.propTypes = { children: PropTypes.node, defaultValue: PropTypes.oneOfType([ PropTypes.object, PropTypes.func, ]), handleSubmit: PropTypes.func, invalid: PropTypes.bool, record: PropTypes.object, resource: PropTypes.string, basePath: PropTypes.string, validate: PropTypes.func, submitOnEnter: PropTypes.bool, }; SimpleForm.defaultProps = { submitOnEnter: true, }; const enhance = compose( connect((state, props) => ({ initialValues: getDefaultValues(state, props), })), reduxForm({ form: 'record-form', enableReinitialize: true, }), ); export default enhance(SimpleForm);
lib/shared/screens/admin/shared/components/page-builder-menu/tabs/style/style-picker/editing/index.js
relax/relax
import * as pageBuilderActions from 'actions/page-builder'; import bind from 'decorators/bind'; import forEach from 'lodash/forEach'; import getElementStyleValues from 'helpers/element/get-style-values'; import union from 'lodash/union'; import Component from 'components/component'; import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import elements from 'elements'; import Editing from './editing'; @connect( (state) => { const {display} = state; const {selectedElement, selected} = state.pageBuilder; const ElementClass = elements[selectedElement.tag]; // get element style options let styleOptions; if (typeof ElementClass.style === 'string') { // this element style setting is a reference to another style forEach(elements, (element) => { if (element.style && typeof element.style === 'object' && element.style.type === ElementClass.style) { styleOptions = element.style; } }); } else { styleOptions = ElementClass.style; } return { styleOptions, selectedElement, selected, display }; }, (dispatch) => bindActionCreators(pageBuilderActions, dispatch) ) export default class StylePickerEditingContainer extends Component { static propTypes = { selectedStyle: PropTypes.object, styleOptions: PropTypes.object.isRequired, selectedElement: PropTypes.object.isRequired, selected: PropTypes.object.isRequired, display: PropTypes.string.isRequired, changeElementStyleProp: PropTypes.func.isRequired, createStyleFromSelectedElement: PropTypes.func.isRequired, saveSelectedElementStyleChanges: PropTypes.func.isRequired }; @bind onChangeProp (property, value) { const {changeElementStyleProp, selected} = this.props; changeElementStyleProp( selected.id, property, value, selected.context ); } @bind onSave (title) { const {createStyleFromSelectedElement, selectedStyle} = this.props; if (title) { // create new style createStyleFromSelectedElement(title, selectedStyle); } } @bind onUpdate () { const { selectedStyle, saveSelectedElementStyleChanges } = this.props; // save to style saveSelectedElementStyleChanges(selectedStyle); } calcValues () { const {selectedStyle, display, selectedElement, styleOptions} = this.props; let hasChanges = false; let elementOverrides = null; let displayOverrides = null; // style values let values = styleOptions.defaults; if (selectedStyle) { values = getElementStyleValues( styleOptions.defaults, selectedStyle.options, selectedStyle.displayOptions, display ); // display overrides if (display !== 'desktop') { const currentDisplayOptions = selectedStyle.displayOptions && selectedStyle.displayOptions[display]; if (currentDisplayOptions) { displayOverrides = Object.keys(currentDisplayOptions); } } } // element values if (selectedElement.styleProps || selectedElement.displayStyleProps) { values = getElementStyleValues( values, selectedElement.styleProps, selectedElement.displayStyleProps, display ); hasChanges = true; // display and element overrides if (display !== 'desktop') { const currentDisplayOptions = selectedElement.displayStyleProps && selectedElement.displayStyleProps[display]; if (currentDisplayOptions) { const keys = Object.keys(currentDisplayOptions); displayOverrides = union(displayOverrides || [], keys); elementOverrides = keys; // Check if element is overridding a display prop to null forEach(currentDisplayOptions, (value, key) => { if (value === null) { const ind = displayOverrides.indexOf(key); displayOverrides.splice(ind, 1); } }); } } else { elementOverrides = selectedElement.styleProps && Object.keys(selectedElement.styleProps); } } return { values, hasChanges, elementOverrides, displayOverrides }; } render () { const {styleOptions, selectedStyle} = this.props; const values = this.calcValues(); return ( <Editing selectedStyle={selectedStyle} options={styleOptions.options} values={values.values} elementOverrides={values.elementOverrides} displayOverrides={values.displayOverrides} hasChanges={values.hasChanges} onChange={this.onChangeProp} onSave={this.onSave} onUpdate={this.onUpdate} /> ); } }
public/app/components/app.js
threepears/react_todo
import React from 'react'; import ToDoHeader from './header'; import EntryForm from './entryform'; import Notes from './notes'; export default class App extends React.Component { constructor(props) { super(props); this.state = {todos: []}; } componentDidMount() { console.log("MOUNTING"); this.fetchTasks(); } // Get initial tasks from database fetchTasks() { fetch('/tasks', {method: 'GET'}) .then((response) => response.json()) .then((responseData) => { console.log("FETCHING", responseData); this.setState({todos: responseData}); }) .catch((err) => { throw new Error(err); }); } // Add task to database addTask(task) { fetch('/tasks/' + task, {method: 'POST'}) .then((response) => response.json()) .then((responseData) => { console.log("ADDING", responseData); this.fetchTasks(); }) .catch((err) => { throw new Error(err); }); } // Toggle task's completed status and save to database completeToggle(currentTask, currentState) { fetch('/tasks/complete/' + currentTask + '/' + currentState, {method: 'PUT'}) .then((response) => response.json()) .then((responseData) => { console.log("UPDATE COMPLETION", responseData); this.fetchTasks(); }) .catch((err) => { throw new Error(err); }); } // Delete task from database deleteTask(task) { fetch('/tasks/' + task, {method: 'DELETE'}) .then((response) => response.json()) .then((responseData) => { console.log("DELETING", responseData); this.fetchTasks(); }) .catch((err) => { throw new Error(err); }); } // Save an edited task name to database saveTask(oldTask, newTask) { fetch('/tasks/edit/' + oldTask + '/' + newTask, {method: 'PUT'}) .then((response) => response.json()) .then((responseData) => { console.log("UPDATE COMPLETION", responseData); this.fetchTasks(); }) .catch((err) => { throw new Error(err); }); } render() { return ( <div className='content'> <div className='content-left'> <ToDoHeader /> <EntryForm addTask={this.addTask.bind(this)} todos={this.state.todos} /> </div> <div className='content-right'> <Notes url="/tasks" todos={this.state.todos} deleteTask={this.deleteTask.bind(this)} saveTask={this.saveTask.bind(this)} completeToggle={this.completeToggle.bind(this)} /> </div> </div> ) } }
modules/IndexLink.js
chunwei/react-router
import React from 'react' import Link from './Link' const IndexLink = React.createClass({ render() { return <Link {...this.props} onlyActiveOnIndex={true} /> } }) export default IndexLink
src/app/components/App.js
itimai/react-try
import Debug from 'debug'; import React from 'react'; import ReactDOM from 'react-dom'; import $ from 'jquery'; import MomentsStore from '../stores/MomentsStore'; import UserStore from '../stores/UserStore'; import MomentsList from './MomentsList'; import Actions from '../actions/Actions'; import config from '../../../config/app'; var debug = Debug('React-app'); /* * @class App * @extends React.Component */ class App extends React.Component { /* * @constructs App */ constructor() { debug('create app'); super(); this.state = { loaded: false }; } /* * @method componentDidMount * @public */ componentDidMount () { var dfd = $.Deferred(); MomentsStore.addInitialLoadedListener(this._onInitialMomentLoaded.bind(this)); Actions.auth(dfd) dfd .then(function(userInfo) { Actions.addCurrentUser(JSON.parse(userInfo)); return Actions.getFeed(); }) .done(function(res) { Actions.setMoments(res); }.bind(this)) .fail(function(err) { debug(err); }); } /** * On initial load hanlder * @private */ _onInitialMomentLoaded () { this.setState({ loaded: true }); } /* * @method render * @public * @returns {JSX} */ render () { if (!this.state.loaded) { return <div>Loading...</div>; } return <div className="App"> <h1 className="app__headline">{ config.title }</h1> <MomentsList /> </div>; } }; export default App;
packages/vx-grid/src/grids/Rows.js
Flaque/vx
import React from 'react'; import cx from 'classnames'; import { Line } from '@vx/shape'; import { Group } from '@vx/group'; import { Point } from '@vx/point'; export default function Rows({ top = 0, left = 0, scale, width, stroke = '#eaf0f6', strokeWidth = 1, strokeDasharray, className, numTicks = 10, lineStyle, ...restProps }) { return ( <Group className={cx('vx-rows', className)} top={top} left={left}> {scale.ticks && scale.ticks(numTicks).map((d, i) => { const y = scale(d); const fromPoint = new Point({ x: 0, y, }); const toPoint = new Point({ x: width, y, }); return ( <Line key={`row-line-${d}-${i}`} from={fromPoint} to={toPoint} stroke={stroke} strokeWidth={strokeWidth} strokeDasharray={strokeDasharray} style={lineStyle} {...restProps} /> ); })} </Group> ); }
src/shared/components/clipPathImage/clipPathImage.js
alexspence/operationcode_frontend
import React from 'react'; import PropTypes from 'prop-types'; import styles from './clipPathImage.css'; const ClipPathImage = (props) => { const { image, altText, title, theme, className, link, ...otherProps } = props; return ( <a href={link} className={`${styles.cpContainer} ${styles.className}`} > <div className={`${styles.cpImage} ${styles[theme]}`} {...otherProps} > <img src={image} alt={altText} /> <h4>{title}</h4> </div> </a> ); }; ClipPathImage.propTypes = { image: PropTypes.string.isRequired, title: PropTypes.string.isRequired, altText: PropTypes.string, theme: PropTypes.string, className: PropTypes.string, link: PropTypes.string }; ClipPathImage.defaultProps = { altText: '', theme: 'blue', className: '', link: null }; export default ClipPathImage;
client/decorators/Link.js
springload/wagtaildraftail
import PropTypes from 'prop-types'; import React from 'react'; import { Icon } from 'draftail'; const Link = ({ entityKey, contentState, children }) => { const { url } = contentState.getEntity(entityKey).getData(); return ( <span data-tooltip={entityKey} className="RichEditor-link"> <Icon name={`icon-${url.indexOf('mailto:') !== -1 ? 'mail' : 'link'}`} /> {children} </span> ); }; Link.propTypes = { entityKey: PropTypes.string.isRequired, contentState: PropTypes.object.isRequired, children: PropTypes.node.isRequired, }; export default Link;
src/server.js
unboundfire/example-react-dashboard
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import 'babel/polyfill'; import _ from 'lodash'; import fs from 'fs'; import path from 'path'; import express from 'express'; import React from 'react'; import './core/Dispatcher'; import App from './components/App'; import bodyParser from 'body-parser'; import apiRoutes from './api/routes'; const server = express(); server.set('port', (process.env.PORT || 5001)); server.use(express.static(path.join(__dirname))); server.use(bodyParser.json()); server.use('/api', apiRoutes); // The top-level React component + HTML template for it const templateFile = path.join(__dirname, 'templates/index.html'); const template = _.template(fs.readFileSync(templateFile, 'utf8')); server.get('*', async (req, res, next) => { try { let notFound = false; let css = []; let data = {description: ''}; let app = <App path={req.path} context={{ onInsertCss: value => css.push(value), onSetMeta: (key, value) => data[key] = value, onPageNotFound: () => notFound = true }} />; data.body = React.renderToString(app); data.css = css.join(''); let html = template(data); if (notFound) { res.status(404); } res.send(html); } catch (err) { next(err); } }); // // Launch the server // ----------------------------------------------------------------------------- server.listen(server.get('port'), () => { if (process.send) { process.send('online'); } else { console.log('The server is running at http://localhost:' + server.get('port')); } });
assets/javascript/view/operation/sandbox.js
benhu/RestApiTester
'use strict'; import React from 'react'; import Button from '../button'; export default class Sandbox extends React.Component { constructor(props) { super(props); this.bind('send'); } bind(...methods) { methods.forEach((method) => this[method] = this[method].bind(this)); } send(e) { e.preventDefault(); if(this.props.onSubmit){ this.props.onSubmit(); } } render() { const spinnerClass = this.props.loading ? "spinner" : "hidden"; return ( <div className="sandbox"> <Button onClick={this.props.onSubmit}>Try it out! <div className={spinnerClass}><div className="circle"></div></div></Button> <Button onClick={this.props.onStop} hide={!this.props.loading} class="danger" wait="1000">Stop</Button> <Button onClick={this.props.onClear} hide={!this.props.hasResponse} class="warning">Clear response</Button> </div> ); } }
src/svg-icons/image/picture-as-pdf.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImagePictureAsPdf = (props) => ( <SvgIcon {...props}> <path d="M20 2H8c-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-8.5 7.5c0 .83-.67 1.5-1.5 1.5H9v2H7.5V7H10c.83 0 1.5.67 1.5 1.5v1zm5 2c0 .83-.67 1.5-1.5 1.5h-2.5V7H15c.83 0 1.5.67 1.5 1.5v3zm4-3H19v1h1.5V11H19v2h-1.5V7h3v1.5zM9 9.5h1v-1H9v1zM4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm10 5.5h1v-3h-1v3z"/> </SvgIcon> ); ImagePictureAsPdf = pure(ImagePictureAsPdf); ImagePictureAsPdf.displayName = 'ImagePictureAsPdf'; ImagePictureAsPdf.muiName = 'SvgIcon'; export default ImagePictureAsPdf;
node_modules/@material-ui/core/esm/NoSsr/NoSsr.js
pcclarke/civ-techs
import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; import React from 'react'; import PropTypes from 'prop-types'; import { exactProp } from '@material-ui/utils'; var useEnhancedEffect = typeof window !== 'undefined' && process.env.NODE_ENV !== 'test' ? React.useLayoutEffect : React.useEffect; /** * NoSsr purposely removes components from the subject of Server Side Rendering (SSR). * * This component can be useful in a variety of situations: * - Escape hatch for broken dependencies not supporting SSR. * - Improve the time-to-first paint on the client by only rendering above the fold. * - Reduce the rendering time on the server. * - Under too heavy server load, you can turn on service degradation. */ function NoSsr(props) { var children = props.children, _props$defer = props.defer, defer = _props$defer === void 0 ? false : _props$defer, _props$fallback = props.fallback, fallback = _props$fallback === void 0 ? null : _props$fallback; var _React$useState = React.useState(false), _React$useState2 = _slicedToArray(_React$useState, 2), mountedState = _React$useState2[0], setMountedState = _React$useState2[1]; useEnhancedEffect(function () { if (!defer) { setMountedState(true); } }, [defer]); React.useEffect(function () { if (defer) { setMountedState(true); } }, [defer]); // We need the Fragment here to force react-docgen to recognise NoSsr as a component. return React.createElement(React.Fragment, null, mountedState ? children : fallback); } process.env.NODE_ENV !== "production" ? NoSsr.propTypes = { /** * You can wrap a node. */ children: PropTypes.node.isRequired, /** * If `true`, the component will not only prevent server-side rendering. * It will also defer the rendering of the children into a different screen frame. */ defer: PropTypes.bool, /** * The fallback content to display. */ fallback: PropTypes.node } : void 0; if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line NoSsr['propTypes' + ''] = exactProp(NoSsr.propTypes); } export default NoSsr;
client/src/app/containers/header/TasksMenu.js
mtiger2k/graphql-tutorial
import React from 'react'; import TasksMenu from '../../../lib/header/TasksMenu'; const tasks = [ { key: 1, id: 1, color: 'aqua', progress: 20, text: 'Design some buttons', }, { key: 2, id: 2, color: 'green', progress: 40, text: 'Create a nice theme', }, { key: 3, id: 3, color: 'red', progress: 60, text: 'Some task I need to do', }, { key: 4, id: 4, color: 'yellow', progress: 80, text: 'Make beautiful transitions', }, { key: 5, id: 5, color: 'aqua', progress: 20, text: 'Design some buttons', }, { key: 6, id: 6, color: 'green', progress: 40, text: 'Create a nice theme', }, { key: 7, id: 7, color: 'red', progress: 60, text: 'Some task I need to do', }, { key: 8, id: 8, color: 'yellow', progress: 80, text: 'Make beautiful transitions', }, { key: 9, id: 9, color: 'aqua', progress: 20, text: 'Design some buttons', }, ]; function onItemClick(item) { // eslint-disable-next-line no-alert alert(`item ${item.id} clicked`); } function onFooterClick() { // eslint-disable-next-line no-alert alert('footer clicked'); } export default function () { return ( <TasksMenu items={tasks} onItemClick={onItemClick} onFooterClick={onFooterClick} /> ); }
code/web/node_modules/react-bootstrap/es/ModalHeader.js
zyxcambridge/RecordExistence
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'; import createChainedFunction from './utils/createChainedFunction'; // TODO: `aria-label` should be `closeLabel`. var propTypes = { /** * The 'aria-label' attribute provides an accessible label for the close * button. It is used for Assistive Technology when the label text is not * readable. */ 'aria-label': React.PropTypes.string, /** * Specify whether the Component should contain a close button */ closeButton: React.PropTypes.bool, /** * A Callback fired when the close button is clicked. If used directly inside * a Modal component, the onHide will automatically be propagated up to the * parent Modal `onHide`. */ onHide: React.PropTypes.func }; var defaultProps = { 'aria-label': 'Close', closeButton: false }; var contextTypes = { $bs_modal: React.PropTypes.shape({ onHide: React.PropTypes.func }) }; var ModalHeader = function (_React$Component) { _inherits(ModalHeader, _React$Component); function ModalHeader() { _classCallCheck(this, ModalHeader); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ModalHeader.prototype.render = function render() { var _props = this.props; var label = _props['aria-label']; var closeButton = _props.closeButton; var onHide = _props.onHide; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['aria-label', 'closeButton', 'onHide', 'className', 'children']); var modal = this.context.$bs_modal; var _splitBsProps = splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement( 'div', _extends({}, elementProps, { className: classNames(className, classes) }), closeButton && React.createElement( 'button', { type: 'button', className: 'close', 'aria-label': label, onClick: createChainedFunction(modal.onHide, onHide) }, React.createElement( 'span', { 'aria-hidden': 'true' }, '\xD7' ) ), children ); }; return ModalHeader; }(React.Component); ModalHeader.propTypes = propTypes; ModalHeader.defaultProps = defaultProps; ModalHeader.contextTypes = contextTypes; export default bsClass('modal-header', ModalHeader);
src/GridColumnHeader.js
shaneosullivan/spotlist
import React, { Component } from 'react'; import cancelEvt from './cancelEvt'; export default class GridColumnHeader extends Component { render() { let artist = this.props.artist; return ( <div className="grid-col"> <a href="#" onClick={this._toggleArtist} className="grid-artist-name"> <span>{artist.name}</span> </a> </div> ); } _toggleArtist = evt => { cancelEvt(evt); this.props.onArtistToggle(this.props.artist); }; }
app/components/AddEditExerciseFormContainer/AddEditExerciseFormContainer.js
sunnymis/Swoleciety
import React from 'react'; import PropTypes from 'prop-types'; import AddEditExerciseForm from '../AddEditExerciseForm/AddEditExerciseForm'; import UserService from '../../services/users.service'; import AuthService from '../../services/auth.service'; import DateService from '../../services/date.service'; require('./AddEditExerciseFormContainer.scss'); class AddEditExerciseFormContainer extends React.Component { static defaultProps = { onBlur: () => { }, selectedExercise: {}, isEditting: false }; static propTypes = { onBlur: PropTypes.func, selectedExercise: PropTypes.object, isEditting: PropTypes.bool }; handleOnBlur = (e) => { this.setState({}); /* Newly focused AddEdit isn't focused as the blur event occurs This solution solves this issue: https://gist.github.com/pstoica/4323d3e6e37e8a23dd59 */ const currentTarget = e.currentTarget; setTimeout(() => { if (!currentTarget.contains(document.activeElement)) { this.props.onBlur(false); } }, 0); } handleOnDataChange = (e) => { this.setState({ [e.target.name]: e.target.value, }); } handleOnNewEntryChange = (e) => { const newEntry = (this.state.newEntry) ? this.state.newEntry : {}; newEntry[e.target.name] = e.target.value; this.setState({ newEntry: newEntry, }); } handleOnSave = () => { const day = this.props.match.params.day; const key = this.props.selectedExercise.details.key; const modifiedExercise = {}; modifiedExercise[this.state.newEntry.field] = this.state.newEntry.value; AuthService.getCurrentlySignedInUser((user) => { if (this.props.selectedExercise.details) { UserService.updateExerciseByKey(user.uid, day, key, modifiedExercise); } else { UserService.addExercise(user.uid, day, { name: this.props.selectedExercise.details.name, [this.state.newEntry.field.toLowerCase()]: this.state.newEntry.value, }); } }); } handleOnCancel = () => { this.props.onBlur(false); } render() { return ( <div> <AddEditExerciseForm exerciseDetails={this.props.selectedExercise} onOutsideClick={this.handleOnBlur} onSave={this.handleOnSave} onCancel={this.handleOnCancel} onDataChange={this.handleOnDataChange} onNewEntryChange={this.handleOnNewEntryChange} /> </div> ); } } export default AddEditExerciseFormContainer;
Native/Learn_Navigation/index.ios.js
renxlWin/React-Native_Demo
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Button } from 'react-native'; import { StackNavigator } from 'react-navigation' class HomeScreen extends React.Component { static navigationOptions = { title : '附近', }; render() { const { navigate } = this.props.navigation; var testPra = {'testKey' : '我是谁','user' : 'React'} return ( <View> <Text>Hello,React</Text> <Button onPress={() => navigate('Detail',testPra) } title = '详情' /> </View> ); } } class DetailSereen extends React.Component { static navigationOptions = ({ navigation }) => ({ title: `${navigation.state.params.user}`, }); render() { const { params } = this.props.navigation.state; return ( <Text>Hello {params.testKey}</Text> ); } } const Learn_Navigation = StackNavigator({ Home : { screen : HomeScreen }, Detail : { screen : DetailSereen}, }); AppRegistry.registerComponent('Learn_Navigation', () => Learn_Navigation);
app/javascript/mastodon/features/standalone/public_timeline/index.js
d6rkaiz/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { expandPublicTimeline, expandCommunityTimeline } from 'mastodon/actions/timelines'; import Masonry from 'react-masonry-infinite'; import { List as ImmutableList, Map as ImmutableMap } from 'immutable'; import DetailedStatusContainer from 'mastodon/features/status/containers/detailed_status_container'; import { debounce } from 'lodash'; import LoadingIndicator from 'mastodon/components/loading_indicator'; const mapStateToProps = (state, { local }) => { const timeline = state.getIn(['timelines', local ? 'community' : 'public'], ImmutableMap()); return { statusIds: timeline.get('items', ImmutableList()), isLoading: timeline.get('isLoading', false), hasMore: timeline.get('hasMore', false), }; }; export default @connect(mapStateToProps) class PublicTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, statusIds: ImmutablePropTypes.list.isRequired, isLoading: PropTypes.bool.isRequired, hasMore: PropTypes.bool.isRequired, local: PropTypes.bool, }; componentDidMount () { this._connect(); } componentDidUpdate (prevProps) { if (prevProps.local !== this.props.local) { this._connect(); } } _connect () { const { dispatch, local } = this.props; dispatch(local ? expandCommunityTimeline() : expandPublicTimeline()); } handleLoadMore = () => { const { dispatch, statusIds, local } = this.props; const maxId = statusIds.last(); if (maxId) { dispatch(local ? expandCommunityTimeline({ maxId }) : expandPublicTimeline({ maxId })); } } setRef = c => { this.masonry = c; } handleHeightChange = debounce(() => { if (!this.masonry) { return; } this.masonry.forcePack(); }, 50) render () { const { statusIds, hasMore, isLoading } = this.props; const sizes = [ { columns: 1, gutter: 0 }, { mq: '415px', columns: 1, gutter: 10 }, { mq: '640px', columns: 2, gutter: 10 }, { mq: '960px', columns: 3, gutter: 10 }, { mq: '1255px', columns: 3, gutter: 10 }, ]; const loader = (isLoading && statusIds.isEmpty()) ? <LoadingIndicator key={0} /> : undefined; return ( <Masonry ref={this.setRef} className='statuses-grid' hasMore={hasMore} loadMore={this.handleLoadMore} sizes={sizes} loader={loader}> {statusIds.map(statusId => ( <div className='statuses-grid__item' key={statusId}> <DetailedStatusContainer id={statusId} compact measureHeight onHeightChange={this.handleHeightChange} /> </div> )).toArray()} </Masonry> ); } }
docs/app/Examples/modules/Dropdown/Content/DropdownExampleInput.js
mohammed88/Semantic-UI-React
import React from 'react' import { Dropdown, Input } from 'semantic-ui-react' const DropdownExampleInput = () => ( <Dropdown text='Filter' floating labeled button className='icon'> {/* <i class="filter icon"></i> */} <Dropdown.Menu> <Dropdown.Header content='Search Issues' /> <Input icon='search' iconPosition='left' name='search' /> <Dropdown.Header icon='tags' content='Filter by tag' /> <Dropdown.Divider /> <Dropdown.Item label={{ color: 'red', empty: true, circular: true }} text='Important' /> <Dropdown.Item label={{ color: 'blue', empty: true, circular: true }} text='Announcement' /> <Dropdown.Item label={{ color: 'black', empty: true, circular: true }} text='Discussion' /> </Dropdown.Menu> </Dropdown> ) export default DropdownExampleInput
packages/core/stories/tokens/colors/ColorDisplay.js
massgov/mayflower
import React from 'react'; import PropTypes from 'prop-types'; import ButtonCopy from '@massds/mayflower-react/dist/ButtonCopy'; import './_color-display.scss'; const ColorSwatch = ({ name, value, variable, width = '200px', height = '4rem', copiable = true, inline = false }) => { const hexValue = value.toUpperCase(); return( <div style={{ display: 'flex', flexDirection: inline ? 'row' : 'column' }}> { name && <h6>{name}</h6>} <div className="sg-swatch" style={{ background: value, borderRadius: 0, height, width, border: '1px solid #EEEEEE' }} /> <div className="sg-info"> <span>{hexValue}</span> {copiable && <ButtonCopy content={hexValue} />} {copiable && <br />} {variable && <span style={{ fontSize: '.9rem' }}>{variable}</span>} </div> </div> ); }; ColorSwatch.propTypes = { /** Color name */ name: PropTypes.string, /** Color hex value */ value: PropTypes.string, /** Color variable alias */ variable: PropTypes.string, /** Whether to inline color swatch and hex code */ inline: PropTypes.bool, /** Whether to add button copy */ copiable: PropTypes.bool, /** Width of the color swatch */ width: PropTypes.string, /** Height of the color swatch */ height: PropTypes.string }; const GradientTile = (props) => { const colorRef = React.useRef(null); const [rgb, setRgb] = React.useState(''); React.useEffect(() => { const computedStyles = window.getComputedStyle(colorRef.current).getPropertyValue('background-color'); setRgb(() => computedStyles); }); const hex = (x) => `0${Number(x).toString(16)}`.slice(-2); const rgbToHex = (rgbVal) => { const rgbValues = rgbVal && rgbVal.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); const hexValue = rgbValues && `#${hex(rgbValues[1])}${hex(rgbValues[2])}${hex(rgbValues[3])}`; return hexValue; }; const { index, effect } = props; const firstTile = index === 0; const name = firstTile ? props.name : `${index * 10} % ${effect}`; const hexValue = rgbToHex(rgb).toUpperCase(); return( <li className={`${props.token}--${effect}`}> <h6>{name}</h6> <div className="sg-swatch" ref={colorRef} /> <div className="sg-info"> <span>{hexValue}</span> <ButtonCopy content={hexValue} /> </div> </li> ); }; GradientTile.propTypes = { /** Gradient index, used to determine the percentage of the effect */ index: PropTypes.number, /** Color effect: tint or shade */ effect: PropTypes.string, /** Base color name */ name: PropTypes.string, /** Base color SCSS variable name */ token: PropTypes.string }; const GradientSpectrum = ({ token, name, effect }) => { const tiles = effect === 'tint' ? 10 : 6; let i; const tilesArray = []; for (i = 0; i < tiles; i += 1) { tilesArray.push(i); } return( <ul className="sg-colors sg-colors--gradient"> { // eslint-disable-next-line react/no-array-index-key tilesArray.map((index) => <GradientTile key={`${token}${index}`} name={name} token={token} index={index} effect={effect} />) } </ul> ); }; GradientSpectrum.propTypes = { /** Color effect: tint or shade */ effect: PropTypes.string, /** Base color name */ name: PropTypes.string, /** Base color SCSS variable alias */ token: PropTypes.string }; export { ColorSwatch, GradientSpectrum };
docs/app/Examples/views/Statistic/Variations/StatisticExampleInverted.js
aabustamante/Semantic-UI-React
import React from 'react' import { Segment, Statistic } from 'semantic-ui-react' const StatisticExampleInverted = () => ( <Segment inverted> <Statistic inverted value='54' label='inverted' /> <Statistic inverted color='red' value='27' label='red' /> <Statistic inverted color='orange' value='8' label='orange' /> <Statistic inverted color='yellow' value='28' label='yellow' /> <Statistic inverted color='olive' value='7' label='olive' /> <Statistic inverted color='green' value='14' label='green' /> <Statistic inverted color='teal' value='82' label='teal' /> <Statistic inverted color='blue' value='1' label='blue' /> <Statistic inverted color='violet' value='22' label='violet' /> <Statistic inverted color='purple' value='23' label='purple' /> <Statistic inverted color='pink' value='15' label='pink' /> <Statistic inverted color='brown' value='36' label='brown' /> <Statistic inverted color='grey' value='49' label='grey' /> </Segment> ) export default StatisticExampleInverted
lib/src/game/stopwatch.js
Hezko/MineBlown-GameUI
import React from 'react'; const interval = 200; class Stopwatch extends React.Component { constructor(props) { super(props); this.initialState = { isRunning: false, timeElapsed: props.initialTime, }; if (props.runOnStart) { this.state = { isRunning: true, timeElapsed: props.initialTime }; this.startTimerInternal(); } else { this.state = { isRunning: this.initialState.isRunning, timeElapsed: this.initialState.timeElapsed } } } toggle() { this.setState({ isRunning: !this.state.isRunning }, () => { this.state.isRunning ? this.startTimerInternal() : this.stopTimerInternal(); }); } reset() { clearTimeout(this.timer); this.setState({ isRunning: this.initialState.isRunning, timeElapsed: this.initialState.timeElapsed }); } startTimer() { this.setState({ isRunning: true }); this.startTimerInternal(); } startTimerInternal() { this.startTime = Date.now(); this.timer = setTimeout(this.tick.bind(this), interval); } stopTimer() { this.setState({ isRunning: false }); this.stopTimerInternal(); } stopTimerInternal() { clearTimeout(this.timer); } tick() { if (this.state.isRunning === true && this.state.isMounted === true) { this.timer = setTimeout(this.tick.bind(this), interval); } this.update(); } update() { const delta = Date.now() - this.startTime; const time = this.state.timeElapsed + delta; this.setState({ timeElapsed: time }); this.startTime = Date.now(); } componentDidMount() { this.setState({ isMounted: true }); } componentWillUnmount() { this.setState({ isMounted: false }); clearTimeout(this.timer); } render() { const { isRunning, timeElapsed } = this.state; return ( <div> <TimeElapsed id="timer" timeElapsed={this.props.initialTime + timeElapsed} initialTime={this.props.initialTime} assetsProvider={this.props.assetsProvider} /> </div> ); } } class TimeElapsed extends React.Component { getUnits() { const seconds = this.props.timeElapsed / 1000 + this.props.initialTime; return { // min: Math.floor(seconds / 100).toString(), sec: Math.floor(seconds).toString(), // msec: (seconds % 1).toFixed(3).substring(2) }; } render() { const units = this.getUnits(); const left = Math.floor((units.sec % 1000) / 100); const center = Math.floor((units.sec % 100) / 10); const right = units.sec % 10; const leftImgSrc = this.props.assetsProvider.getAsset('../../assets/images/counters/counter' + left + '.gif'); const centerImgSrc = this.props.assetsProvider.getAsset('../../assets/images/counters/counter' + center + '.gif'); const rightImgSrc = this.props.assetsProvider.getAsset('../../assets/images/counters/counter' + right + '.gif'); return ( <div id={this.props.id}> <span className={'counter'}> <img src={leftImgSrc} /> </span> <span className={'counter'}> <img src={centerImgSrc} /> </span> <span className={'counter'}> <img src={rightImgSrc} /> </span> </div> ); } } export default Stopwatch;
examples/huge-apps/routes/Course/routes/Assignments/components/Assignments.js
keathley/react-router
import React from 'react'; class Assignments extends React.Component { render () { return ( <div> <h3>Assignments</h3> {this.props.children || <p>Choose an assignment from the sidebar.</p>} </div> ); } } export default Assignments;
docs-js/VoteShareByYear.js
esonderegger/us-house-if-proportional
import React from 'react'; import {LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend} from 'recharts'; import fec from './fec.json'; function percent(dec) { return (dec * 100).toFixed(2); } export default class VoteShareByYear extends React.Component { render() { const data = [2004, 2006, 2008, 2010, 2012, 2014, 2016].map((year) => { return { 'name': year, 'D votes (%)': percent(fec[year].summary.demVoteRatio), 'R votes (%)': percent(fec[year].summary.gopVoteRatio), 'D seats (%)': percent(fec[year].summary.demRepRatio), 'R seats (%)': percent(fec[year].summary.gopRepRatio), }; }); return ( <div> <LineChart width={720} height={320} data={data} margin={{top: 15, right: 40, left: 0, bottom: 15}} > <XAxis dataKey="name" /> <YAxis domain={[40, 60]} /> <CartesianGrid strokeDasharray="3 3"/> <Tooltip/> <Legend /> <Line type="monotone" dataKey="D votes (%)" stroke="#aaaaff" /> <Line type="monotone" dataKey="D seats (%)" stroke="#0000ff" /> <Line type="monotone" dataKey="R votes (%)" stroke="#ffaaaa" /> <Line type="monotone" dataKey="R seats (%)" stroke="#ff0000" /> </LineChart> </div> ); } }
src/svg-icons/action/watch-later.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionWatchLater = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm4.2 14.2L11 13V7h1.5v5.2l4.5 2.7-.8 1.3z"/> </SvgIcon> ); ActionWatchLater = pure(ActionWatchLater); ActionWatchLater.displayName = 'ActionWatchLater'; ActionWatchLater.muiName = 'SvgIcon'; export default ActionWatchLater;
imports/ui/components/NestedCategoriesWidget/NestedCategoriesWidget.js
hwillson/meteor-solr-demo
/* eslint-disable react/prefer-es6-class */ /* global window */ import React from 'react'; import { _ } from 'meteor/underscore'; import NestedCategories from './NestedCategories'; const NestedCategoriesWidget = React.createClass({ propTypes: { field: React.PropTypes.string.isRequired, name: React.PropTypes.string.isRequired, categories: React.PropTypes.object.isRequired, searchParams: React.PropTypes.object.isRequired, handleSearchParamsUpdate: React.PropTypes.func.isRequired, showHelp: React.PropTypes.bool, selectedCategoryPath: React.PropTypes.string, rootNodeLimit: React.PropTypes.number, sortRootNodesDesc: React.PropTypes.bool, }, getDefaultProps() { return { showHelp: false, }; }, componentWillMount() { this.setState({ showHelp: this.props.showHelp, }); }, handleCategorySelect(selectedCategoryPath) { if (selectedCategoryPath) { const newSearchParams = _.extend({}, this.props.searchParams); newSearchParams.fields[this.props.field] = selectedCategoryPath; newSearchParams.currentPage = 1; newSearchParams.lastAddedFieldName = this.props.field; this.props.handleSearchParamsUpdate(newSearchParams); window.scroll(0, 0); } }, resetSelectedCategory() { const newSearchParams = _.extend({}, this.props.searchParams); delete newSearchParams.fields[this.props.field]; newSearchParams.lastAddedFieldName = null; this.props.handleSearchParamsUpdate(newSearchParams); }, closeHelp() { this.setState({ showHelp: false, }); }, renderResetLink() { let resetLink; if (this.props.selectedCategoryPath) { resetLink = ( <div className="reset"> <button className="btn btn-xs btn-danger" onClick={this.resetSelectedCategory} > <i className="fa fa-times-circle" /> RESET </button> </div> ); } return resetLink; }, renderHelp() { let help; if (this.state.showHelp) { help = ( <div className="alert alert-info alert-dismissible notice" role="alert"> <button type="button" className="close" onClick={this.closeHelp}> <span aria-hidden="true">&times;</span> </button> Click <i className="fa fa-plus-square" /> to see more categories; click on a category name to refine your search. </div> ); } return help; }, renderCategoryContent() { let categoryContent; if (this.props.categories.children.length > 0) { const categories = []; let children = this.props.categories.children; if (this.props.sortRootNodesDesc) { children = _.sortBy(children, 'name').reverse(); } let cutoff = children.length; if (this.props.rootNodeLimit && (this.props.rootNodeLimit <= children.length)) { cutoff = this.props.rootNodeLimit; } for (let i = 0; i < cutoff; i++) { const child = children[i]; categories.push( <NestedCategories key={child.name} categories={child} onCategorySelect={this.handleCategorySelect} selectedCategoryPath={this.props.selectedCategoryPath} /> ); } categoryContent = ( <ul className="category-tree"> {categories} </ul> ); } else { categoryContent = (<span>No results found.</span>); } return categoryContent; }, render() { return ( <div className="nested-categories panel panel-default"> <div className="panel-heading clearfix"> <div className="pull-left"> <strong>{this.props.name}</strong> </div> <div className="pull-right"> {this.renderResetLink()} </div> </div> <div className="panel-body"> {this.renderHelp()} {this.renderCategoryContent()} </div> </div> ); }, }); export default NestedCategoriesWidget;
packages/core/admin/admin/src/components/UpgradePlanModal/index.js
wistityhq/strapi
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { useIntl } from 'react-intl'; import { Portal } from '@strapi/design-system/Portal'; import { FocusTrap } from '@strapi/design-system/FocusTrap'; import { IconButton } from '@strapi/design-system/IconButton'; import { LinkButton } from '@strapi/design-system/LinkButton'; import { Box } from '@strapi/design-system/Box'; import { Flex } from '@strapi/design-system/Flex'; import { Typography } from '@strapi/design-system/Typography'; import { Stack } from '@strapi/design-system/Stack'; import ExternalLink from '@strapi/icons/ExternalLink'; import Cross from '@strapi/icons/Cross'; import { setHexOpacity, useLockScroll } from '@strapi/helper-plugin'; import AirBalloon from '../../assets/images/hot-air-balloon.png'; import BigArrow from '../../assets/images/upgrade-details.png'; const UpgradeWrapper = styled.div` position: absolute; z-index: 3; inset: 0; background: ${({ theme }) => setHexOpacity(theme.colors.neutral800, 0.2)}; padding: 0 ${({ theme }) => theme.spaces[8]}; `; const UpgradeContainer = styled(Flex)` position: relative; max-width: ${830 / 16}rem; height: ${415 / 16}rem; margin: 0 auto; overflow: hidden; margin-top: 10%; padding-left: ${64 / 16}rem; img:first-of-type { position: absolute; right: 0; top: 0; max-width: ${360 / 16}rem; } img:not(:first-of-type) { width: ${130 / 16}rem; margin-left: 12%; margin-right: ${20 / 16}rem; z-index: 0; } `; const StackFlexStart = styled(Stack)` align-items: flex-start; max-width: ${400 / 16}rem; z-index: 0; `; const CloseButtonContainer = styled(Box)` position: absolute; right: ${({ theme }) => theme.spaces[4]}; top: ${({ theme }) => theme.spaces[4]}; `; const UpgradePlanModal = ({ onClose, isOpen }) => { useLockScroll(isOpen); const { formatMessage } = useIntl(); if (!isOpen) { return null; } return ( <Portal> <UpgradeWrapper onClick={onClose}> <FocusTrap onEscape={onClose}> <UpgradeContainer onClick={e => e.stopPropagation()} aria-labelledby="upgrade-plan" background="neutral0" hasRadius > <img src={AirBalloon} alt="air-balloon" /> <CloseButtonContainer> <IconButton onClick={onClose} aria-label="Close" icon={<Cross />} /> </CloseButtonContainer> <StackFlexStart size={6}> <Typography fontWeight="bold" textColor="primary600"> {formatMessage({ id: 'app.components.UpgradePlanModal.text-ce', defaultMessage: 'COMMUNITY EDITION', })} </Typography> <Stack size={2}> <Typography variant="alpha" as="h2" id="upgrade-plan"> {formatMessage({ id: 'app.components.UpgradePlanModal.limit-reached', defaultMessage: 'You have reached the limit', })} </Typography> <Typography> {formatMessage({ id: 'app.components.UpgradePlanModal.text-power', defaultMessage: 'Unlock the full power of Strapi by upgrading your plan to the Enterprise Edition', })} </Typography> </Stack> <LinkButton href="https://strapi.io/pricing-self-hosted" endIcon={<ExternalLink />}> {formatMessage({ id: 'app.components.UpgradePlanModal.button', defaultMessage: 'Learn more', })} </LinkButton> </StackFlexStart> <img src={BigArrow} alt="upgrade-arrow" /> </UpgradeContainer> </FocusTrap> </UpgradeWrapper> </Portal> ); }; UpgradePlanModal.propTypes = { onClose: PropTypes.func.isRequired, isOpen: PropTypes.bool.isRequired, }; export default UpgradePlanModal;
src/pages/Charts/Nasdaq.js
chaitanya1375/Myprojects
import React from 'react'; import ReactChartist from 'react-chartist'; import Chartist from 'chartist'; const dataStock = { labels: ['\'07','\'08','\'09', '\'10', '\'11', '\'12', '\'13', '\'14', '\'15'], series: [ [22.20, 34.90, 42.28, 51.93, 62.21, 80.23, 62.21, 82.12, 102.50, 107.23] ] }; const optionsStock = { lineSmooth: false, height: "260px", axisY: { offset: 40, labelInterpolationFnc: function(value) { return '$' + value; } }, low: 10, high: 110, classNames: { point: 'ct-point ct-green', line: 'ct-line ct-green' } }; const Nasdaq = () => ( <div className="card"> <div className="header"> <h4>NASDAQ: AAPL</h4> <p className="category">Line Chart with Points</p> </div> <div className="content"> <ReactChartist data={dataStock} options={optionsStock} type="Line" className="ct-chart" /> </div> </div> ); export default Nasdaq;
src/index.js
timmathews/react-digital-gauge
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
src/components/capture/capture-modal/DatePicker.js
sebpearce/cycad-react
import React from 'react'; import styles from './CaptureModal.scss'; import { formatLongDate } from '../../../helpers/date-helpers'; const getDayOfWeek = isoDate => { const dateObj = new Date(isoDate); return dateObj.getDay(); }; const Picker = ({ selected, adjustDate }) => { const isSelected = day => { return day === selected ? styles.datePickerCellSelected : styles.datePickerCell; }; const offset = Math.abs(selected - (selected === 0 ? 7 : 0)); return ( <div className={styles.datePicker}> <div className={isSelected(1)} onClick={()=>{adjustDate(1 - offset)}}>M</div> <div className={isSelected(2)} onClick={()=>{adjustDate(2 - offset)}}>T</div> <div className={isSelected(3)} onClick={()=>{adjustDate(3 - offset)}}>W</div> <div className={isSelected(4)} onClick={()=>{adjustDate(4 - offset)}}>T</div> <div className={isSelected(5)} onClick={()=>{adjustDate(5 - offset)}}>F</div> <div className={isSelected(6)} onClick={()=>{adjustDate(6 - offset)}}>S</div> <div className={isSelected(0)} onClick={()=>{adjustDate(7 - offset)}}>S</div> </div> ); }; const DatePicker = props => { return ( <div> <div className={styles.tips}> {'[ and ] to change day, { and } to change week'} </div> <div className={styles.dateDisplay}> {formatLongDate(props.date)} </div> <Picker selected={getDayOfWeek(props.date)} adjustDate={props.adjustDate} /> </div> ); }; DatePicker.propTypes = { date: React.PropTypes.string.isRequired, adjustDate: React.PropTypes.func.isRequired, } export default DatePicker;
src/components/Search/ResultList.js
honeypotio/techmap
import React from 'react'; import { Link } from 'react-router'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import Icon from '../Icon'; const Item = styled(Link)` color: #1f2228; display: flex; align-items: center; font-weight: 500; padding: 15px 10px; text-decoration: none; width: 100%; &:hover { background-color: #f2f2f2; } > svg { margin-left: 8px; margin-right: 15px; } `; const ResultList = ({ data }) => { const items = data.map((item, idx) => { const url = `/london/company/${encodeURIComponent(item.name)}`; return ( <Item key={idx} to={url}> <Icon name="business" fill="#104986" />{item.name} </Item> ); }); return ( <div> {items.length ? items : ''} </div> ); }; ResultList.propTypes = { data: PropTypes.array }; export default ResultList;
src/modules/feedback/Feedback.js
rllc/llc-archives-react
import React from 'react' class Feedback extends React.Component { render() { // TODO return <div>Feedback</div> } } export default Feedback
frontend/sections/info/about.js
apostolidhs/wiregoose
import React from 'react'; import tr from '../../components/localization/localization.js'; import { publish } from '../../components/events/events.js'; import Info from './info.js'; import headerImage from '../../assets/img/option-menu-about-bg.png'; import headerFooterImage from '../../assets/img/option-menu-about-bg-footer.png'; export default class About extends React.Component { componentDidMount() { publish('page-ready', { title: tr.infoAboutTitle, description: tr.infoAboutWiregoose, keywords: tr.infoAboutTitle }); } render() { return ( <Info headerImg={headerImage} headerFooterImg={headerFooterImage} > <h1>{tr.infoAboutTitle}</h1> <h2>{tr.infoAboutWiregoose}</h2> <p>{tr.infoAboutWiregooseDesc}</p> <h2>{tr.infoAboutWorking}</h2> <h3>{tr.infoAboutWorkingRss}</h3> <p>{tr.infoAboutWorkingRssDesc}</p> <p>{tr.infoAboutWorkingRssDescWiregoose}</p> <h3>{tr.infoAboutCrawler}</h3> <p dangerouslySetInnerHTML={{ __html: tr.infoAboutCrawlerDesc}}></p> <p dangerouslySetInnerHTML={{ __html: tr.infoAboutCrawlerDescMozilla}}></p> </Info> ); } }
app/javascript/mastodon/features/lists/index.js
increments/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import { fetchLists } from '../../actions/lists'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ColumnLink from '../ui/components/column_link'; import ColumnSubheading from '../ui/components/column_subheading'; import NewListForm from './components/new_list_form'; import { createSelector } from 'reselect'; const messages = defineMessages({ heading: { id: 'column.lists', defaultMessage: 'Lists' }, subheading: { id: 'lists.subheading', defaultMessage: 'Your lists' }, }); const getOrderedLists = createSelector([state => state.get('lists')], lists => { if (!lists) { return lists; } return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title'))); }); const mapStateToProps = state => ({ lists: getOrderedLists(state), }); @connect(mapStateToProps) @injectIntl export default class Lists extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, lists: ImmutablePropTypes.list, intl: PropTypes.object.isRequired, }; componentWillMount () { this.props.dispatch(fetchLists()); } render () { const { intl, lists } = this.props; if (!lists) { return ( <Column> <LoadingIndicator /> </Column> ); } return ( <Column icon='bars' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <NewListForm /> <div className='scrollable'> <ColumnSubheading text={intl.formatMessage(messages.subheading)} /> {lists.map(list => <ColumnLink key={list.get('id')} to={`/timelines/list/${list.get('id')}`} icon='bars' text={list.get('title')} /> )} </div> </Column> ); } }
src/components/view/index.js
sergeyruskov/sergeyruskov.github.io
//@flow import React from 'react'; import {compose} from 'redux'; import {connect} from "react-redux"; import {Redirect} from "react-router-dom"; import ViewInput from './view-input'; import type { Cards } from '../../types/cards'; /** * Конечное представление настроенной формы * */ function ViewForm({view}: { view: Cards, }) { if (!view.length) return <Redirect to="/" />; return <div className="form">{view.map(({type, title, required, list}, i) => { switch (type) { case 'input': { return <ViewInput title={title} required={required} key={i} /> } case 'select': { return <div className="preview__item--without-hover" key={i}> {title}: <br/><br/> <select required={required}> {list && list.map(text => { return <option key={text}>{text}</option> })} </select> </div> } default: { return <span>Error</span> } } })}</div> } export default compose( connect(({view}: {view: Cards}) => ({view})) )(ViewForm);
src/icons/GlyphSmallArrow.js
ipfs/webui
import React from 'react' const GlyphSmallArrows = props => ( <svg viewBox="0 0 32 21" {...props}> <path d="M16 20.2L0.5 4.7L4.4 0.800003L16 12.4L27.6 0.800003L31.5 4.7C26.3 9.8 21.2 15 16 20.2Z" /> </svg> ) export default GlyphSmallArrows
information/blendle-frontend-react-source/app/components/navigation/LogoLink/index.js
BramscoChill/BlendleParser
import React from 'react'; import PropTypes from 'prop-types'; import { pure } from 'recompose'; import classNames from 'classnames'; import { BlendleLogo } from '@blendle/lego'; import Link from 'components/Link'; import CSS from './LogoLink.scss'; const LogoLink = ({ className, ...props }) => { const linkClassName = classNames(CSS.link, 'blendle-logo', className); return ( <Link href="/" className={linkClassName}> <BlendleLogo {...props} className={CSS.logo} /> </Link> ); }; LogoLink.propTypes = { className: PropTypes.string, }; export default pure(LogoLink); // WEBPACK FOOTER // // ./src/js/app/components/navigation/LogoLink/index.js
app/containers/NotFoundPage/index.js
sulthan16/awesome-jr-frontend-sulthan
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import H1 from 'components/H1'; import messages from './messages'; export default function NotFound() { return ( <article> <H1> <FormattedMessage {...messages.header} /> </H1> </article> ); }
examples/counter/index.js
leoasis/redux
import React from 'react' import ReactDOM from 'react-dom' import { createStore } from 'redux' import Counter from './components/Counter' import counter from './reducers' const store = createStore(counter) const rootEl = document.getElementById('root') function render() { ReactDOM.render( <Counter value={store.getState()} onIncrement={() => store.dispatch({ type: 'INCREMENT' })} onDecrement={() => store.dispatch({ type: 'DECREMENT' })} />, rootEl ) } render() store.subscribe(render)
node_modules/react-select/examples/src/components/CustomComponents.js
maty21/statistisc
import React from 'react'; import Select from 'react-select'; import Gravatar from 'react-gravatar'; const USERS = require('../data/users'); const GRAVATAR_SIZE = 15; const GravatarOption = React.createClass({ propTypes: { children: React.PropTypes.node, className: React.PropTypes.string, isDisabled: React.PropTypes.bool, isFocused: React.PropTypes.bool, isSelected: React.PropTypes.bool, onFocus: React.PropTypes.func, onSelect: React.PropTypes.func, option: React.PropTypes.object.isRequired, }, handleMouseDown (event) { event.preventDefault(); event.stopPropagation(); this.props.onSelect(this.props.option, event); }, handleMouseEnter (event) { this.props.onFocus(this.props.option, event); }, handleMouseMove (event) { if (this.props.isFocused) return; this.props.onFocus(this.props.option, event); }, render () { let gravatarStyle = { borderRadius: 3, display: 'inline-block', marginRight: 10, position: 'relative', top: -2, verticalAlign: 'middle', }; return ( <div className={this.props.className} onMouseDown={this.handleMouseDown} onMouseEnter={this.handleMouseEnter} onMouseMove={this.handleMouseMove} title={this.props.option.title}> <Gravatar email={this.props.option.email} size={GRAVATAR_SIZE} style={gravatarStyle} /> {this.props.children} </div> ); } }); const GravatarValue = React.createClass({ propTypes: { children: React.PropTypes.node, placeholder: React.PropTypes.string, value: React.PropTypes.object }, render () { var gravatarStyle = { borderRadius: 3, display: 'inline-block', marginRight: 10, position: 'relative', top: -2, verticalAlign: 'middle', }; return ( <div className="Select-value" title={this.props.value.title}> <span className="Select-value-label"> <Gravatar email={this.props.value.email} size={GRAVATAR_SIZE} style={gravatarStyle} /> {this.props.children} </span> </div> ); } }); const UsersField = React.createClass({ propTypes: { hint: React.PropTypes.string, label: React.PropTypes.string, }, getInitialState () { return {}; }, setValue (value) { this.setState({ value }); }, render () { var placeholder = <span>&#9786; Select User</span>; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select arrowRenderer={arrowRenderer} onChange={this.setValue} optionComponent={GravatarOption} options={USERS} placeholder={placeholder} value={this.state.value} valueComponent={GravatarValue} /> <div className="hint"> This example implements custom Option and Value components to render a Gravatar image for each user based on their email. It also demonstrates rendering HTML elements as the placeholder. </div> </div> ); } }); function arrowRenderer () { return ( <span>+</span> ); } module.exports = UsersField;
src/elements/Reveal/Reveal.js
aabustamante/Semantic-UI-React
import cx from 'classnames' import PropTypes from 'prop-types' import React from 'react' import { customPropTypes, getElementType, getUnhandledProps, META, useKeyOnly, } from '../../lib' import RevealContent from './RevealContent' /** * A reveal displays additional content in place of previous content when activated. */ function Reveal(props) { const { active, animated, children, className, disabled, instant, } = props const classes = cx( 'ui', animated, useKeyOnly(active, 'active'), useKeyOnly(disabled, 'disabled'), useKeyOnly(instant, 'instant'), 'reveal', className, ) const rest = getUnhandledProps(Reveal, props) const ElementType = getElementType(Reveal, props) return <ElementType {...rest} className={classes}>{children}</ElementType> } Reveal._meta = { name: 'Reveal', type: META.TYPES.ELEMENT, } Reveal.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** An active reveal displays its hidden content. */ active: PropTypes.bool, /** An animation name that will be applied to Reveal. */ animated: PropTypes.oneOf([ 'fade', 'small fade', 'move', 'move right', 'move up', 'move down', 'rotate', 'rotate left', ]), /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** A disabled reveal will not animate when hovered. */ disabled: PropTypes.bool, /** An element can show its content without delay. */ instant: PropTypes.bool, } Reveal.Content = RevealContent export default Reveal
App/node_modules/react-native/local-cli/templates/HelloNavigation/views/welcome/WelcomeText.ios.js
Dagers/React-Native-Differential-Updater
'use strict'; import React, { Component } from 'react'; import { StyleSheet, Text, View, } from 'react-native'; export default class WelcomeText extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> This app shows the basics of navigating between a few screens, working with ListView and handling text input. </Text> <Text style={styles.instructions}> Modify any files to get started. For example try changing the file{'\n'}views/welcome/WelcomeText.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: 'white', padding: 20, }, welcome: { fontSize: 20, textAlign: 'center', margin: 16, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 12, }, });
node_modules/@material-ui/core/es/RadioGroup/RadioGroupContext.js
pcclarke/civ-techs
import React from 'react'; /** * @ignore - internal component. */ const RadioGroupContext = React.createContext(); export default RadioGroupContext;
app/javascript/plugins/email_pension/EmailRepresentativeView.js
SumOfUs/Champaign
import React, { Component } from 'react'; import { isEmpty, find, template, merge, each, pick } from 'lodash'; import Input from '../../components/SweetInput/SweetInput'; import Button from '../../components/Button/Button'; import FormGroup from '../../components/Form/FormGroup'; import EmailEditor from '../../components/EmailEditor/EmailEditor'; import SelectTarget from './SelectTarget'; import SelectCountry from '../../components/SelectCountry/SelectCountry'; import { FormattedMessage, injectIntl } from 'react-intl'; import './EmailPensionView.scss'; class EmailRepresentativeView extends Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.defaultTemplateVars = { targets_names: this.props.intl.formatMessage({ id: 'email_tool.template_defaults.target_full_name', }), constituency: this.props.intl.formatMessage({ id: 'email_tool.template_defaults.constituency_name', }), name: this.props.intl.formatMessage({ id: 'email_tool.template_defaults.name', }), }; this.state = { errors: {}, targets: [], name: '', email: '', subject: '', country: '', target_name: '', target_email: '', ...props, }; } validateForm() { const errors = {}; const fields = ['country', 'subject', 'name', 'email', 'targets']; fields.forEach(field => { if (isEmpty(this.state[field])) { const location = `email_tool.form.errors.${field}`; const message = <FormattedMessage id={location} />; errors[field] = message; } }); this.setState({ errors: errors }); return isEmpty(errors); } templateVars() { let vars = pick(this.state, ['name', 'email', 'constituency']); if (this.state.targets) { vars.targets_names = this.state.targets .map( target => `${target.title} ${target.first_name} ${target.last_name}` ) .join(', '); } each(this.defaultTemplateVars, (val, key) => { if (vars[key] === undefined || vars[key] === '') { vars[key] = val; } }); return vars; } onEmailEditorUpdate = ({ subject, body }) => { this.setState(state => ({ ...state, body, subject })); }; errorNotice = () => { if (!isEmpty(this.state.errors)) { return ( <span className="error-msg left-align"> <FormattedMessage id="email_tool.form.errors.message" /> </span> ); } }; onSubmission = e => { e.preventDefault(); const valid = this.validateForm(); if (!valid) return; const payload = { body: this.state.body, country: this.state.country, subject: this.state.subject, from_name: this.state.name, from_email: this.state.email, postcode: this.state.postcode.trim(), plugin_id: this.props.pluginId, }; merge(payload, this.props.formValues); this.setState({ isSubmitting: true }); // FIXME Handle errors $.post(`/api/pages/${this.props.pageId}/pension_emails`, payload).fail( e => { console.log('Unable to send email', e); } ); }; handleTargetSelection(data) { this.setState({ constituency: data.targets[0].constituency, targets: data.targets, postcode: data.postcode, }); } handleChange(data) { this.setState(data); } render() { return ( <div className="email-target"> <div className="email-target-form"> <form onSubmit={e => e.preventDefault()} className="action-form form--big" > <FormGroup> <SelectCountry value={this.state.country} name="country" label={ <FormattedMessage id="email_tool.form.select_country" defaultMessage="Select country (default)" /> } className="form-control" errorMessage={this.state.errors.country} onChange={value => { this.handleChange({ country: value }); }} /> </FormGroup> <SelectTarget handler={this.handleTargetSelection.bind(this)} endpoint={this.props.targetEndpoint} error={this.state.errors.targets} /> <div className="email-target-action"> <h3> <FormattedMessage id="email_tool.section.compose" defaultMessage="Compose Your Email" /> </h3> <FormGroup> <Input name="name" label={ <FormattedMessage id="email_tool.form.your_name" defaultMessage="Your name (default)" /> } value={this.state.name} errorMessage={this.state.errors.name} onChange={value => { this.handleChange({ name: value }); }} /> </FormGroup> <FormGroup> <Input name="email" type="email" label={ <FormattedMessage id="email_tool.form.your_email" defaultMessage="Your email (default)" /> } value={this.state.email} errorMessage={this.state.errors.email} onChange={value => { this.handleChange({ email: value }); }} /> </FormGroup> <EmailEditor errors={this.state.errors} body={this.props.emailBody} header={this.props.emailHeader} footer={this.props.emailFooter} subject={this.props.emailSubject} templateVars={this.templateVars()} onUpdate={this.onEmailEditorUpdate} /> </div> <div className="form__group"> <Button onClick={this.onSubmission} disabled={this.state.isSubmitting} type="button" className="button action-form__submit-button" > <FormattedMessage id="email_tool.form.send_email" defaultMessage="Send email (default)" /> </Button> {this.errorNotice()} </div> </form> </div> </div> ); } } export default injectIntl(EmailRepresentativeView);
src/layouts/ErrorLayout.js
vijayasankar/ML2.0
import React from 'react' import Col from 'react-bootstrap/lib/Col' import Grid from 'react-bootstrap/lib/Grid' import Row from 'react-bootstrap/lib/Row' import Footer from './Footer' import logo from 'components/Header/assets/nibFirstChoice.svg' const cssName = 'error-layout' export const ErrorLayout = ({ main }) => ( <div className={`${cssName}`}> <div className='container-wrapper'> <Grid> <div className={`${cssName}__header`}> <Row className='container'> <Col xsOffset={1} mdOffset={1} xs={10} md={10}> <Row> <Col className='logo-col' xsOffset={1} mdOffset={1} xs={10} md={10}> <Row> <img className={`${cssName}__header-logo`} src={logo} /> </Row> <Row> <main className='error-layout__viewport'> {main} </main> </Row> </Col> </Row> </Col> </Row> </div> </Grid> <Footer /> </div> </div> ) ErrorLayout.propTypes = { main : React.PropTypes.element } export default ErrorLayout
src/svg-icons/image/camera-roll.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCameraRoll = (props) => ( <SvgIcon {...props}> <path d="M14 5c0-1.1-.9-2-2-2h-1V2c0-.55-.45-1-1-1H6c-.55 0-1 .45-1 1v1H4c-1.1 0-2 .9-2 2v15c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2h8V5h-8zm-2 13h-2v-2h2v2zm0-9h-2V7h2v2zm4 9h-2v-2h2v2zm0-9h-2V7h2v2zm4 9h-2v-2h2v2zm0-9h-2V7h2v2z"/> </SvgIcon> ); ImageCameraRoll = pure(ImageCameraRoll); ImageCameraRoll.displayName = 'ImageCameraRoll'; export default ImageCameraRoll;
app/components/icons/Check/index.js
yasserhennawi/yasserhennawi
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'utils/styled-components'; const StyledCheckCircle = styled.svg` fill: ${(props) => props.fill}; `; export default function CheckCircle({ onClick, fill, ...props }) { return ( <StyledCheckCircle {...props} fill={fill} onClick={onClick} width="100%" viewBox="0 0 24 24" > <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" /> </StyledCheckCircle> ); } CheckCircle.propTypes = { fill: PropTypes.string, onClick: PropTypes.func, };
src/client/chat/threadlistitem.react.js
Zycon42/este-chat
import PureComponent from '../components/purecomponent.react'; import React from 'react'; import {Link} from 'react-router'; import {Thread} from './store'; export default class ThreadListItem extends PureComponent { render() { const thread = this.props.thread; const lastMessage = thread.lastMessage; console.log(lastMessage); return ( <li className="thread-list-item"> <Link params={{threadId: thread.id}} to="thread"> <img className="avatar" height="40" src={thread.avatarUrl} /> <div className="thread-info"> <header> <div className="thread-name">{thread.name}</div> <div className="thread-time"> {lastMessage.date.toLocaleTimeString()} </div> </header> <div className="thread-last-message"> {lastMessage.author.name === this.props.userName ? 'You:' : ''} {lastMessage.text} </div> </div> </Link> </li> ); } } ThreadListItem.propTypes = { thread: React.PropTypes.instanceOf(Thread), userName: React.PropTypes.string };
docs/src/components/Playground/Atoms/IconButton/IconButton.js
seek-oss/seek-style-guide
import styles from './IconButton.less'; import React from 'react'; import PropTypes from 'prop-types'; import { PlusIcon, DeleteIcon } from 'seek-style-guide/react'; export default function IconButton({ children, icon }) { return ( <button className={styles.root}> {icon === 'plus' ? <PlusIcon /> : null} {icon === 'delete' ? <DeleteIcon /> : null} {children} </button> ); } IconButton.propTypes = { children: PropTypes.node, icon: PropTypes.oneOf(['plus', 'delete']).isRequired };
frontend/js/components/gallery.js
mcallistersean/b2-issue-tracker
import React from 'react' import Lightbox from 'react-images' class Gallery extends React.Component { constructor () { super(); this.state = { lightboxIsOpen: false, currentImage: 0, }; this.closeLightbox = this.closeLightbox.bind(this); this.gotoNext = this.gotoNext.bind(this); this.gotoPrevious = this.gotoPrevious.bind(this); this.gotoImage = this.gotoImage.bind(this); this.handleClickImage = this.handleClickImage.bind(this); this.openLightbox = this.openLightbox.bind(this); } openLightbox (index, event) { event.preventDefault(); this.setState({ currentImage: index, lightboxIsOpen: true, }); } closeLightbox () { this.setState({ currentImage: 0, lightboxIsOpen: false, }); } gotoPrevious () { this.setState({ currentImage: this.state.currentImage - 1, }); } gotoNext () { this.setState({ currentImage: this.state.currentImage + 1, }); } gotoImage (index) { this.setState({ currentImage: index, }); } handleClickImage () { if (this.state.currentImage === this.props.images.length - 1) return; this.gotoNext(); } renderGallery () { const { images } = this.props; if (!images) return; const gallery = images.map((obj, i) => { return ( <a href={obj.image} key={i} onClick={(e) => this.openLightbox(i, e)} > <img src={obj.thumbnail_url} /> </a> ); }); return ( <div> {gallery} </div> ); } render () { let images = this.props.images.map((image) => { return { src: image.image } }); return ( <div className="gallery"> {this.renderGallery()} <Lightbox currentImage={this.state.currentImage} images={images} isOpen={this.state.lightboxIsOpen} onClickImage={this.handleClickImage} onClickNext={this.gotoNext} onClickPrev={this.gotoPrevious} onClickThumbnail={this.gotoImage} onClose={this.closeLightbox} showThumbnails={this.props.showThumbnails} theme={this.props.theme} /> </div> ); } }; export default Gallery;
app/containers/LanguageProvider/index.js
rodrigoTrespalacios/project-bank
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { selectLocale } from './selectors'; export class LanguageProvider extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ); } } LanguageProvider.propTypes = { locale: React.PropTypes.string, messages: React.PropTypes.object, children: React.PropTypes.element.isRequired, }; const mapStateToProps = createSelector( selectLocale(), (locale) => ({ locale }) ); function mapDispatchToProps(dispatch) { return { dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider);
packages/node_modules/@ciscospark/react-component-new-messages-separator/src/index.js
Altocloud/alto-react-ciscospark
import React from 'react'; import PropTypes from 'prop-types'; import ListSeparator from '@ciscospark/react-component-list-separator'; function NewMessageSeparator({message}) { return ( <div> <ListSeparator isInformative primaryText={message} /> </div> ); } NewMessageSeparator.propTypes = { message: PropTypes.string.isRequired }; export default NewMessageSeparator;
src/ModalHeader.js
asiniy/react-bootstrap
import React from 'react'; import classNames from 'classnames'; class ModalHeader extends React.Component { render() { return ( <div {...this.props} className={classNames(this.props.className, this.props.modalClassName)}> { this.props.closeButton && <button className='close' onClick={this.props.onHide}> <span aria-hidden="true"> &times; </span> </button> } { this.props.children } </div> ); } } //used in liue of parent contexts right now to auto wire the close button ModalHeader.__isModalHeader = true; ModalHeader.propTypes = { /** * The 'aria-label' attribute is used to define a string that labels the current element. * It is used for Assistive Technology when the label text is not visible on screen. */ 'aria-label': React.PropTypes.string, /** * A css class applied to the Component */ modalClassName: React.PropTypes.string, /** * Specify whether the Component should contain a close button */ closeButton: React.PropTypes.bool, /** * A Callback fired when the close button is clicked. If used directly inside a Modal component, the onHide will automatically * be propagated up to the parent Modal `onHide`. */ onHide: React.PropTypes.func }; ModalHeader.defaultProps = { 'aria-label': 'Close', modalClassName: 'modal-header', closeButton: false }; export default ModalHeader;
packages/mineral-ui-icons/src/IconLocalCafe.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 IconLocalCafe(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M20 3H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm0 5h-2V5h2v3zM2 21h18v-2H2v2z"/> </g> </Icon> ); } IconLocalCafe.displayName = 'IconLocalCafe'; IconLocalCafe.category = 'maps';
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js
Nedomas/react-router
/*globals COURSES:true */ import React from 'react' import { Link } from 'react-router' class Sidebar extends React.Component { render() { let { assignments } = COURSES[this.props.params.courseId] return ( <div> <h3>Sidebar Assignments</h3> <ul> {assignments.map(assignment => ( <li key={assignment.id}> <Link to={`/course/${this.props.params.courseId}/assignments/${assignment.id}`}> {assignment.title} </Link> </li> ))} </ul> </div> ) } } export default Sidebar
packages/wix-style-react/src/FloatingNotification/test/FloatingNotification.visual.js
wix/wix-style-react
import React from 'react'; import { storiesOf } from '@storybook/react'; import StatusComplete from 'wix-ui-icons-common/StatusComplete'; import { TYPES } from '../constants'; import FloatingNotification from '..'; const LONG_TEXT = 'all work and no play makes jack a dull boy '.repeat(2); const defaultProps = { text: 'Some content text', prefixIcon: <StatusComplete />, textButtonProps: { label: 'Trash' }, buttonProps: { label: 'Undo' }, }; const types = Object.values(TYPES); const test = (it, props) => ({ it, props }); const tests = [ { describe: 'Types', its: types.map(type => test(type, { type })), }, { describe: 'Long text', its: [ { it: 'example', props: { text: LONG_TEXT, }, }, ], }, { describe: 'Full width prop', its: [ { it: 'example', props: { fullWidth: true, }, }, ], }, ]; tests.forEach(({ describe, its }) => { its.forEach(({ it, props }) => { storiesOf( `FloatingNotification${describe ? '/' + describe : ''}`, module, ).add(it, () => <FloatingNotification {...defaultProps} {...props} />); }); });
src/svg-icons/communication/ring-volume.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationRingVolume = (props) => ( <SvgIcon {...props}> <path d="M23.71 16.67C20.66 13.78 16.54 12 12 12 7.46 12 3.34 13.78.29 16.67c-.18.18-.29.43-.29.71 0 .28.11.53.29.71l2.48 2.48c.18.18.43.29.71.29.27 0 .52-.11.7-.28.79-.74 1.69-1.36 2.66-1.85.33-.16.56-.5.56-.9v-3.1c1.45-.48 3-.73 4.6-.73s3.15.25 4.6.72v3.1c0 .39.23.74.56.9.98.49 1.87 1.12 2.66 1.85.18.18.43.28.7.28.28 0 .53-.11.71-.29l2.48-2.48c.18-.18.29-.43.29-.71 0-.27-.11-.52-.29-.7zM21.16 6.26l-1.41-1.41-3.56 3.55 1.41 1.41s3.45-3.52 3.56-3.55zM13 2h-2v5h2V2zM6.4 9.81L7.81 8.4 4.26 4.84 2.84 6.26c.11.03 3.56 3.55 3.56 3.55z"/> </SvgIcon> ); CommunicationRingVolume = pure(CommunicationRingVolume); CommunicationRingVolume.displayName = 'CommunicationRingVolume'; CommunicationRingVolume.muiName = 'SvgIcon'; export default CommunicationRingVolume;
app/static/scripts/user/authView/main.js
joshleeb/WordpressPylon
import UserLoginForm from './loginForm/main.js'; import UserSignupForm from './signupForm/main.js'; import React from 'react'; require('./styles.scss'); export default class UserAuthView extends React.Component { constructor(props) { super(props); this.state = { mode: props.mode || 'signup' }; } toggleMode = () => { this.setState({ mode: this.state.mode === 'signup' ? 'login' : 'signup' }); } render() { let view = { signup: { form: <UserSignupForm />, title: 'Create an account', toggleText: 'Login instead' }, login: { form: <UserLoginForm />, title: 'Login to your account', toggleText: 'Sign up instead' } }[this.state.mode]; return ( <div id="userAuthView"> <h3 className="title">{view.title}</h3> <h5 className="toggleText"><a onClick={this.toggleMode}> {view.toggleText} </a></h5> {view.form} </div> ); } }
app/app.js
theJian/hn-FrontPage
import $ from 'jquery'; import React from 'react'; import { render } from 'react-dom'; import NewsList from './NewsList.js'; import './app.css'; function get(url) { return Promise.resolve($.ajax(url)); } get('https://hacker-news.firebaseio.com/v0/topstories.json').then( function(stories) { return Promise.all(stories.slice(0, 30).map(itemId => get('https://hacker-news.firebaseio.com/v0/item/' + itemId + '.json'))); }).then(function(items) { render(<NewsList items={items} />, $('#content')[0]); }).catch(function(err) { console.log('error occur', err); });
src/js/pages/Sobre.js
diegovilarinho/wp-react-portfolio-site
import React from 'react'; export default class Sobre extends React.Component { render() { return ( <h1 className="title">Quem Somos</h1> ); } }
src/components/game/board/drop-zone.js
aautem/aa
import React from 'react'; import PropTypes from 'prop-types'; import { Row } from 'react-native-easy-grid'; import DropButton from './drop-button'; export default class DropZone extends React.Component { render() { if (!this.props.game.roomName) { return null; } const dropButtons = []; for (let count = 0; count < this.props.game.boardSize; count ++) { dropButtons.push( <DropButton key={`drop-btn-${count}`} colId={count} /> ); } return ( <Row size={2/14} style={{ paddingTop: 5 }}> { dropButtons } </Row> ); } } DropZone.propTypes = { game: PropTypes.object, };
src/parser/shared/modules/items/bfa/raids/crucibleofstorms/HarbingersInscrutableWill.js
sMteX/WoWAnalyzer
import React from 'react'; import { formatNumber, formatPercentage } from 'common/format'; import SPELLS from 'common/SPELLS/index'; import ITEMS from 'common/ITEMS/index'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import ItemStatistic from 'interface/statistics/ItemStatistic'; import ItemDamageDone from 'interface/others/ItemDamageDone'; import BoringItemValueText from 'interface/statistics/components/BoringItemValueText'; import UptimeIcon from 'interface/icons/Uptime'; import { TooltipElement } from 'common/Tooltip'; import ItemLink from 'common/ItemLink'; import SpellLink from 'common/SpellLink'; //Example Log: https://www.warcraftlogs.com/reports/KkB8jL1HpwxV7NtT#fight=4&source=136 class HarbingersInscrutableWill extends Analyzer { hits = 0; silences = 0; damage = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrinket(ITEMS.HARBINGERS_INSCRUTABLE_WILL.id); if(!this.active) { return; } this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.OBLIVION_SPEAR_DAMAGE), this._damage); this.addEventListener(Events.applydebuff.to(SELECTED_PLAYER).spell(SPELLS.OBLIVION_SPEAR_SILENCE), this._silence); } _damage(event) { this.hits += 1; this.damage += (event.amount || 0) + (event.absorbed || 0); } _silence(event) { this.silences += 1; } get silenceUptime() { return this.selectedCombatant.getBuffUptime(SPELLS.OBLIVION_SPEAR_SILENCE.id); } statistic() { return ( <ItemStatistic size="flexible" > <BoringItemValueText item={ITEMS.HARBINGERS_INSCRUTABLE_WILL}> <TooltipElement content={`Damage done: ${formatNumber(this.damage)}`}> <ItemDamageDone amount={this.damage} /> </TooltipElement> <TooltipElement content={`Silenced ${this.silences} time${this.silences !== 1 && 's'}`}> <UptimeIcon /> {(this.silenceUptime / 1000).toFixed(0)} s <small>spent silenced</small> </TooltipElement> </BoringItemValueText> </ItemStatistic> ); } get suggestedSilences() { return { actual: this.silences / this.hits, isGreaterThanOrEqual: { minor: 0.10, average: 0.20, major: 0.25, }, style: 'number', }; } suggestions(when) { when(this.suggestedSilences).addSuggestion((suggest, actual, recommended) => { return suggest( <> You are getting silenced by <SpellLink id={SPELLS.OBLIVION_SPEAR_SILENCE.id} />. Try to dodge <ItemLink id={ITEMS.HARBINGERS_INSCRUTABLE_WILL.id} />'s spears to avoid the silence. </> ) .icon(ITEMS.HARBINGERS_INSCRUTABLE_WILL.icon) .actual(`You got silenced by ${formatPercentage(actual)}% of spears.`) .recommended(`<10% is recommended`); }); } } export default HarbingersInscrutableWill;
src/with-theme.js
paypal/glamorous
import React from 'react' import {CHANNEL} from './constants' import {PropTypes} from './react-compat' function generateWarningMessage(Comp) { const componentName = Comp.displayName || Comp.name || 'FunctionComponent' // eslint-disable-next-line max-len return `glamorous warning: Expected component called "${componentName}" which uses withTheme to be within a ThemeProvider but none was found.` } export default function withTheme( ComponentToTheme, {noWarn = false, createElement = true} = {}, ) { class ThemedComponent extends React.Component { static propTypes = { theme: PropTypes.object, } warned = noWarn state = {theme: {}} setTheme = theme => this.setState({theme}) // eslint-disable-next-line complexity componentWillMount() { if (!this.context[CHANNEL]) { if (process.env.NODE_ENV !== 'production' && !this.warned) { this.warned = true // eslint-disable-next-line no-console console.warn(generateWarningMessage(ComponentToTheme)) } } const {theme} = this.props if (this.context[CHANNEL]) { // if a theme is provided via props, // it takes precedence over context this.setTheme(theme ? theme : this.context[CHANNEL].getState()) } else { this.setTheme(theme || {}) } } componentWillReceiveProps(nextProps) { if (this.props.theme !== nextProps.theme) { this.setTheme(nextProps.theme) } } componentDidMount() { if (this.context[CHANNEL] && !this.props.theme) { // subscribe to future theme changes this.subscriptionId = this.context[CHANNEL].subscribe(this.setTheme) } } componentWillUnmount() { // cleanup subscription this.subscriptionId && this.context[CHANNEL].unsubscribe(this.subscriptionId) } render() { if (createElement) { return <ComponentToTheme {...this.props} {...this.state} /> } else { // this allows us to effectively use the GlamorousComponent // as our `render` method without going through lifecycle hooks. // Also allows us to forward the context in the scenario where // a user wants to add more context. // eslint-disable-next-line babel/new-cap return ComponentToTheme.call( this, {...this.props, ...this.state}, this.context, ) } } } const defaultContextTypes = { [CHANNEL]: PropTypes.object, } let userDefinedContextTypes = null // configure the contextTypes to be settable by the user, // however also retaining the glamorous channel. Object.defineProperty(ThemedComponent, 'contextTypes', { enumerable: true, configurable: true, set(value) { userDefinedContextTypes = value }, get() { // if the user has provided a contextTypes definition, // merge the default context types with the provided ones. if (userDefinedContextTypes) { return { ...defaultContextTypes, ...userDefinedContextTypes, } } return defaultContextTypes }, }) return ThemedComponent }
src/svg-icons/communication/location-on.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationLocationOn = (props) => ( <SvgIcon {...props}> <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/> </SvgIcon> ); CommunicationLocationOn = pure(CommunicationLocationOn); CommunicationLocationOn.displayName = 'CommunicationLocationOn'; CommunicationLocationOn.muiName = 'SvgIcon'; export default CommunicationLocationOn;
assets/jqwidgets/demos/react/app/maskedinput/events/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxMaskedInput from '../../../jqwidgets-react/react_jqxmaskedinput.js'; import JqxPanel from '../../../jqwidgets-react/react_jqxpanel.js'; class App extends React.Component { componentDidMount() { this.refs.myMaskedInput.on('change', (event) => { let value = this.refs.myMaskedInput.val(); this.refs.myPanel.clearcontent(); this.refs.myPanel.prepend('<div style="margin-top: 5px;">Value: ' + value + '</div>'); }); } render() { return ( <div> <div style={{ fontSize: 13, fontFamily: 'Verdana', marginTop: 10 }}> Phone Number </div> <JqxMaskedInput ref='myMaskedInput' style={{ marginTop: 3 }} width={250} height={35} mask={'(###)###-####'} /> <div style={{ marginLeft: 0, marginTop: 20 }}> <div> <span>Events:</span> <JqxPanel ref='myPanel' style={{ border: 'none' }} width={300} height={250} /> </div> </div> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/components/ProposalInput/Navigation.js
nambawan/g-old
import React from 'react'; import PropTypes from 'prop-types'; import { WizardContext } from '../Wizard/wizard-context'; import Button from '../Button'; import Box from '../Box'; const Navigation = ({ onSubmit }) => ( <WizardContext.Consumer> {({ next, previous, step, steps }) => { const onNextClick = () => { const res = onSubmit(); if (res) { next(); } }; return ( <Box> {steps.indexOf(step) > 0 && steps.indexOf(step) < steps.length - 1 && ( <Button label="Back" onClick={previous} /> )} {steps.indexOf(step) < steps.length - 2 && ( <Button primary label="Next" onClick={next} /> )} {steps.indexOf(step) === steps.length - 2 && ( <Button primary label="Submit" onClick={onNextClick} /> )} </Box> ); }} </WizardContext.Consumer> ); Navigation.propTypes = { onSubmit: PropTypes.func.isRequired, }; export default Navigation;
src/components/Header/Header.js
tarixgit/test
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Header.css'; import Navigation from '../Navigation'; class Header extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <Navigation /> <div className={s.banner}> <p className={s.bannerDesc}>Українська греко-католицька церква св. Миколая</p> </div> </div> </div> ); } } export default withStyles(s)(Header);
Gallery-in-React/test/helpers/shallowRenderHelper.js
brilliantyy/React-Native
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
static/src/components/DetermineAuth.js
dternyak/React-Redux-Flask
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as actionCreators from '../actions/auth'; function mapStateToProps(state) { return { token: state.auth.token, userName: state.auth.userName, isAuthenticated: state.auth.isAuthenticated, }; } function mapDispatchToProps(dispatch) { return bindActionCreators(actionCreators, dispatch); } export function DetermineAuth(Component) { class AuthenticatedComponent extends React.Component { componentWillMount() { this.checkAuth(); this.state = { loaded_if_needed: false, }; } componentWillReceiveProps(nextProps) { this.checkAuth(nextProps); } checkAuth(props = this.props) { if (!props.isAuthenticated) { const token = localStorage.getItem('token'); if (token) { fetch('/api/is_token_valid', { method: 'post', credentials: 'include', headers: { 'Accept': 'application/json', // eslint-disable-line quote-props 'Content-Type': 'application/json', }, body: JSON.stringify({ token }), }) .then(res => { if (res.status === 200) { this.props.loginUserSuccess(token); this.setState({ loaded_if_needed: true, }); } }); } } else { this.setState({ loaded_if_needed: true, }); } } render() { return ( <div> {this.state.loaded_if_needed ? <Component {...this.props} /> : null } </div> ); } } AuthenticatedComponent.propTypes = { loginUserSuccess: React.PropTypes.func, }; return connect(mapStateToProps, mapDispatchToProps)(AuthenticatedComponent); }
examples/universal/server/server.js
naoishii/ohk2016C
/* eslint-disable no-console, no-use-before-define */ import path from 'path' import Express from 'express' import qs from 'qs' import webpack from 'webpack' import webpackDevMiddleware from 'webpack-dev-middleware' import webpackHotMiddleware from 'webpack-hot-middleware' import webpackConfig from '../webpack.config' import React from 'react' import { renderToString } from 'react-dom/server' import { Provider } from 'react-redux' import configureStore from '../common/store/configureStore' import App from '../common/containers/App' import { fetchCounter } from '../common/api/counter' const app = new Express() const port = 3000 // Use this middleware to set up hot module reloading via webpack. const compiler = webpack(webpackConfig) app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath })) app.use(webpackHotMiddleware(compiler)) // This is fired every time the server side receives a request app.use(handleRender) function handleRender(req, res) { // Query our mock API asynchronously fetchCounter(apiResult => { // Read the counter from the request, if provided const params = qs.parse(req.query) const counter = parseInt(params.counter, 10) || apiResult || 0 // Compile an initial state const initialState = { counter } // Create a new Redux store instance const store = configureStore(initialState) // Render the component to a string const html = renderToString( <Provider store={store}> <App /> </Provider> ) // Grab the initial state from our Redux store const finalState = store.getState() // Send the rendered page back to the client res.send(renderFullPage(html, finalState)) }) } function renderFullPage(html, initialState) { return ` <!doctype html> <html> <head> <title>Redux Universal Example</title> </head> <body> <div id="app">${html}</div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)} </script> <script src="/static/bundle.js"></script> </body> </html> ` } app.listen(port, (error) => { if (error) { console.error(error) } else { console.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`) } })
frontend/src/Settings/Profiles/Profiles.js
lidarr/Lidarr
import React, { Component } from 'react'; import { DndProvider } from 'react-dnd-multi-backend'; import HTML5toTouch from 'react-dnd-multi-backend/dist/esm/HTML5toTouch'; import PageContent from 'Components/Page/PageContent'; import PageContentBody from 'Components/Page/PageContentBody'; import SettingsToolbarConnector from 'Settings/SettingsToolbarConnector'; import DelayProfilesConnector from './Delay/DelayProfilesConnector'; import MetadataProfilesConnector from './Metadata/MetadataProfilesConnector'; import QualityProfilesConnector from './Quality/QualityProfilesConnector'; import ReleaseProfilesConnector from './Release/ReleaseProfilesConnector'; // Only a single DragDrop Context can exist so it's done here to allow editing // quality profiles and reordering delay profiles to work. class Profiles extends Component { // // Render render() { return ( <PageContent title="Profiles"> <SettingsToolbarConnector showSave={false} /> <PageContentBody> <DndProvider options={HTML5toTouch}> <QualityProfilesConnector /> <MetadataProfilesConnector /> <DelayProfilesConnector /> <ReleaseProfilesConnector /> </DndProvider> </PageContentBody> </PageContent> ); } } export default Profiles;
common/components/Search.js
alexdvance/the-watcher
import { provideHooks } from 'redial' import React from 'react' import { connect } from 'react-redux' import { searchMedia } from '../routes/Home/actions' import { displaySearchResults } from '../routes/Home/reducer' import axios from 'axios'; import { StyleSheet, css } from 'aphrodite' var searchResults = []; function typeTerm(e) { console.log('key', e.key) console.log('target', e.target.value) return axios.get(`http://www.omdbapi.com/?s=${e.target.value}`) .then(res => { console.log('resource', res) searchResults = []; res.data.Search.forEach(function(searchResult, i) { // add to list }); }) // dispatch(searchMedia(term)); } function search() { console.log('kill me'); } const redial = { fetch: ({ dispatch, params: { term } }) => dispatch(searchMedia(term)) } const mapStateToProps = state => displaySearchResults(state) const Search = () => ( <div>Fuck me daddy <input type="text" placeholder="Search for a movie or TV show" onKeyUp={typeTerm} /> <input type="button" value="blub" onClick={search} /> {searchResults} </div> ) const styles = StyleSheet.create({ root: { maxWidth: 700, color: '#000', margin: '2rem auto', padding: '0 1rem' }, title: { color: '#000', maxWidth: 300, fontWeight: 'bold', fontSize: 56 }, footer: { margin: '4rem auto', textAlign: 'center', color: '#b7b7b7' }, footerLink: { display: 'inline-block', color: '#000', textDecoration: 'none' } }) // export default Search export default connect(mapStateToProps)(Search)
app/components/presentation/BookingDetails.js
PHPiotr/phpiotr4
import React from 'react'; import PropTypes from 'prop-types'; import {TableCell, TableRow} from 'material-ui/Table'; import List, {ListItem, ListItemText} from 'material-ui/List'; import {withRouter} from 'react-router-dom'; import formatDate from '../../utils/formatDateUtil'; import getPrice from '../../utils/formatPriceUtil'; const BookingDetails = ({label, details, isHostel, offset, history}) => { if (!details.length) { return null; } const style = {paddingLeft: 0, paddingRight: 0}; const handleClick = id => history.push(`/bookings/${label}/${id}`); const rowStyle = {cursor: 'pointer'}; if (isHostel) { return details.map((row, i) => { const checkIn = formatDate(row.checkin_date); const checkOut = formatDate(row.checkout_date); return ( <TableRow style={rowStyle} key={`${i}hostel`} onClick={() => handleClick(row._id)}> <TableCell> <List> <ListItem style={style}> <ListItemText primary={`${i + 1 + (offset || 0)}. ${checkIn} - ${checkOut}`} secondary={row.hostel_name} /> </ListItem> </List> </TableCell> <TableCell> <List> <ListItem style={style}> <ListItemText primary={`£${getPrice(row.price)}`} secondary={row.booking_number} /> </ListItem> </List> </TableCell> </TableRow> ); }); } return details.map((row, i) => { const departDate = formatDate(row.departure_date); const returnDate = row.is_return ? ' - ' + formatDate(row.return_departure_date) : ''; return ( <TableRow style={rowStyle} key={i} onClick={() => handleClick(row._id)}> <TableCell> <List> <ListItem style={style}> <ListItemText primary={`${i + 1 + (offset || 0)}. ${departDate}${returnDate}`} secondary={`${row.from} - ${row.to}`} /> </ListItem> </List> </TableCell> <TableCell> <List> <ListItem style={style}> <ListItemText primary={`£${getPrice(row.price)}`} secondary={row.booking_number || row.confirmation_code || ''} /> </ListItem> </List> </TableCell> </TableRow> ); }); }; BookingDetails.propTypes = { details: PropTypes.array.isRequired, isHostel: PropTypes.bool, label: PropTypes.string.isRequired, }; BookingDetails.defaultProps = { isHostel: false, }; BookingDetails.displayName = 'BookingDetails'; export default withRouter(BookingDetails);
src/Main/PlayerSelectorHeader.js
enragednuke/WoWAnalyzer
// Note: Based on PlayerSelecter import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { getPlayerName } from 'selectors/url/report'; import SelectorBase from './SelectorBase'; import PlayerSelectionList from './PlayerSelectionList'; class PlayerSelectorHeader extends SelectorBase { static propTypes = { selectedPlayerName: PropTypes.string.isRequired, }; render() { const { selectedPlayerName, ...others } = this.props; delete others.dispatch; return ( <div ref={this.setRef} {...others}> <a onClick={this.handleClick}>{selectedPlayerName}</a> {this.state.show && ( <span className="selectorHeader"> <div className="panel"> <div className="panel-heading"> <h2>Select the player you wish to analyze</h2> </div> <div className="panel-body" style={{ padding: 0 }} onClick={this.handleClick}> <PlayerSelectionList /> </div> </div> </span> )} </div> ); } } const mapStateToProps = state => ({ selectedPlayerName: getPlayerName(state), }); export default connect( mapStateToProps )(PlayerSelectorHeader);
node_modules/rc-trigger/es/Popup.js
yhx0634/foodshopfront
import _extends from 'babel-runtime/helpers/extends'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import Align from 'rc-align'; import Animate from 'rc-animate'; import PopupInner from './PopupInner'; import LazyRenderBox from './LazyRenderBox'; import { saveRef } from './utils'; var Popup = function (_Component) { _inherits(Popup, _Component); function Popup(props) { _classCallCheck(this, Popup); var _this = _possibleConstructorReturn(this, (Popup.__proto__ || Object.getPrototypeOf(Popup)).call(this, props)); _initialiseProps.call(_this); _this.savePopupRef = saveRef.bind(_this, 'popupInstance'); _this.saveAlignRef = saveRef.bind(_this, 'alignInstance'); return _this; } _createClass(Popup, [{ key: 'componentDidMount', value: function componentDidMount() { this.rootNode = this.getPopupDomNode(); } }, { key: 'getPopupDomNode', value: function getPopupDomNode() { return ReactDOM.findDOMNode(this.popupInstance); } }, { key: 'getMaskTransitionName', value: function getMaskTransitionName() { var props = this.props; var transitionName = props.maskTransitionName; var animation = props.maskAnimation; if (!transitionName && animation) { transitionName = props.prefixCls + '-' + animation; } return transitionName; } }, { key: 'getTransitionName', value: function getTransitionName() { var props = this.props; var transitionName = props.transitionName; if (!transitionName && props.animation) { transitionName = props.prefixCls + '-' + props.animation; } return transitionName; } }, { key: 'getClassName', value: function getClassName(currentAlignClassName) { return this.props.prefixCls + ' ' + this.props.className + ' ' + currentAlignClassName; } }, { key: 'getPopupElement', value: function getPopupElement() { var savePopupRef = this.savePopupRef, props = this.props; var align = props.align, style = props.style, visible = props.visible, prefixCls = props.prefixCls, destroyPopupOnHide = props.destroyPopupOnHide; var className = this.getClassName(this.currentAlignClassName || props.getClassNameFromAlign(align)); var hiddenClassName = prefixCls + '-hidden'; if (!visible) { this.currentAlignClassName = null; } var newStyle = _extends({}, style, this.getZIndexStyle()); var popupInnerProps = { className: className, prefixCls: prefixCls, ref: savePopupRef, onMouseEnter: props.onMouseEnter, onMouseLeave: props.onMouseLeave, style: newStyle }; if (destroyPopupOnHide) { return React.createElement( Animate, { component: '', exclusive: true, transitionAppear: true, transitionName: this.getTransitionName() }, visible ? React.createElement( Align, { target: this.getTarget, key: 'popup', ref: this.saveAlignRef, monitorWindowResize: true, align: align, onAlign: this.onAlign }, React.createElement( PopupInner, _extends({ visible: true }, popupInnerProps), props.children ) ) : null ); } return React.createElement( Animate, { component: '', exclusive: true, transitionAppear: true, transitionName: this.getTransitionName(), showProp: 'xVisible' }, React.createElement( Align, { target: this.getTarget, key: 'popup', ref: this.saveAlignRef, monitorWindowResize: true, xVisible: visible, childrenProps: { visible: 'xVisible' }, disabled: !visible, align: align, onAlign: this.onAlign }, React.createElement( PopupInner, _extends({ hiddenClassName: hiddenClassName }, popupInnerProps), props.children ) ) ); } }, { key: 'getZIndexStyle', value: function getZIndexStyle() { var style = {}; var props = this.props; if (props.zIndex !== undefined) { style.zIndex = props.zIndex; } return style; } }, { key: 'getMaskElement', value: function getMaskElement() { var props = this.props; var maskElement = void 0; if (props.mask) { var maskTransition = this.getMaskTransitionName(); maskElement = React.createElement(LazyRenderBox, { style: this.getZIndexStyle(), key: 'mask', className: props.prefixCls + '-mask', hiddenClassName: props.prefixCls + '-mask-hidden', visible: props.visible }); if (maskTransition) { maskElement = React.createElement( Animate, { key: 'mask', showProp: 'visible', transitionAppear: true, component: '', transitionName: maskTransition }, maskElement ); } } return maskElement; } }, { key: 'render', value: function render() { return React.createElement( 'div', null, this.getMaskElement(), this.getPopupElement() ); } }]); return Popup; }(Component); Popup.propTypes = { visible: PropTypes.bool, style: PropTypes.object, getClassNameFromAlign: PropTypes.func, onAlign: PropTypes.func, getRootDomNode: PropTypes.func, onMouseEnter: PropTypes.func, align: PropTypes.any, destroyPopupOnHide: PropTypes.bool, className: PropTypes.string, prefixCls: PropTypes.string, onMouseLeave: PropTypes.func }; var _initialiseProps = function _initialiseProps() { var _this2 = this; this.onAlign = function (popupDomNode, align) { var props = _this2.props; var currentAlignClassName = props.getClassNameFromAlign(align); // FIX: https://github.com/react-component/trigger/issues/56 // FIX: https://github.com/react-component/tooltip/issues/79 if (_this2.currentAlignClassName !== currentAlignClassName) { _this2.currentAlignClassName = currentAlignClassName; popupDomNode.className = _this2.getClassName(currentAlignClassName); } props.onAlign(popupDomNode, align); }; this.getTarget = function () { return _this2.props.getRootDomNode(); }; }; export default Popup;
src/js/components/ContentBlocks/BlockCarousel/BlockCarouselWireframe.js
grommet/grommet-cms-boilerplate
import React from 'react'; import Box from 'grommet/components/Box'; export default function BlockCarouselWireframe() { return ( <Box pad={{ between: 'small' }} direction="row"> <Box basis="1/4" colorIndex="accent-3" pad={{ horizontal: 'small', vertical: 'large' }} /> <Box basis="1/2" colorIndex="accent-3" pad={{ horizontal: 'small', vertical: 'large' }} /> <Box basis="1/4" colorIndex="accent-3" pad={{ horizontal: 'small', vertical: 'large' }} /> </Box> ); }
client/scripts/index.react.js
nevillegallimore/weekend-countdown
// import external dependencies import React from 'react'; import { render } from 'react-dom'; // import internal dependencies import WeekendCountdown from './containers/weekend-countdown'; //////////////////////////////////////////////////////////////////////////////////////////////////// const container = document.getElementById('weekend-countdown'); render(<WeekendCountdown />, container);
client/src/index.js
tiagofabre/koa2-react
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render(<App />, document.querySelector('#root'));
src/components/google_map.js
yihan940211/WTFSIGTP
/* * @Author: guangled * @Date: 2017-03-25 13:43:16 * @Last Modified by: guangled * @Last Modified time: 2017-03-26 08:51:30 */ import React, { Component } from 'react'; import MainButton from './main_button'; class GoogleMap extends Component { constructor() { super(); this.state = { lat: 0, lng: 0, map: null, directionsDisplay: null, arr :[] } this.draw = this.draw.bind(this); } draw(lat, lng){ //this.marker = new google.maps.Marker({position: this.state, map: this.state.map}); var start = new google.maps.LatLng(this.state.lat, this.state.lng); var end = new google.maps.LatLng(lat, lng); //console.log(this.props.lat, this.props.lon); //var directionsDisplay = new google.maps.DirectionsRenderer();// also, constructor can get "DirectionsRendererOptions" object var tempDirectionsDisplay = this.state.directionsDisplay; tempDirectionsDisplay.setMap(null); tempDirectionsDisplay.setMap(this.state.map); // map should be already initialized. var request = { origin : start, destination : end, travelMode : google.maps.TravelMode.DRIVING }; var directionsService = new google.maps.DirectionsService(); directionsService.route(request, function(response, status){ if (status == google.maps.DirectionsStatus.OK) { tempDirectionsDisplay.setDirections(response); console.log(response.routes[0].legs[0].distance.text); console.log(response.routes[0].legs[0].duration.text); //this.state.arr = [response.routes[0].legs[0].distance.text,response.routes[0].legs[0].duration.text]; } }); // } componentDidMount() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition((position) => { this.pos = { lat: position.coords.latitude, lng: position.coords.longitude }; this.setState({lat: this.pos.lat, lng:this.pos.lng}) this.map = new google.maps.Map(this.refs.map, { center: {lat: this.state.lat, lng: this.state.lng}, zoom:12 }); var directionsDisplay = new google.maps.DirectionsRenderer(); this.setState({map: this.map}); this.setState({directionsDisplay: directionsDisplay}); //this.draw(this.pos.lat, this.pos.lng); }, () => { console.log('navigator disabled'); }); } } render() { // this.refs.map return ( <div className='mainb'> <div ref="map" className="map"> </div> <MainButton drawb = {this.draw} getFirstEvent = {this.getFirstEvent} /> </div> ) } } export default GoogleMap;