path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/svg-icons/places/smoke-free.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesSmokeFree = (props) => ( <SvgIcon {...props}> <path d="M2 6l6.99 7H2v3h9.99l7 7 1.26-1.25-17-17zm18.5 7H22v3h-1.5zM18 13h1.5v3H18zm.85-8.12c.62-.61 1-1.45 1-2.38h-1.5c0 1.02-.83 1.85-1.85 1.85v1.5c2.24 0 4 1.83 4 4.07V12H22V9.92c0-2.23-1.28-4.15-3.15-5.04zM14.5 8.7h1.53c1.05 0 1.97.74 1.97 2.05V12h1.5v-1.59c0-1.8-1.6-3.16-3.47-3.16H14.5c-1.02 0-1.85-.98-1.85-2s.83-1.75 1.85-1.75V2c-1.85 0-3.35 1.5-3.35 3.35s1.5 3.35 3.35 3.35zm2.5 7.23V13h-2.93z"/> </SvgIcon> ); PlacesSmokeFree = pure(PlacesSmokeFree); PlacesSmokeFree.displayName = 'PlacesSmokeFree'; PlacesSmokeFree.muiName = 'SvgIcon'; export default PlacesSmokeFree;
src/App.js
leeppolis/bookmarks
import React, { Component } from 'react'; import './App.css'; import Header from './Header.js'; import Body from './Body.js'; import Footer from './Footer.js'; class App extends Component { render() { return ( <div className="App"> <Header /> <Body /> <Footer /> </div> ); } } export default App;
src/svg-icons/image/filter-2.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter2 = (props) => ( <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zm-4-4h-4v-2h2c1.1 0 2-.89 2-2V7c0-1.11-.9-2-2-2h-4v2h4v2h-2c-1.1 0-2 .89-2 2v4h6v-2z"/> </SvgIcon> ); ImageFilter2 = pure(ImageFilter2); ImageFilter2.displayName = 'ImageFilter2'; ImageFilter2.muiName = 'SvgIcon'; export default ImageFilter2;
src/tile/FeaturedTile.js
kosiakMD/react-native-elements
import PropTypes from 'prop-types'; import React from 'react'; import { TouchableOpacity, Text as NativeText, View, Image, StyleSheet, Dimensions, } from 'react-native'; import Text from '../text/Text'; import Icon from '../icons/Icon'; import ViewPropTypes from '../config/ViewPropTypes'; const FeaturedTile = props => { const { title, icon, caption, imageSrc, containerStyle, imageContainerStyle, overlayContainerStyle, iconContainerStyle, titleStyle, captionStyle, ...attributes } = props; let { width, height } = props; if (!width) { width = Dimensions.get('window').width; } if (!height) { height = width * 0.8; } const styles = StyleSheet.create({ container: { width, height, }, imageContainer: { alignItems: 'center', justifyContent: 'center', resizeMode: 'cover', backgroundColor: '#ffffff', width, height, }, overlayContainer: { flex: 1, alignItems: 'center', backgroundColor: 'rgba(0,0,0,0.2)', alignSelf: 'stretch', justifyContent: 'center', paddingLeft: 25, paddingRight: 25, paddingTop: 45, paddingBottom: 40, position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, }, text: { color: '#ffffff', backgroundColor: 'rgba(0,0,0,0)', marginBottom: 15, textAlign: 'center', }, iconContainer: { justifyContent: 'center', alignItems: 'center', alignSelf: 'center', }, }); return ( <TouchableOpacity style={[styles.container, containerStyle && containerStyle]} {...attributes} > <Image source={imageSrc} style={[ styles.imageContainer, imageContainerStyle && imageContainerStyle, ]} > <View style={[ styles.overlayContainer, overlayContainerStyle && overlayContainerStyle, ]} > <View style={[ styles.iconContainer, iconContainerStyle && iconContainerStyle, ]} > {icon && <Icon {...icon} />} </View> <Text h4 style={[styles.text, titleStyle && titleStyle]}> {title} </Text> <Text style={[styles.text, captionStyle && captionStyle]}> {caption} </Text> </View> </Image> </TouchableOpacity> ); }; FeaturedTile.propTypes = { title: PropTypes.string, icon: PropTypes.object, caption: PropTypes.string, imageSrc: Image.propTypes.source.isRequired, onPress: PropTypes.func, containerStyle: ViewPropTypes.style, iconContainerStyle: ViewPropTypes.style, imageContainerStyle: ViewPropTypes.style, overlayContainerStyle: ViewPropTypes.style, titleStyle: NativeText.propTypes.style, captionStyle: NativeText.propTypes.style, width: PropTypes.number, height: PropTypes.number, }; export default FeaturedTile;
src/assets/scripts/containers/App.js
curlybracesco/pablo
import React, { Component } from 'react'; import Footer from './../components/Footer'; import Navbar from './../components/Navbar'; import Navigation from './../components/Navigation'; const __INITIAL_STATE__ = window.__INITIAL_STATE__; const THEME_URL_BASE = '/theme'; export default class App extends Component { setResources({ styles, scripts}) { this.setState({ styles: styles.map(styleHref => `${THEME_URL_BASE}/${styleHref}`) }); return this; } componentWillMount() { this.setResources(__INITIAL_STATE__.theme[0].assets); } render() { return ( <div> <section className="sidebar"> <Navbar themes={ __INITIAL_STATE__.theme } handler={ this.setResources.bind(this) } /> <Navigation data={ __INITIAL_STATE__ } /> </section> <main> { this.props.children && React.cloneElement(this.props.children, { theme: { styles: this.state.styles } }) } <Footer /> </main> </div> ); } };
src/js/components/icons/base/Send.js
linde12/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-send`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'send'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M22,3 L2,11 L20.5,19 L22,3 Z M10,20.5 L13,16 M15.5,9.5 L9,14 L9.85884537,20.0119176 C9.93680292,20.5576204 10.0751625,20.5490248 10.1651297,20.009222 L11,15 L15.5,9.5 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Send'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/components/modal/Modal.js
sanjay1909/WeaveReact
import React from 'react'; import ComponentManager from "../../ComponentManager"; import ModalConfig from "./ModalConfig"; import ModalPanel from "./ModalPanel"; class Modal extends React.Component { constructor(props) { super(props); ComponentManager.initialize(this); this.openModal = this.openModal.bind(this); } componentWillUnmount(){ ComponentManager.componentWillUnmount(this); } openModal(){ this.settings.open.value = true; } componentWillReceiveProps(nextProps){ ComponentManager.componentWillReceiveProps(this,nextProps); } render() { var isOpen = this.settings.open.value; var overlay = Style.overlayContainer(isOpen); var modal = Style.modal(isOpen); var modalButtonUI = ""; var modalPanelUI = ""; if(isOpen){ modalPanelUI = <ModalPanel title={this.props.title} sessionOpen={this.settings.open} settings={this.settings.panelConfig}> {this.props.children} </ModalPanel> } if (!this.props.keyPress){ if(this.settings.buttonIcon.value){ modalButtonUI = <span style={{cursor:"pointer"}} onClick={this.openModal}><i className={this.settings.buttonIcon.value}></i></span>; } else{ modalButtonUI = <span type="button" className="btn btn-primary" onClick={this.openModal}>Open</span>; } } return (<span > {modalButtonUI} <div style={overlay}/> <div style={modal}> {modalPanelUI} </div> </span> ); } } Weave.registerClass( Modal,["weavereact.Modal"],[weavejs.api.core.ILinkableObject],"Modal"); ComponentManager.registerToolConfig(Modal,ModalConfig); ComponentManager.registerToolImplementation("weavereact.ModalConfig",Modal); export default Modal;
src/intl.js
Tarabyte/foodlr-web
import React from 'react' import { addLocaleData, IntlProvider } from 'react-intl' import ru from 'react-intl/locale-data/ru' addLocaleData(ru) export default (locale, messages, component) => ( <IntlProvider locale={locale} messages={messages} defaultLocale="ru-RU"> {component} </IntlProvider> )
src/UserGrid.js
niyue/react-github
import React, { Component } from 'react'; import User from './User'; import UserListCaption from './UserListCaption'; import $ from 'jquery'; module.exports = React.createClass({ shouldComponentUpdate: function (nextProps, nextState) { console.log('action=should_user_grid_component_update users=%s', this.props.users.length); return true; }, render: function() { var style = { display: 'inline' }; var users = this.props.users.map(function (user) { var uid = `user-${user.login}`; return ( <div style={style} key={user.login} id={uid}> <User user={user} /> </div> ); }); var grid = []; for(var i = 0; i < users.length; i++) { grid.push(users[i]); if((i + 1) % 50 === 0) { grid.push(<br key={i}/>); } } return ( <div>{grid}</div> ); } });
src/PlusSign.js
borisyankov/shapetastic
import React from 'react'; import Shapetastic from './Shapetastic'; import XPrimitive from './XPrimitive'; export default class PlusSign { render() { return ( <Shapetastic stroke="red"> <XPrimitive {...this.props} /> </Shapetastic> ); } }
app/javascript/mastodon/components/dropdown_menu.js
tootcafe/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import IconButton from './icon_button'; import Overlay from 'react-overlays/lib/Overlay'; import Motion from '../features/ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { supportsPassiveEvents } from 'detect-passive-events'; const listenerOptions = supportsPassiveEvents ? { passive: true } : false; let id = 0; class DropdownMenu extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { items: PropTypes.array.isRequired, onClose: PropTypes.func.isRequired, style: PropTypes.object, placement: PropTypes.string, arrowOffsetLeft: PropTypes.string, arrowOffsetTop: PropTypes.string, openedViaKeyboard: PropTypes.bool, }; static defaultProps = { style: {}, placement: 'bottom', }; state = { mounted: false, }; handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } componentDidMount () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('keydown', this.handleKeyDown, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); if (this.focusedItem && this.props.openedViaKeyboard) { this.focusedItem.focus({ preventScroll: true }); } this.setState({ mounted: true }); } componentWillUnmount () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('keydown', this.handleKeyDown, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } setFocusRef = c => { this.focusedItem = c; } handleKeyDown = e => { const items = Array.from(this.node.getElementsByTagName('a')); const index = items.indexOf(document.activeElement); let element = null; switch(e.key) { case 'ArrowDown': element = items[index+1] || items[0]; break; case 'ArrowUp': element = items[index-1] || items[items.length-1]; break; case 'Tab': if (e.shiftKey) { element = items[index-1] || items[items.length-1]; } else { element = items[index+1] || items[0]; } break; case 'Home': element = items[0]; break; case 'End': element = items[items.length-1]; break; case 'Escape': this.props.onClose(); break; } if (element) { element.focus(); e.preventDefault(); e.stopPropagation(); } } handleItemKeyPress = e => { if (e.key === 'Enter' || e.key === ' ') { this.handleClick(e); } } handleClick = e => { const i = Number(e.currentTarget.getAttribute('data-index')); const { action, to } = this.props.items[i]; this.props.onClose(); if (typeof action === 'function') { e.preventDefault(); action(e); } else if (to) { e.preventDefault(); this.context.router.history.push(to); } } renderItem (option, i) { if (option === null) { return <li key={`sep-${i}`} className='dropdown-menu__separator' />; } const { text, href = '#', target = '_blank', method } = option; return ( <li className='dropdown-menu__item' key={`${text}-${i}`}> <a href={href} target={target} data-method={method} rel='noopener noreferrer' role='button' tabIndex='0' ref={i === 0 ? this.setFocusRef : null} onClick={this.handleClick} onKeyPress={this.handleItemKeyPress} data-index={i}> {text} </a> </li> ); } render () { const { items, style, placement, arrowOffsetLeft, arrowOffsetTop } = this.props; const { mounted } = this.state; return ( <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}> {({ opacity, scaleX, scaleY }) => ( // It should not be transformed when mounting because the resulting // size will be used to determine the coordinate of the menu by // react-overlays <div className={`dropdown-menu ${placement}`} style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null }} ref={this.setRef}> <div className={`dropdown-menu__arrow ${placement}`} style={{ left: arrowOffsetLeft, top: arrowOffsetTop }} /> <ul> {items.map((option, i) => this.renderItem(option, i))} </ul> </div> )} </Motion> ); } } export default class Dropdown extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { icon: PropTypes.string.isRequired, items: PropTypes.array.isRequired, size: PropTypes.number.isRequired, title: PropTypes.string, disabled: PropTypes.bool, status: ImmutablePropTypes.map, isUserTouching: PropTypes.func, onOpen: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, dropdownPlacement: PropTypes.string, openDropdownId: PropTypes.number, openedViaKeyboard: PropTypes.bool, }; static defaultProps = { title: 'Menu', }; state = { id: id++, }; handleClick = ({ target, type }) => { if (this.state.id === this.props.openDropdownId) { this.handleClose(); } else { const { top } = target.getBoundingClientRect(); const placement = top * 2 < innerHeight ? 'bottom' : 'top'; this.props.onOpen(this.state.id, this.handleItemClick, placement, type !== 'click'); } } handleClose = () => { if (this.activeElement) { this.activeElement.focus({ preventScroll: true }); this.activeElement = null; } this.props.onClose(this.state.id); } handleMouseDown = () => { if (!this.state.open) { this.activeElement = document.activeElement; } } handleButtonKeyDown = (e) => { switch(e.key) { case ' ': case 'Enter': this.handleMouseDown(); break; } } handleKeyPress = (e) => { switch(e.key) { case ' ': case 'Enter': this.handleClick(e); e.stopPropagation(); e.preventDefault(); break; } } handleItemClick = e => { const i = Number(e.currentTarget.getAttribute('data-index')); const { action, to } = this.props.items[i]; this.handleClose(); if (typeof action === 'function') { e.preventDefault(); action(); } else if (to) { e.preventDefault(); this.context.router.history.push(to); } } setTargetRef = c => { this.target = c; } findTarget = () => { return this.target; } componentWillUnmount = () => { if (this.state.id === this.props.openDropdownId) { this.handleClose(); } } render () { const { icon, items, size, title, disabled, dropdownPlacement, openDropdownId, openedViaKeyboard } = this.props; const open = this.state.id === openDropdownId; return ( <div> <IconButton icon={icon} title={title} active={open} disabled={disabled} size={size} ref={this.setTargetRef} onClick={this.handleClick} onMouseDown={this.handleMouseDown} onKeyDown={this.handleButtonKeyDown} onKeyPress={this.handleKeyPress} /> <Overlay show={open} placement={dropdownPlacement} target={this.findTarget}> <DropdownMenu items={items} onClose={this.handleClose} openedViaKeyboard={openedViaKeyboard} /> </Overlay> </div> ); } }
app/components/modal/index.js
wfa207/portfolio-page
'use strict'; import React, { Component } from 'react'; import { arrayConcat } from '../../../utils'; export default class Modal extends Component { constructor(props) { super(props); } render() { let teamMembersProp = this.props.teamMembers; let teamNum = teamMembersProp ? teamMembersProp.length : null; let teamStr = arrayConcat(teamMembersProp); let teamHTML; if (teamNum > 0) { teamHTML = <li>{'Team Member' + (teamNum > 1 ? 's' : '') + ':'} <strong>{teamStr}</strong></li>; } return ( <div className='portfolio-modal modal fade' id={this.props.link} tabIndex='-1' role='dialog' aria-hidden='true'> <div className='modal-content'> <div className='close-modal' data-dismiss='modal'> <div className='lr'> <div className='rl'> </div> </div> </div> <div className='container'> <div className='row'> <div className='col-lg-8 col-lg-offset-2'> <div className='modal-body'> <h2><a href={this.props.url}>{this.props.title}</a></h2> <hr className='star-primary'/> <img src={this.props.img} className='img-responsive img-centered'/> <p>{this.props.description}</p> <ul className='list-inline item-details'> <li>Date: <strong>{this.props.date}</strong></li> { teamHTML } <li>Project Type: <strong>{this.props.projectType}</strong></li> </ul> <button type='button' className='btn btn-default' data-dismiss='modal'><i className='fa fa-times'></i> Close</button> </div> </div> </div> </div> </div> </div> ); } }
webApp/src/Components/NavBarView.js
s-law/silent-disco
import React from 'react'; // MATERIAL DESIGN import AppBar from '../../node_modules/material-ui/lib/app-bar'; import LeftNav from '../../node_modules/material-ui/lib/left-nav'; import MenuItem from '../../node_modules/material-ui/lib/menus/menu-item'; import List from '../../node_modules/material-ui/lib/lists/list'; import ListItem from '../../node_modules/material-ui/lib/lists/list-item'; import FlatButton from '../../node_modules/material-ui/lib/flat-button'; import RaisedButton from '../../node_modules/material-ui/lib/raised-button'; class NavBarView extends React.Component { render() { return ( <div> <LeftNav onRequestChange={this.props.toggle} open={this.props.open} docked={false}> <a href='/' style={{textDecoration:'none'}}><div style={styles.leftNavTitle}>Socket Radio</div></a> <MenuItem onClick={this.props.goListen}>Listen</MenuItem> { this.props.isAuth ? ( <List subheader=""> <ListItem primaryText="Broadcast" initiallyOpen={true} primaryTogglesNestedList={true} nestedItems={[ <ListItem key={1} primaryText="Create Broadcast" onClick={this.props.goBroadcast} />, <ListItem key={2} primaryText="Profile" onClick={this.props.goProfile} />, <ListItem key={3} primaryText="Logout" onClick={this.props.goLogout} />, ]} /> </List> ) : ( <List subheader=""> <ListItem primaryText="Broadcast" initiallyOpen={true} primaryTogglesNestedList={true} nestedItems={[ <ListItem key={1} primaryText="Login" onClick={this.props.goLogin} />, ]} /> </List> )} </LeftNav> <AppBar title={this.props.title} titleStyle={styles.title} onLeftIconButtonTouchTap={this.props.toggle} zDepth={0}/> </div> ) } } var styles = { leftNavTitle:{ 'cursor': 'pointer', 'fontSize': '24px', 'color': 'rgba(255, 255, 255, 1)', 'lineHeight': '64px', 'fontWeight': 300, 'backgroundColor': '#00bcd4', 'paddingLeft': '24px', 'marginBottom': '8px' } } export default NavBarView;
libs/utils/react.js
zangxd/ui-react
import React from 'react' function firstChild(props) { const childrenArray = React.Children.toArray(props.children); return childrenArray[0] || null; } export {firstChild}
app/components/todolist/Link.js
flanamacca/react-learning-kit
import React from 'react' import PropTypes from 'prop-types'; // ES6 const Link = ({ active, children, onClick }) => { if (active) { return <span>{children}</span> } return ( <a href="#" onClick={e => { e.preventDefault() onClick() }} > {children} </a> ) } Link.propTypes = { active: PropTypes.bool.isRequired, children: PropTypes.node.isRequired, onClick: PropTypes.func.isRequired } export default Link
front_end/front_end_app/src/client/todos/tocheck.react.js
carlodicelico/horizon
import Component from '../components/component.react'; import React from 'react'; import {FormattedHTMLMessage} from 'react-intl'; import {Link} from 'react-router'; export default class ToCheck extends Component { static propTypes = { msg: React.PropTypes.object.isRequired } render() { const {msg} = this.props; return ( <div className="tocheck"> <h3>{msg.header}</h3> <ul> {msg.itemListHtml.map(item => <li key={item.key}> <FormattedHTMLMessage message={item.txt} /> </li> )} <li> {msg.isomorphicPage}{' '} <Link to="/this-is-not-the-web-page-you-are-looking-for">404</Link>. </li> <li> {msg.andMuchMore} </li> </ul> </div> ); } }
es/ExpansionPanel/ExpansionPanelSummary.js
uplevel-technology/material-ui-next
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } // @inheritedComponent ButtonBase import React from 'react'; import classNames from 'classnames'; import ButtonBase from '../ButtonBase'; import IconButton from '../IconButton'; import withStyles from '../styles/withStyles'; export const styles = theme => { const transition = { duration: theme.transitions.duration.shortest, easing: theme.transitions.easing.ease }; return { root: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', minHeight: theme.spacing.unit * 6, transition: theme.transitions.create(['min-height', 'background-color'], transition), padding: `0 ${theme.spacing.unit * 3}px 0 ${theme.spacing.unit * 3}px`, position: 'relative', '&:hover:not($disabled)': { cursor: 'pointer' } }, expanded: { minHeight: 64 }, focused: { backgroundColor: theme.palette.grey[300] }, disabled: { opacity: 0.38, color: theme.palette.action.disabled }, content: { display: 'flex', flexGrow: 1, transition: theme.transitions.create(['margin'], transition), margin: '12px 0', '& > :last-child': { paddingRight: theme.spacing.unit * 4 } }, contentExpanded: { margin: '20px 0' }, expandIcon: { color: theme.palette.text.icon, position: 'absolute', top: '50%', right: theme.spacing.unit, transform: 'translateY(-50%) rotate(0deg)', transition: theme.transitions.create('transform', transition) }, expandIconExpanded: { transform: 'translateY(-50%) rotate(180deg)' } }; }; class ExpansionPanelSummary extends React.Component { constructor(...args) { var _temp; return _temp = super(...args), this.state = { focused: false }, this.handleFocus = () => { this.setState({ focused: true }); }, this.handleBlur = () => { this.setState({ focused: false }); }, this.handleChange = event => { const { onChange, onClick } = this.props; if (onChange) { onChange(event); } if (onClick) { onClick(event); } }, _temp; } render() { const _props = this.props, { children, classes, className, disabled, expanded, expandIcon, onChange } = _props, other = _objectWithoutProperties(_props, ['children', 'classes', 'className', 'disabled', 'expanded', 'expandIcon', 'onChange']); const { focused } = this.state; return React.createElement( ButtonBase, _extends({ focusRipple: false, disableRipple: true, disabled: disabled, component: 'div', 'aria-expanded': expanded, className: classNames(classes.root, { [classes.disabled]: disabled, [classes.expanded]: expanded, [classes.focused]: focused }, className) }, other, { onKeyboardFocus: this.handleFocus, onBlur: this.handleBlur, onClick: this.handleChange }), React.createElement( 'div', { className: classNames(classes.content, { [classes.contentExpanded]: expanded }) }, children ), expandIcon && React.createElement( IconButton, { disabled: disabled, className: classNames(classes.expandIcon, { [classes.expandIconExpanded]: expanded }), component: 'div', tabIndex: '-1', 'aria-hidden': 'true', onClick: this.handleChange }, expandIcon ) ); } } ExpansionPanelSummary.muiName = 'ExpansionPanelSummary'; ExpansionPanelSummary.defaultProps = { classes: {}, disabled: false }; export default withStyles(styles, { name: 'MuiExpansionPanelSummary' })(ExpansionPanelSummary);
packages/neos-ui-validators/src/Float/index.js
dimaip/neos-ui
import React from 'react'; import I18n from '@neos-project/neos-ui-i18n'; /** * Checks if the given value is a valid floating point number */ const Float = value => { const number = parseFloat(value); if (value.length !== 0 && (isNaN(number) || value.toString().match(/.+\d$/) === null)) { return <I18n id="content.inspector.validators.floatValidator.validFloatExpected"/>; } return null; }; export default Float;
src/components/ErrorBoundary.js
demisto/sane-reports
import React from 'react'; import PropTypes from 'prop-types'; class ErrorBoundary extends React.Component { static getDerivedStateFromError(error) { return { errorMessage: `"${error.message}"` }; } static propTypes = { children: PropTypes.any }; constructor(props) { super(props); this.state = { errorMessage: false }; } render() { if (this.state.errorMessage) { return ( <div className="error-section"> <h5>Something Went Wrong - Error:</h5> <div className="error-message"> {this.state.errorMessage} </div> </div> ); } return this.props.children ? this.props.children : null; } } export default ErrorBoundary;
server/sonar-web/src/main/js/apps/projectActivity/components/forms/AddCustomEventForm.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // @flow import React from 'react'; import { connect } from 'react-redux'; import { addCustomEvent } from '../../actions'; import AddEventForm from './AddEventForm'; import type { Analysis } from '../../../../store/projectActivity/duck'; type Props = { addEvent: () => Promise<*>, analysis: Analysis }; const AddCustomEventForm = (props: Props) => ( <AddEventForm {...props} addEventButtonText="project_activity.add_custom_event" /> ); const mapStateToProps = null; const mapDispatchToProps = { addEvent: addCustomEvent }; export default connect(mapStateToProps, mapDispatchToProps)(AddCustomEventForm);
examples/json-placeholder/src/app.js
taion/flux-resource-marty
import martyResource from 'flux-resource-marty'; import { Application, ApplicationContainer, createContainer, HttpStateSource } from 'marty'; import React from 'react'; HttpStateSource.removeHook('parseJSON'); const {PostActions, PostApi, PostStore} = martyResource({ name: 'post', urlFunc: id => `http://jsonplaceholder.typicode.com/posts/${id}`, postprocessors: [ function parseJson(res) { if (!res.ok) { throw res.statusText; } return res.json(); } ] }); class JsonPlaceholderApplication extends Application { constructor(options) { super(options); this.register({ postActions: PostActions, postApi: PostApi, postStore: PostStore }); } } class PostList extends React.Component { render() { return ( <div> {this.renderPosts()} </div> ); } renderPosts() { return this.props.posts.map(this.renderPost); } renderPost(post, i) { return ( <div key={i}> {JSON.stringify(post)} </div> ); } } PostList = createContainer( PostList, { listenTo: 'postStore', fetch: { posts() { return this.app.postStore.getPosts(); } } } ); const app = new JsonPlaceholderApplication(); const mountNode = document.createElement("DIV"); document.body.appendChild(mountNode); React.render( ( <ApplicationContainer app={app}> <PostList /> </ApplicationContainer> ), mountNode );
server/sonar-web/src/main/js/apps/overview/meta/MetaOrganizationKey.js
Builders-SonarSource/sonarqube-bis
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import { translate } from '../../../helpers/l10n'; const MetaOrganizationKey = ({ component }) => { return ( <div className="overview-meta-card"> <h4 className="overview-meta-header"> {translate('organization_key')} </h4> <input className="overview-key" type="text" value={component.organization} readOnly={true} onClick={e => e.target.select()}/> </div> ); }; export default MetaOrganizationKey;
app/components/BookList/index.js
ZhydraBook/zhydrabook
// @flow import React, { Component } from 'react'; import { Segment, Card } from 'semantic-ui-react'; import Book from './Book'; import SearchForm from './Form'; export default class BookList extends Component { render() { return ( <Segment> <SearchForm onSubmit={this.props.handleUpdate} /> { (this.props.books.length > 0 && this.props.query.isbn) ? <Card.Group style={{ justifyContent: 'center' }}> {this.props.books.map(book => <Book key={book.isbn} {...book} handleClick={() => this.props.onBookClick(book)} /> )} </Card.Group> : (!this.props.query.isbn) ? <p> Prova a cercare un isbn </p> : <p> Nessun isbn trovato </p> } </Segment> ); } }
app/javascript/mastodon/features/status/components/card.js
verniy6462/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import punycode from 'punycode'; const IDNA_PREFIX = 'xn--'; const decodeIDNA = domain => { return domain .split('.') .map(part => part.indexOf(IDNA_PREFIX) === 0 ? punycode.decode(part.slice(IDNA_PREFIX.length)) : part) .join('.'); }; const getHostname = url => { const parser = document.createElement('a'); parser.href = url; return parser.hostname; }; export default class Card extends React.PureComponent { static propTypes = { card: ImmutablePropTypes.map, }; renderLink () { const { card } = this.props; let image = ''; let provider = card.get('provider_name'); if (card.get('image')) { image = ( <div className='status-card__image'> <img src={card.get('image')} alt={card.get('title')} className='status-card__image-image' /> </div> ); } if (provider.length < 1) { provider = decodeIDNA(getHostname(card.get('url'))); } return ( <a href={card.get('url')} className='status-card' target='_blank' rel='noopener'> {image} <div className='status-card__content'> <strong className='status-card__title' title={card.get('title')}>{card.get('title')}</strong> <p className='status-card__description'>{(card.get('description') || '').substring(0, 50)}</p> <span className='status-card__host'>{provider}</span> </div> </a> ); } renderPhoto () { const { card } = this.props; return ( <a href={card.get('url')} className='status-card-photo' target='_blank' rel='noopener'> <img src={card.get('url')} alt={card.get('title')} width={card.get('width')} height={card.get('height')} /> </a> ); } renderVideo () { const { card } = this.props; const content = { __html: card.get('html') }; return ( <div className='status-card-video' dangerouslySetInnerHTML={content} /> ); } render () { const { card } = this.props; if (card === null) { return null; } switch(card.get('type')) { case 'link': return this.renderLink(); case 'photo': return this.renderPhoto(); case 'video': return this.renderVideo(); case 'rich': default: return null; } } }
lib/shared/screens/admin/screens/settings/screens/google/index.js
relax/relax
import Component from 'components/component'; import Content from 'components/content'; import React from 'react'; import SettingsForm from 'components/settings-form'; import mapSettingsIds from 'helpers/map-settings-ids'; import {googleAPI} from 'statics/settings-keys'; const options = [ { label: 'Google API ID', type: 'String', id: googleAPI, props: { placeholder: 'Your google API ID' } } ]; export default class GoogleSettingsContainer extends Component { static propTypes = {}; render () { return ( <Content noOffset> <SettingsForm options={options} settingsIds={mapSettingsIds(options)} /> </Content> ); } }
src/svg-icons/maps/local-atm.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalAtm = (props) => ( <SvgIcon {...props}> <path d="M11 17h2v-1h1c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1h-3v-1h4V8h-2V7h-2v1h-1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1h3v1H9v2h2v1zm9-13H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4V6h16v12z"/> </SvgIcon> ); MapsLocalAtm = pure(MapsLocalAtm); MapsLocalAtm.displayName = 'MapsLocalAtm'; MapsLocalAtm.muiName = 'SvgIcon'; export default MapsLocalAtm;
app/javascript/mastodon/features/compose/components/upload_progress.js
dwango/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { FormattedMessage } from 'react-intl'; export default class UploadProgress extends React.PureComponent { static propTypes = { active: PropTypes.bool, progress: PropTypes.number, }; render () { const { active, progress } = this.props; if (!active) { return null; } return ( <div className='upload-progress'> <div className='upload-progress__icon'> <i className='fa fa-upload' /> </div> <div className='upload-progress__message'> <FormattedMessage id='upload_progress.label' defaultMessage='Uploading...' /> <div className='upload-progress__backdrop'> <Motion defaultStyle={{ width: 0 }} style={{ width: spring(progress) }}> {({ width }) => <div className='upload-progress__tracker' style={{ width: `${width}%` }} /> } </Motion> </div> </div> </div> ); } }
app/javascript/mastodon/features/account/components/header.js
pinfort/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import Button from 'mastodon/components/button'; import Area_header from '../../../components/area_header'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { autoPlayGif, me, isStaff } from 'mastodon/initial_state'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; import IconButton from 'mastodon/components/icon_button'; import Avatar from 'mastodon/components/avatar'; import { counterRenderer } from 'mastodon/components/common_counter'; import ShortNumber from 'mastodon/components/short_number'; import { NavLink } from 'react-router-dom'; import DropdownMenuContainer from 'mastodon/containers/dropdown_menu_container'; import AccountNoteContainer from '../containers/account_note_container'; const messages = defineMessages({ unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' }, follow: { id: 'account.follow', defaultMessage: 'Follow' }, cancel_follow_request: { id: 'account.cancel_follow_request', defaultMessage: 'Cancel follow request' }, requested: { id: 'account.requested', defaultMessage: 'Awaiting approval. Click to cancel follow request' }, unblock: { id: 'account.unblock', defaultMessage: 'Unblock @{name}' }, edit_profile: { id: 'account.edit_profile', defaultMessage: 'Edit profile' }, linkVerifiedOn: { id: 'account.link_verified_on', defaultMessage: 'Ownership of this link was checked on {date}' }, account_locked: { id: 'account.locked_info', defaultMessage: 'This account privacy status is set to locked. The owner manually reviews who can follow them.' }, mention: { id: 'account.mention', defaultMessage: 'Mention @{name}' }, direct: { id: 'account.direct', defaultMessage: 'Direct message @{name}' }, unmute: { id: 'account.unmute', defaultMessage: 'Unmute @{name}' }, block: { id: 'account.block', defaultMessage: 'Block @{name}' }, mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' }, report: { id: 'account.report', defaultMessage: 'Report @{name}' }, share: { id: 'account.share', defaultMessage: 'Share @{name}\'s profile' }, media: { id: 'account.media', defaultMessage: 'Media' }, blockDomain: { id: 'account.block_domain', defaultMessage: 'Block domain {domain}' }, unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unblock domain {domain}' }, hideReblogs: { id: 'account.hide_reblogs', defaultMessage: 'Hide boosts from @{name}' }, showReblogs: { id: 'account.show_reblogs', defaultMessage: 'Show boosts from @{name}' }, enableNotifications: { id: 'account.enable_notifications', defaultMessage: 'Notify me when @{name} posts' }, disableNotifications: { id: 'account.disable_notifications', defaultMessage: 'Stop notifying me when @{name} posts' }, pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' }, preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' }, follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' }, favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' }, lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' }, blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' }, domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Blocked domains' }, mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' }, endorse: { id: 'account.endorse', defaultMessage: 'Feature on profile' }, unendorse: { id: 'account.unendorse', defaultMessage: 'Don\'t feature on profile' }, add_or_remove_from_list: { id: 'account.add_or_remove_from_list', defaultMessage: 'Add or Remove from lists' }, admin_account: { id: 'status.admin_account', defaultMessage: 'Open moderation interface for @{name}' }, }); const dateFormatOptions = { month: 'short', day: 'numeric', year: 'numeric', hour12: false, hour: '2-digit', minute: '2-digit', }; export default @injectIntl class Header extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map, identity_props: ImmutablePropTypes.list, onFollow: PropTypes.func.isRequired, onBlock: PropTypes.func.isRequired, onMention: PropTypes.func.isRequired, onDirect: PropTypes.func.isRequired, onReblogToggle: PropTypes.func.isRequired, onNotifyToggle: PropTypes.func.isRequired, onReport: PropTypes.func.isRequired, onMute: PropTypes.func.isRequired, onBlockDomain: PropTypes.func.isRequired, onUnblockDomain: PropTypes.func.isRequired, onEndorseToggle: PropTypes.func.isRequired, onAddToList: PropTypes.func.isRequired, onEditAccountNote: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, domain: PropTypes.string.isRequired, }; openEditProfile = () => { window.open('/settings/profile', '_blank'); } isStatusesPageActive = (match, location) => { if (!match) { return false; } return !location.pathname.match(/\/(followers|following)\/?$/); } handleMouseEnter = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-original'); } } handleMouseLeave = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-static'); } } render () { const { account, intl, domain, identity_proofs } = this.props; if (!account) { return null; } const suspended = account.get('suspended'); let info = []; let actionBtn = ''; let bellBtn = ''; let lockedIcon = ''; let menu = []; if (me !== account.get('id') && account.getIn(['relationship', 'followed_by'])) { info.push(<span key='followed_by' className='relationship-tag'><FormattedMessage id='account.follows_you' defaultMessage='Follows you' /></span>); } else if (me !== account.get('id') && account.getIn(['relationship', 'blocking'])) { info.push(<span key='blocked' className='relationship-tag'><FormattedMessage id='account.blocked' defaultMessage='Blocked' /></span>); } if (me !== account.get('id') && account.getIn(['relationship', 'muting'])) { info.push(<span key='muted' className='relationship-tag'><FormattedMessage id='account.muted' defaultMessage='Muted' /></span>); } else if (me !== account.get('id') && account.getIn(['relationship', 'domain_blocking'])) { info.push(<span key='domain_blocked' className='relationship-tag'><FormattedMessage id='account.domain_blocked' defaultMessage='Domain blocked' /></span>); } if (account.getIn(['relationship', 'requested']) || account.getIn(['relationship', 'following'])) { bellBtn = <IconButton icon='bell-o' size={24} active={account.getIn(['relationship', 'notifying'])} title={intl.formatMessage(account.getIn(['relationship', 'notifying']) ? messages.disableNotifications : messages.enableNotifications, { name: account.get('username') })} onClick={this.props.onNotifyToggle} />; } if (me !== account.get('id')) { if (!account.get('relationship')) { // Wait until the relationship is loaded actionBtn = ''; } else if (account.getIn(['relationship', 'requested'])) { actionBtn = <Button className={classNames('logo-button', { 'button--with-bell': bellBtn !== '' })} text={intl.formatMessage(messages.cancel_follow_request)} title={intl.formatMessage(messages.requested)} onClick={this.props.onFollow} />; } else if (!account.getIn(['relationship', 'blocking'])) { actionBtn = <Button disabled={account.getIn(['relationship', 'blocked_by'])} className={classNames('logo-button', { 'button--destructive': account.getIn(['relationship', 'following']), 'button--with-bell': bellBtn !== '' })} text={intl.formatMessage(account.getIn(['relationship', 'following']) ? messages.unfollow : messages.follow)} onClick={this.props.onFollow} />; } else if (account.getIn(['relationship', 'blocking'])) { actionBtn = <Button className='logo-button' text={intl.formatMessage(messages.unblock, { name: account.get('username') })} onClick={this.props.onBlock} />; } } else { actionBtn = <Button className='logo-button' text={intl.formatMessage(messages.edit_profile)} onClick={this.openEditProfile} />; } if (account.get('moved') && !account.getIn(['relationship', 'following'])) { actionBtn = ''; } if (account.get('locked')) { lockedIcon = <Icon id='lock' title={intl.formatMessage(messages.account_locked)} />; } if (account.get('id') !== me) { menu.push({ text: intl.formatMessage(messages.mention, { name: account.get('username') }), action: this.props.onMention }); menu.push({ text: intl.formatMessage(messages.direct, { name: account.get('username') }), action: this.props.onDirect }); menu.push(null); } if ('share' in navigator) { menu.push({ text: intl.formatMessage(messages.share, { name: account.get('username') }), action: this.handleShare }); menu.push(null); } if (account.get('id') === me) { menu.push({ text: intl.formatMessage(messages.edit_profile), href: '/settings/profile' }); menu.push({ text: intl.formatMessage(messages.preferences), href: '/settings/preferences' }); menu.push({ text: intl.formatMessage(messages.pins), to: '/pinned' }); menu.push(null); menu.push({ text: intl.formatMessage(messages.follow_requests), to: '/follow_requests' }); menu.push({ text: intl.formatMessage(messages.favourites), to: '/favourites' }); menu.push({ text: intl.formatMessage(messages.lists), to: '/lists' }); menu.push(null); menu.push({ text: intl.formatMessage(messages.mutes), to: '/mutes' }); menu.push({ text: intl.formatMessage(messages.blocks), to: '/blocks' }); menu.push({ text: intl.formatMessage(messages.domain_blocks), to: '/domain_blocks' }); } else { if (account.getIn(['relationship', 'following'])) { if (!account.getIn(['relationship', 'muting'])) { if (account.getIn(['relationship', 'showing_reblogs'])) { menu.push({ text: intl.formatMessage(messages.hideReblogs, { name: account.get('username') }), action: this.props.onReblogToggle }); } else { menu.push({ text: intl.formatMessage(messages.showReblogs, { name: account.get('username') }), action: this.props.onReblogToggle }); } } menu.push({ text: intl.formatMessage(account.getIn(['relationship', 'endorsed']) ? messages.unendorse : messages.endorse), action: this.props.onEndorseToggle }); menu.push({ text: intl.formatMessage(messages.add_or_remove_from_list), action: this.props.onAddToList }); menu.push(null); } if (account.getIn(['relationship', 'muting'])) { menu.push({ text: intl.formatMessage(messages.unmute, { name: account.get('username') }), action: this.props.onMute }); } else { menu.push({ text: intl.formatMessage(messages.mute, { name: account.get('username') }), action: this.props.onMute }); } if (account.getIn(['relationship', 'blocking'])) { menu.push({ text: intl.formatMessage(messages.unblock, { name: account.get('username') }), action: this.props.onBlock }); } else { menu.push({ text: intl.formatMessage(messages.block, { name: account.get('username') }), action: this.props.onBlock }); } menu.push({ text: intl.formatMessage(messages.report, { name: account.get('username') }), action: this.props.onReport }); } if (account.get('acct') !== account.get('username')) { const domain = account.get('acct').split('@')[1]; menu.push(null); if (account.getIn(['relationship', 'domain_blocking'])) { menu.push({ text: intl.formatMessage(messages.unblockDomain, { domain }), action: this.props.onUnblockDomain }); } else { menu.push({ text: intl.formatMessage(messages.blockDomain, { domain }), action: this.props.onBlockDomain }); } } if (account.get('id') !== me && isStaff) { menu.push(null); menu.push({ text: intl.formatMessage(messages.admin_account, { name: account.get('username') }), href: `/admin/accounts/${account.get('id')}` }); } const content = { __html: account.get('note_emojified') }; const displayNameHtml = { __html: account.get('display_name_html') }; const fields = account.get('fields'); const acct = account.get('acct').indexOf('@') === -1 && domain ? `${account.get('acct')}@${domain}` : account.get('acct'); let badge; if (account.get('bot')) { badge = (<div className='account-role bot'><FormattedMessage id='account.badges.bot' defaultMessage='Bot' /></div>); } else if (account.get('group')) { badge = (<div className='account-role group'><FormattedMessage id='account.badges.group' defaultMessage='Group' /></div>); } else { badge = null; } return ( <div className={classNames('account__header', { inactive: !!account.get('moved') })} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <div className='account__header__image'> <div className='account__header__info'> {!suspended && info} </div> <img src={autoPlayGif ? account.get('header') : account.get('header_static')} alt='' className='parallax' /> </div> <div className='account__header__bar'> <div className='account__header__tabs'> <a className='avatar' href={account.get('url')} rel='noopener noreferrer' target='_blank'> <Avatar account={account} size={90} /> <Area_header account={account} /> </a> <div className='spacer' /> {!suspended && ( <div className='account__header__tabs__buttons'> {actionBtn} {bellBtn} <DropdownMenuContainer items={menu} icon='ellipsis-v' size={24} direction='right' /> </div> )} </div> <div className='account__header__tabs__name'> <h1> <span dangerouslySetInnerHTML={displayNameHtml} /> {badge} <small>@{acct} {lockedIcon}</small> </h1> </div> <div className='account__header__extra'> <div className='account__header__bio'> {(fields.size > 0 || identity_proofs.size > 0) && ( <div className='account__header__fields'> {identity_proofs.map((proof, i) => ( <dl key={i}> <dt dangerouslySetInnerHTML={{ __html: proof.get('provider') }} /> <dd className='verified'> <a href={proof.get('proof_url')} target='_blank' rel='noopener noreferrer'><span title={intl.formatMessage(messages.linkVerifiedOn, { date: intl.formatDate(proof.get('updated_at'), dateFormatOptions) })}> <Icon id='check' className='verified__mark' /> </span></a> <a href={proof.get('profile_url')} target='_blank' rel='noopener noreferrer'><span dangerouslySetInnerHTML={{ __html: ' '+proof.get('provider_username') }} /></a> </dd> </dl> ))} {fields.map((pair, i) => ( <dl key={i}> <dt dangerouslySetInnerHTML={{ __html: pair.get('name_emojified') }} title={pair.get('name')} className='translate' /> <dd className={`${pair.get('verified_at') ? 'verified' : ''} translate`} title={pair.get('value_plain')}> {pair.get('verified_at') && <span title={intl.formatMessage(messages.linkVerifiedOn, { date: intl.formatDate(pair.get('verified_at'), dateFormatOptions) })}><Icon id='check' className='verified__mark' /></span>} <span dangerouslySetInnerHTML={{ __html: pair.get('value_emojified') }} /> </dd> </dl> ))} </div> )} {account.get('id') !== me && !suspended && <AccountNoteContainer account={account} />} {account.get('note').length > 0 && account.get('note') !== '<p></p>' && <div className='account__header__content translate' dangerouslySetInnerHTML={content} />} <div className='account__header__joined'><FormattedMessage id='account.joined' defaultMessage='Joined {date}' values={{ date: intl.formatDate(account.get('created_at'), { year: 'numeric', month: 'short', day: '2-digit' }) }} /></div> </div> {!suspended && ( <div className='account__header__extra__links'> <NavLink isActive={this.isStatusesPageActive} activeClassName='active' to={`/accounts/${account.get('id')}`} title={intl.formatNumber(account.get('statuses_count'))}> <ShortNumber value={account.get('statuses_count')} renderer={counterRenderer('statuses')} /> </NavLink> <NavLink exact activeClassName='active' to={`/accounts/${account.get('id')}/following`} title={intl.formatNumber(account.get('following_count'))}> <ShortNumber value={account.get('following_count')} renderer={counterRenderer('following')} /> </NavLink> <NavLink exact activeClassName='active' to={`/accounts/${account.get('id')}/followers`} title={intl.formatNumber(account.get('followers_count'))}> <ShortNumber value={account.get('followers_count')} renderer={counterRenderer('followers')} /> </NavLink> </div> )} </div> </div> </div> ); } }
views/main.js
smaty1/black-screen
import React from 'react'; import _ from 'lodash'; import Rx from 'rx'; import ApplicationView from './compiled/src/views/ApplicationView.js'; var keys = { goUp: event => (event.ctrlKey && event.keyCode === 80) || event.keyCode === 38, goDown: event => (event.ctrlKey && event.keyCode === 78) || event.keyCode === 40, enter: event => event.keyCode === 13, tab: event => event.keyCode === 9, deleteWord: event => event.ctrlKey && event.keyCode === 87 }; function scrollToBottom() { $('html body').animate({ scrollTop: $(document).height() }, 0); } function focusLastInput(event) { if (_.contains(event.target.classList, 'prompt') || event.metaKey) { return; } var originalEvent = event.originalEvent; if (isMetaKey(originalEvent)) { return; } var newEvent = new KeyboardEvent("keydown", _.pick(originalEvent, [ 'altkey', 'bubbles', 'cancelBubble', 'cancelable', 'charCode', 'ctrlKey', 'keyIdentifier', 'metaKey', 'shiftKey' ])); var target = _.last(document.getElementsByClassName('prompt')); target.focus(); withCaret(target, () => target.innerText.length); target.dispatchEvent(newEvent) } function setCaretPosition(node, position) { var selection = window.getSelection(); var range = document.createRange(); if (node.childNodes.length) { range.setStart(node.childNodes[0], position); } else { range.setStart(node, 0); } range.collapse(true); selection.removeAllRanges(); selection.addRange(range); } function withCaret(target, callback) { var selection = window.getSelection(); var range = document.createRange(); var offset = callback(selection.baseOffset); if (target.childNodes.length) { range.setStart(target.childNodes[0], offset); } else { range.setStart(target, 0); } range.collapse(true); selection.removeAllRanges(); selection.addRange(range); } function isCommandKey(event) { return _.contains([16, 17, 18], event.keyCode) || event.ctrlKey || event.altKey || event.metaKey; } function isMetaKey(event) { return event.metaKey || _.some([event.key, event.keyIdentifier], key => _.includes(['Shift', 'Alt', 'Ctrl'], key)); } const isDefinedKey = _.memoize(event => _.some(_.values(keys), matcher => matcher(event)), event => [event.ctrlKey, event.keyCode]); function stopBubblingUp(event) { event.stopPropagation(); event.preventDefault(); return event; } // TODO: Figure out how it works. function createEventHandler() { var subject = function() { subject.onNext.apply(subject, arguments); }; getEnumerablePropertyNames(Rx.Subject.prototype) .forEach(function (property) { subject[property] = Rx.Subject.prototype[property]; }); Rx.Subject.call(subject); return subject; } function getEnumerablePropertyNames(target) { var result = []; for (var key in target) { result.push(key); } return result; } $(document).ready(() => { React.render(<ApplicationView/>, document.getElementById('black-board')); // TODO: focus the last input of the active terminal. $(document).keydown(event => focusLastInput(event)); });
scaffold/templates/google-booking-project/template/frontend/src/app/index.js
binocarlos/templatestack
import React from 'react' import { render } from 'react-dom' import { routerForBrowser } from 'redux-little-router' import RootFactory from 'template-ui/lib/containers/Root' import configureStore from 'template-ui/lib/store/configureStore' import rootSaga from './sagas' import { routeConfig, routes } from './routes' import reducers from './reducers' const router = routerForBrowser({ routes: routeConfig }) const Root = RootFactory(routes) const store = configureStore({ router, reducers, initialState: window.__INITIAL_STATE__ }) store.runSaga(rootSaga) render( <Root store={ store } />, document.getElementById('mount') )
docs/src/components/Menu/index.js
michalko/draft-wyswig
/* @flow */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router'; import classNames from 'classnames'; import './styles.css'; export default class Menu extends Component { static propTypes = { pathname: PropTypes.string, }; state: any = { status: false, }; changeState: any = () => { const status = !this.state.status; this.setState({ status, }); }; render() { const { pathname } = this.props; return ( <div className="menu-root"> <Link to={'/'} className={classNames('menu-option', { 'menu-option-active': pathname === '/' })}> Home </Link> <Link to={'/demo'} className={classNames('menu-option', { 'menu-option-active': pathname === '/demo' })}> Demo </Link> <Link to={'/docs'} className={classNames('menu-option', { 'menu-option-active': pathname === '/docs' })}> Docs </Link> <Link to={'/author'} className={classNames('menu-option', { 'menu-option-active': pathname === '/author' })}> Author </Link> </div> ); } }
src/index.js
jiangxy/react-antd-admin
/** * 程序的入口, 类似java中的main */ import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux' import {Router, Route, IndexRoute, hashHistory} from 'react-router'; import './utils/index.js'; // 引入各种prototype辅助方法 import store from 'redux/store.js'; // redux store // 开始引入各种自定义的组件 import App from './components/App'; import Welcome from './components/Welcome'; import Error from './components/Error'; import Hello from './components/Hello'; //import DBTable from './components/DBTable'; // 将DBTable组件做成动态路由, 减小bundle size // 注意不要再import DBTable了, 不然就没意义了 // 一些比较大/不常用的组件, 都可以考虑做成动态路由 const DBTableContainer = (location, cb) => { require.ensure([], require => { cb(null, require('./components/DBTable').default) }, 'DBTable'); }; // 路由表, 只要menu.js中所有的叶子节点配置了路由就可以了 // 我本来想根据menu.js自动生成路由表, 但那样太不灵活了, 还是自己配置好些 const routes = ( <Provider store={store}> <Router history={hashHistory}> <Route path="/" component={App}> <IndexRoute component={Welcome}/> <Route path="index"> <Route path="option1" tableName="test" getComponent={DBTableContainer}/> <Route path="option2" tableName="testSms" getComponent={DBTableContainer}/> <Route path="option3" tableName="testAction" getComponent={DBTableContainer}/> </Route> <Route path="daohang"> <Route path="555" component={Hello}/> <Route path="sanji"> <Route path="666" component={Hello}/> <Route path="777" component={Hello}/> <Route path="888" component={Hello}/> <Route path="999" component={Hello}/> </Route> </Route> <Route path="test"> <Route path="aaa" component={Hello}/> <Route path="bbb" component={Hello}/> <Route path="ccc" component={Hello}/> <Route path="sanjiaaa"> <Route path="666aa" component={Hello}/> </Route> <Route path="sanjibbb"> <Route path="666bb" component={Hello}/> </Route> </Route> <Route path="headerMenu5"> <Route path="headerMenu5000000" component={Hello}/> <Route path="headerMenu51111"> <Route path="headerMenu51111aa" component={Hello}/> <Route path="headerMenu51111bb" component={Hello}/> </Route> <Route path="headerMenu52222"> <Route path="headerMenu52222aa" component={Hello}/> <Route path="headerMenu52222bb" component={Hello}/> </Route> </Route> <Route path="headerMenu4" component={Hello}/> <Route path="alone" component={Hello}/> <Route path="alone2" component={Hello}/> <Route path="*" component={Error}/> </Route> </Router> </Provider> ); ReactDOM.render(routes, document.getElementById('root'));
src/components/Subscribe.js
aengl/sector4-website
import React from 'react'; import './Subscribe.css'; export class Subscribe extends React.Component { constructor(props) { super(props); this.resetError = this.resetError.bind(this); this.subscribe = this.subscribe.bind(this); this.state = { error: null, loading: false }; } render() { let error = null; if (this.state.error) { error = ( <div className='Subscribe-error'>{this.state.error}</div> ); } let button; if (this.state.loading) { button = ( <button className='busy'> <i className='fa fa-refresh fa-spin fa-fw'></i> </button> ); } else { button = ( <button onClick={this.subscribe}>Subscribe</button> ); } return ( <div className='Subscribe'> <h2>Subscribe to ours newsletter for offers and updates</h2> <div> <input ref='mail' placeholder='Email address' onKeyUp={this.resetError} /> </div> <div> {button} </div> {error} </div> ); } resetError() { this.setState({ error: null }); } subscribe() { const email = this.refs.mail.value; if (!email) { this.setState({ error: "Please be a darling and enter your e-mail address first." }); } else { if (email.match(/[^@]+@[^.]+/)) { this.submitEmail(email); } else { this.setState({ error: "That address looks a bit funky!" }); } } } submitEmail(email) { var request = new XMLHttpRequest(); request.onreadystatechange = () => { if (request.readyState === 4) { this.handleResponse(request); } }; request.open('GET', 'https://sector4-server.herokuapp.com/subscribe/' + email, true); request.send(); this.setState({ loading: true }); } handleResponse(request) { let handled = false; if (request.status === 200) { const response = JSON.parse(request.responseText); if (response.status === 'ok') { this.setState({ error: null, loading: false }); handled = true; } } if (!handled) { this.setState({ error: "Whoops! You caught us with our pantyhose down. Can you try again later?", loading: false }); } } }
static/scripts/components/DayWelfareUserList.js
minhuaF/bcb-koa2
import React from 'react'; const UserList = React.createClass({ render: function(){ return ( <div> <p className="mrfl-text">今天又143位用户获得加息</p> <div className="prize-winner"> <ul> <li>让xx 刚刚领取了 +0.5%</li> <li>叶xx 刚刚领取了 +0.1%</li> <li>易xx 刚刚领取了 +0.2% </li> </ul> </div> </div> ) } }); module.exports = UserList;
example/react-user/components/profile.js
jsful/treeful
import React, { Component } from 'react'; import Treeful from '../../../src/treeful'; export default class Profile extends Component { constructor() { super(); this.state = { username: Treeful.get('username'), isLoggedIn: Treeful.get('login') }; } componentDidMount() { this.unsubscribe = Treeful.subscribe('user', this.userChanged.bind(this)); } componentWillUnmount() { this.unsubscribe(); } userChanged(data, node) { switch(node) { case 'login': this.setState({ isLoggedIn: data }); break; case 'username': this.setState({ username: data }); break; } } render() { return ( <div className='section'> <h2>User Profile</h2> <p>Username: <b>{this.state.username}</b></p> <br /> <p>{this.state.isLoggedIn ? 'Logged in' : 'Not Logged In'}</p> </div> ); } }
views/decoration_toggle.js
Dangku/black-screen
import React from 'react'; export default React.createClass({ getInitialState() { return {enabled: this.props.invocation.state.decorate}; }, handleClick(event) { stopBubblingUp(event); var newState = !this.state.enabled; this.setState({enabled: newState}); this.props.invocation.setState({decorate: newState}); }, render() { var classes = ['decoration-toggle']; if (!this.state.enabled) { classes.push('disabled'); } return ( <a href="#" className={classes.join(' ')} onClick={this.handleClick}> <i className="fa fa-magic"></i> </a> ); } });
assets/Admin/components/Navbar.js
janta-devs/nyumbani
import React, { Component } from 'react'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import Actions from '../../DataStore/Actions'; //material-ui elements that are essential for the pop-up menu import Popover from 'material-ui/Popover'; import Menu from 'material-ui/Menu'; import MenuItem from 'material-ui/MenuItem'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import $ from 'jquery'; class Navbar extends Component{ constructor( context, props ){ super( context, props ); this.state = { open: false } this.store = this.getLocalStorage(); } handleTouchTap( e ){ e.preventDefault(); (this.state.open === false ) ? this.setState({ open: true, anchorEl: e.currentTarget }) : this.setState({ open: false }); } handleClose(){ this.setState({ open: false }); } handleClick( e ){ e.preventDefault(); var el = e.target; var text = $( el ).text(); } getLocalStorage(){ try { var localstore = localStorage.getItem('JantaAccountUser'); return JSON.parse(localstore); } catch(exception) { return false; } } render(){ const profileStyle = { height: '70px', minWidth: '60px', overFlow: 'hidden' }; const NavBarStyle = { position: 'fixed', zIndex: '100' }; var count = 0; if( this.props.Messages.length !== 0 ){ const arr = this.props.Messages; arr.map((value) => { return ( value.status === 'unread') ? count = count + 1 : false; }) } return( <div className="mdl-layout mdl-js-layout mdl-layout--fixed-header" id="nav-bar"> <header className="mdl-layout__header"> <div className="mdl-layout__header-row"> <span className="mdl-layout-title"> <div className="logo-home" > </div> </span> <div className="mdl-layout-spacer"> </div> <Link to = {`/nyumbani/index.php/home/timeline/MyOrders/`} className = 'mdl-button ' >My Orders </Link> <Link to = {`/nyumbani/index.php/home/timeline/Messages/`} className = 'mdl-button ' >Messages{(count === 0) ? "": <div className="material-icons mdl-badge mdl-badge--overlap" data-badge={count}>notifications</div>} </Link> <nav className="mdl-navigation"> <button className="mdl-button mdl-js-button mdl-button--icon" style={profileStyle}> <img className="demo-avatar" src={(!this.props.AccountUser) ? this.store.profile_photo : this.props.AccountUser.profile_photo} alt ={this.props.AccountUser.profile_photo} onClick={this.handleTouchTap.bind(this)} /> </button> <MuiThemeProvider> <Popover open={this.state.open} anchorEl={this.state.anchorEl} anchorOrigin={{horizontal: 'left', vertical: 'bottom'}} targetOrigin={{horizontal: 'left', vertical: 'top'}} onRequestClose={this.handleClose.bind(this)} > <Menu> <MenuItem primaryText="Home" containerElement={<Link to={`/nyumbani/index.php/admin/main/`}/>}/> <MenuItem primaryText="Sign out" href="/nyumbani/index.php/home/logout" /> </Menu> </Popover> </MuiThemeProvider> </nav> </div> </header> </div> ) } } function mapStateToProps( state ){ return state; } function mapDispatchToProps(dispatch){ return{ Actions: bindActionCreators( Actions, dispatch ) } } export default connect(mapStateToProps, mapDispatchToProps)(Navbar);
templates/rubix/rubix-bootstrap/src/DropdownButton.js
jeffthemaximum/Teachers-Dont-Pay-Jeff
import React from 'react'; import ReactDOM from 'react-dom'; import classNames from 'classnames'; import RDropdownButton from 'react-bootstrap/lib/DropdownButton'; import isBrowser from './isBrowser'; import isTouchDevice from './isTouchDevice'; var requestFrame = null, rAF = () => {}, cAF = () => {}; if (isBrowser()) { requestFrame = require('request-frame'); rAF = requestFrame('request'); cAF = requestFrame('cancel'); } const expectedTypes = ["success","warning","danger","info","default","primary","link"]; function isBtnOfType(type) { for (var i = 0; i < expectedTypes.length; i++) { if (expectedTypes[i] === type) { return true; } } return false; } export var DropdownButtonHOC = ComposedComponent => class extends React.Component { static displayName = 'DropdownButton'; static propTypes = { xs: React.PropTypes.bool, sm: React.PropTypes.bool, lg: React.PropTypes.bool, rounded: React.PropTypes.bool, onlyOnHover: React.PropTypes.bool, retainBackground: React.PropTypes.bool, inverse: React.PropTypes.bool, outlined: React.PropTypes.bool, }; render() { var props = {...this.props}; if (this.props.hasOwnProperty('xs')) { props.bsSize = 'xsmall'; delete props.xs; } if (this.props.hasOwnProperty('sm')) { props.bsSize = 'small'; delete props.sm; } if (this.props.hasOwnProperty('lg')) { props.bsSize = 'large'; delete props.lg; } if (this.props.hasOwnProperty('bsStyle') && typeof this.props.bsStyle === 'string') { var styles = this.props.bsStyle.split(/\s|\,/mgi).filter((a) => a); for (var i = 0; i < styles.length; i++) { props.className = classNames(props.className, 'btn-' + styles[i]); if (styles[i] === 'link') { props.bsClass = 'menu-default dropdown'; } else { props.bsClass = 'menu-' + styles[i] + ' dropdown'; } if (isBtnOfType(styles[i])) { props.bsStyle = styles[i]; } else { props.bsStyle = 'default'; } } } if (!props.bsStyle) { props.bsStyle = 'default'; } if (!props.className) { props.className = 'btn-default'; } if (!props.bsClass) { props.bsClass = 'menu-default dropdown'; } if (props.hasOwnProperty('dropup')) { props.bsClass = 'dropup ' + props.bsClass; } if (props.retainBackground) { props.className = classNames(props.className, 'btn-retainBg'); } if (props.rounded) { props.className = classNames(props.className, 'btn-rounded'); } if (props.onlyOnHover) { props.className = classNames(props.className, 'btn-onlyOnHover'); } if (props.inverse || props.retainBackground) { props.className = classNames(props.className, 'btn-inverse'); } if (props.outlined || props.onlyOnHover || props.inverse || props.retainBackground) { props.className = classNames(props.className, 'btn-outlined'); } delete props.retainBackground; delete props.onlyOnHover; delete props.outlined; delete props.rounded; delete props.inverse; delete props.dropup; return ( <ComposedComponent buttonProps={props} /> ); } } @DropdownButtonHOC export var DropdownHoverButtonHOC = ComposedComponent => class extends React.Component { static displayName = 'DropdownHoverButton'; constructor(props) { super(props); this.state = { open: false, }; this._eventObject = { handleEvent: this._handleOver.bind(this), name: 'DropdownHoverEvent', }; this._timeout = null; } _isWithinDropdown(node) { var componentNode = ReactDOM.findDOMNode(this._node); return componentNode.contains(node) || componentNode === node; } _handleOver(e) { if (this._isWithinDropdown(e.target)) { cAF(this._timeout); this.setState({ open: true }); } else { this._timeout = rAF(() => { this.setState({ open: false }); }); } } _onToggle(isOpen) { this.setState({ open: isOpen }); } componentWillUnmount() { if (!isTouchDevice()) { document.removeEventListener('mouseover', this._eventObject); } } componentDidMount() { if (!isTouchDevice()) { rAF(() => { document.addEventListener('mouseover', this._eventObject); }); } } render() { return ( <ComposedComponent ref={ (node) => this._node = node } onToggle={::this._onToggle} open={this.state.open} buttonProps={this.props.buttonProps} /> ); } } @DropdownButtonHOC export default class DropdownButton extends React.Component { render() { return <RDropdownButton {...this.props.buttonProps} />; } }
examples/with-overmind/pages/_app.js
azukaru/next.js
import React from 'react' import App from 'next/app' import { createOvermind, createOvermindSSR, rehydrate } from 'overmind' import { Provider } from 'overmind-react' import { config } from '../overmind' class MyApp extends App { // CLIENT: On initial route // SERVER: On initial route constructor(props) { super(props) const mutations = props.pageProps.mutations || [] if (typeof window !== 'undefined') { // On the client we just instantiate the Overmind instance and run // the "changePage" action this.overmind = createOvermind(config) this.overmind.actions.changePage(mutations) } else { // On the server we rehydrate the mutations to an SSR instance of Overmind, // as we do not want to run any additional logic here this.overmind = createOvermindSSR(config) rehydrate(this.overmind.state, mutations) } } // CLIENT: After initial route, on page change // SERVER: never componentDidUpdate() { // This runs whenever the client routes to a new page this.overmind.actions.changePage(this.props.pageProps.mutations || []) } // CLIENT: On every page change // SERVER: On initial route render() { const { Component } = this.props return ( <Provider value={this.overmind}> <Component /> </Provider> ) } } export default MyApp
assets/jqwidgets/demos/react/app/calendar/rangeselection/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxCalendar from '../../../jqwidgets-react/react_jqxcalendar.js'; class App extends React.Component { componentDidMount() { this.refs.myCalendar.on('change', (event) => { let selection = event.args.range; let log = document.getElementById('log'); log.innerHTML = '<div>From: ' + selection.from.toLocaleDateString() + ' <br/>To: ' + selection.to.toLocaleDateString() + '</div>'; }); let date1 = new Date(); date1.setFullYear(2016, 7, 7); let date2 = new Date(); date2.setFullYear(2016, 7, 15); this.refs.myCalendar.setRange(date1, date2); } render() { return ( <div> <JqxCalendar ref='myCalendar' width={220} height={220} selectionMode={'range'} value={new Date(2016, 7, 7)} /> <div id='log'></div> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
docs/src/app/components/pages/components/List/ExamplePhone.js
barakmitz/material-ui
import React from 'react'; import MobileTearSheet from '../../../MobileTearSheet'; import {List, ListItem} from 'material-ui/List'; import Divider from 'material-ui/Divider'; import CommunicationCall from 'material-ui/svg-icons/communication/call'; import CommunicationChatBubble from 'material-ui/svg-icons/communication/chat-bubble'; import {indigo500} from 'material-ui/styles/colors'; import CommunicationEmail from 'material-ui/svg-icons/communication/email'; const ListExamplePhone = () => ( <MobileTearSheet> <List> <ListItem leftIcon={<CommunicationCall color={indigo500} />} rightIcon={<CommunicationChatBubble />} primaryText="(650) 555 - 1234" secondaryText="Mobile" /> <ListItem insetChildren={true} rightIcon={<CommunicationChatBubble />} primaryText="(323) 555 - 6789" secondaryText="Work" /> </List> <Divider inset={true} /> <List> <ListItem leftIcon={<CommunicationEmail color={indigo500} />} primaryText="aliconnors@example.com" secondaryText="Personal" /> <ListItem insetChildren={true} primaryText="ali_connors@example.com" secondaryText="Work" /> </List> </MobileTearSheet> ); export default ListExamplePhone;
src/components/tvshows/index.js
scholtzm/arnold
import React, { Component } from 'react'; import TvShowGrid from './grid.js'; import LibraryPage from '../library/page.js'; class TvShows extends Component { state = { showSeen: true }; _onShowSeenToggle() { this.setState({ showSeen: !this.state.showSeen }); } render() { return ( <LibraryPage headerIcon='television' headerText='TV Shows' headerSubText='Manage your TV show collection' grid={TvShowGrid} /> ); } } export default TvShows;
docs/src/examples/collections/Menu/Types/index.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Link } from 'react-static' import { Message } from 'semantic-ui-react' import ExampleSection from 'docs/src/components/ComponentDoc/ExampleSection' import ComponentExample from 'docs/src/components/ComponentDoc/ComponentExample' import ShorthandExample from 'docs/src/components/ComponentDoc/ShorthandExample' // TODO: Add example with <Popup> after it will be added const Types = () => ( <ExampleSection title='Types'> <ComponentExample title='Menu' description='A menu.' examplePath='collections/Menu/Types/MenuExampleBasic' /> <ShorthandExample examplePath='collections/Menu/Types/MenuExampleProps' /> <ComponentExample description='Menu item text can be defined with the content prop.' examplePath='collections/Menu/Types/MenuExampleContentProp' /> <ComponentExample description='The name prop will be used for content if neither children nor content props are defined.' examplePath='collections/Menu/Types/MenuExampleNameProp' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleAttached' /> <ComponentExample title='Secondary Menu' description='A menu can adjust its appearance to de-emphasize its contents.' examplePath='collections/Menu/Types/MenuExampleSecondary' /> <ComponentExample title='Pointing' description='A menu can point to show its relationship to nearby content.' examplePath='collections/Menu/Types/MenuExamplePointing' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleSecondaryPointing' /> <ComponentExample title='Tabular' description='A menu can be formatted to show tabs of information.' examplePath='collections/Menu/Types/MenuExampleTabular' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleTabularOnTop' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleTabularOnBottom' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleTabularOnLeft' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleTabularOnRight' /> <ComponentExample title='Text' description='A menu can be formatted for text content.' examplePath='collections/Menu/Types/MenuExampleText' /> <ComponentExample title='Vertical Menu' description='A vertical menu displays elements vertically.' examplePath='collections/Menu/Types/MenuExampleVertical' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleVerticalText' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleVerticalDropdown' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleVerticalPointing' /> <ComponentExample examplePath='collections/Menu/Types/MenuExampleVerticalSecondary' /> <ComponentExample title='Pagination' description='A pagination menu is specially formatted to present links to pages of content.' examplePath='collections/Menu/Types/MenuExamplePagination' > <Message info> For fully featured pagination, see{' '} <Link to='/addons/pagination'>Pagination</Link> addon. </Message> </ComponentExample> </ExampleSection> ) export default Types
app/views/Rankings.js
upbit/pixivfan
'use strict'; import React, { Component } from 'react'; import { StyleSheet, Text, View, FlatList, RefreshControl, ActivityIndicator, Dimensions, AppRegistry } from 'react-native'; import Reactotron from 'reactotron-react-native'; import PixivAPI from '../pixiv_api'; import Illust from './Illust'; import GlobalStore from '../GlobalStore'; export default class Rankings extends Component { static navigationOptions = { title: 'Rankings', }; constructor(props) { super(props) this.api = new PixivAPI(); this.state = { pagination: { loading: false, next_url: null }, illusts: [] } } componentWillMount() { this.columnNumber = 2 this.illust_width = (Dimensions.get('window').width-2) / this.columnNumber GlobalStore.reloadSettings() .then(() => { Reactotron.display({ name: 'Login', preview: GlobalStore.settings.username, value: {user: GlobalStore.settings.username, pass: GlobalStore.settings.password}, }) this.api.auth(GlobalStore.settings.username, GlobalStore.settings.password) .then((response) => { Reactotron.display({ name: 'Login Success', preview: response.user.name, value: {response: response}, important: true }) this._getIllusts() }) }); } _getRankingRequest() { const pagination = { ...this.state.pagination, loading: true } this._update(pagination) } _getRankingSuccess(responseData) { const pagination = { ...this.state.pagination, loading: false, next_url: responseData.next_url } const new_illusts = this.state.illusts ? [ ...this.state.illusts, ...responseData.illusts ] : responseData.illusts Reactotron.display({ name: 'getRankingSuccess', preview: responseData.next_url, value: {pagination: pagination, illusts: new_illusts}, important: true }) this._update(pagination, new_illusts) } _getRankingFailure(error) { Reactotron.error({message: '_getRankingFailure', error: error}) const pagination = { ...this.state.pagination, loading: false } this._update(pagination) } _update(pagination, illusts = null) { const illustsItems = illusts || this.state.illusts this.setState({ pagination: pagination, illusts: illustsItems }) } _getIllusts(req_auth=true) { if (this.state.pagination.loading) { Reactotron.log('loading incomplete, wait...') return } var url = this.state.pagination.next_url ? this.state.pagination.next_url : `https://app-api.pixiv.net/v1/illust/ranking?mode=${GlobalStore.settings.mode}&date=${GlobalStore.settings.date}&filter=for_ios` Reactotron.display({ name: 'getIllusts', preview: `mode=${GlobalStore.settings.mode} date=${GlobalStore.settings.date}`, value: {url: url, settings: GlobalStore.settings} }) this._getRankingRequest() this.api.get(url, req_auth=req_auth) .then(responseData => this._getRankingSuccess(responseData)) .catch(error => this._getRankingFailure(error)) } render() { return ( <FlatList data={this.state.illusts} keyExtractor={(illust, index) => { return illust.id }} refreshing={false} onRefresh={() => { Reactotron.log('onRefresh') this.setState({ pagination: { loading: false, next_url: null }, illusts: [] }, function afterReset () { Reactotron.log('Pull refreshing') this._getIllusts() }) }} onEndReachedThreshold={1} onEndReached={({ distanceFromEnd }) => { Reactotron.log('onEndReached, load more') this._getIllusts() }} renderItem={({item}) => { return ( <Illust illust={item} max_width={this.illust_width} onSelected={(item) => this._onPress(item)} /> ) }} numColumns={this.columnNumber} /> ) } _onPress(illust) { Reactotron.display({ name: 'IllustSelected', preview: illust.title, value: illust }) } };
src/templates/news-index.js
adrienlozano/stephaniewebsite
import React from 'react'; import PageSection from "~/components/page-section"; import Typography from '~/components/typography'; import Heading from '~/components/heading'; import LinkButton from '~/components/link-button'; import { Box } from 'rebass'; import format from 'date-fns/format'; import Pagination from '~/components/pagination'; import NumberLink from '~/components/pagination/number-link'; import Link, { BadgeLink } from '~/components/link'; import { curry } from 'ramda'; import Icon from '~/components/icon'; import {Badge} from 'rebass'; import kebabCase from "~/utils/kebab-case"; import styled from "styled-components"; const toAreaPageUrl = curry((area, page) => { return page === 1 ? `/${area}` : `/${area}/page/${page}`; }); const TagsList = ({tags, path}) =>{ if(!tags) return null; var badgeLinks = tags.map((x, index) => (<BadgeLink key={x} to={`${path}${kebabCase(x)}`}>{x}</BadgeLink>)); return (<span><Icon style={{ marginRight: "10px"}} icon="tag"/>{badgeLinks}</span>); } export default ({data, pathContext}) =>{ const news = data ? data.news.edges.map(x => ({ ...x.node.frontmatter, id:x.node.id, slug: x.node.fields.slug, excerpt: x.node.excerpt })) : []; const { current, total, area } = pathContext; const toPageUrl = toAreaPageUrl(area); var articles = news.map( ({title, excerpt, slug, date, tags, id}) => { return ( <Box key={slug} mb={5} > <Typography component="h4" pb={0} mb={0}>{title}</Typography> <Typography f={1} pt={0} mt={1} color="secondaryAccent">{ format(date, "DD MMM, YYYY")}</Typography> <TagsList tags={tags} path="/news/tags/" /> <Typography>{excerpt}</Typography> <LinkButton href={slug}>Read More</LinkButton> </Box> )}); return ( <PageSection bg="light"> <Heading>News</Heading> {articles} <Pagination current={current} total={total} renderPrevious={ (index, hasPrevious) => (<NumberLink key={`prev_${index}`} to={toPageUrl(index)} disabled={ !hasPrevious }><Icon icon="chevron-double-left"/> previous </NumberLink>) } renderNext={ (index, hasNext) => (<NumberLink key={`next_${index}`} to={toPageUrl(index)} disabled={ !hasNext } >next <Icon icon="chevron-double-right"/> </NumberLink>) } renderPage={ (index) => (<NumberLink key={index} to={toPageUrl(index) }>{index}</NumberLink>) } /> </PageSection> ) } export const pageQuery = graphql` query IndexQuery($skip: Int!, $pageSize: Int!) { news: allMarkdownRemark( skip: $skip, limit: $pageSize, filter:{ fields: { area: { eq: "news"} }} sort: {fields: [frontmatter___date], order: DESC} ) { edges { node { timeToRead excerpt(pruneLength: 350) fields { area, slug } frontmatter { title date, tags, caption, image, date } } } } } `
src/app/modules/students/containers/list.js
Kikonejacob/nodeApp
/** * list grid: * react container for displaying a grid list of level fees: * schema: [fee_code,amount] * (c) 2016 kikone kiswendida */ import GridView,{LinkComponent,COLLECTION_SORT,COLLECTION_FETCH, COLLECTION_FILTER,COLLECTION_SET_PAGE, COLLECTION_SETPAGE_SIZE} from 'components/gridFormView/reduxgridFormView'; import {refreshGrid} from 'lib/grid/actions'; import React from 'react'; import Header from 'components/ModuleHeaderView/ModuleHeaderView'; import Button from 'components/LinkComponent/LinkButtonView'; const BT_DELETE_SELECTED='Delete selected'; const BT_CANCEL='Cancel'; import { connect } from 'react-redux'; var columns=['id','name','email','birth_date']; var columnsMetaData=[{ "columnName": "name", "order": 1, "locked": false, "visible": true, "partialLink":'#students/', "displayName": "Name", 'customComponent': LinkComponent, }, { "columnName": "email", "order": 2, "locked": false, "visible": true, "displayName": "Email" }, { "columnName": "birth_date", "order": 3, "locked": false, "visible": true, "displayName": "Birth date" } ]; class List extends React.Component{ collectionMgr(cmd,options){ switch (cmd) { case COLLECTION_FETCH: case COLLECTION_SORT: case COLLECTION_FILTER: case COLLECTION_SET_PAGE: case COLLECTION_SETPAGE_SIZE: this.props.dispatch(refreshGrid(options,this.props.gridName)); break; default: } } handleActions(e,action){ let selectedRowIds=this.refs.gridlist.refs.SchGrid.state.selectedRowIds; //console.log(selectedRowIds); if (this.props.onAction!=null) { this.props.onAction(action,selectedRowIds,this.props.dispatch); }; } render(){ let {title,description,onAction}=this.props; let header; //console.log(this.props.multiselect); if (!this.props.multiselect) { header=(<Header title= {title} description={description}> <Button link='#students/create' action='new'>Add new </Button> <Button link='#' onLinkAction={this.handleActions.bind(this)} action='multiselect'>Select</Button> </Header>); } else { header= (<Header title= {title} description={description}> <Button link='#' onLinkAction={this.handleActions.bind(this)} action='delete'>{BT_DELETE_SELECTED}</Button> <Button link='#' onLinkAction={this.handleActions.bind(this)} action='cancel_multiselect'>{BT_CANCEL}</Button> </Header>); }{} //columnsMetaData[0].partialLink=columnsMetaData[0].partialLink.replace(':id',this.props.urlgroup); return(<div> {header} <GridView ref='gridlist' {...this.props} columns={columns} columnMetadata={columnsMetaData} collectionMgr={this.collectionMgr.bind(this) } multiselect={this.props.multiselect}/> </div>); }; } function mapStateToProps(state) { const { schGrids} = state; const studentGrid=schGrids['students.grid']; const {results,multiselect, showFilter,showSettings}=studentGrid; return { multiselect, results,showFilter,showSettings }; } export default connect(mapStateToProps)(List);
Paths/React/06.Styling React Components/4-react-styling-components-m4-exercise-files/Before/src/nav.js
phiratio/Pluralsight-materials
import React from 'react' const { func, bool } = React.PropTypes function Nav(props) { return ( <div> <button onClick={props.onPrevious}>&#10094;</button> <button onClick={props.onNext}>&#10095;</button> </div> ) } Nav.propTypes = { onPrevious: func.isRequired, onNext: func.isRequired, hasPrevious: bool, hasNext: bool } export default Nav
src/scripts/components/pages/favourites/favourites.js
jshack3r/ws-react-starter
import React from 'react'; import LinksComponent from '../../common/links/links'; // stateless component export default (props) => { return ( <div> <div className="container container--page-title"><h1>Favourite links</h1></div> <LinksComponent showFavourites={true} /> </div> ) };
examples/huge-apps/routes/Course/routes/Assignments/routes/Assignment/components/Assignment.js
bmathews/react-router
import React from 'react'; class Assignment extends React.Component { //static loadProps (params, cb) { //cb(null, { //assignment: COURSES[params.courseId].assignments[params.assignmentId] //}); //} render () { //var { title, body } = this.props.assignment; var { courseId, assignmentId } = this.props.params; var { title, body } = COURSES[courseId].assignments[assignmentId] return ( <div> <h4>{title}</h4> <p>{body}</p> </div> ); } } export default Assignment;
modules/components/Admin/components/AddBook/index.js
hmltnbrn/classroom-library
import React from 'react'; import Paper from 'material-ui/Paper'; import TextField from 'material-ui/TextField'; import FlatButton from 'material-ui/FlatButton'; import Snackbar from 'material-ui/Snackbar'; import * as libraryService from './../../../../services/library-service'; class AddBook extends React.Component { constructor(props) { super(props); this.state = { title: "", author: "", genre: "", level: "", numberIn: "", snackOpen: false, titleStatus: false, authorStatus: false, genreStatus: false, levelStatus: false, numberInStatus: false } } handleTitleChange(event) { this.setState({title: event.target.value}); } handleAuthorChange(event) { this.setState({author: event.target.value}); } handleGenreChange(event) { this.setState({genre: event.target.value}); } handleLevelChange(event) { this.setState({level: event.target.value}); } handleNumberInChange(event) { this.setState({numberIn: event.target.value}); } handleKeyDown(event) { if (event.keyCode === 13) this.handleAddBook(); } handleAddBook() { this.state.title === "" ? this.setState({titleStatus: "Required field"}) : this.setState({titleStatus: false}); this.state.author === "" ? this.setState({authorStatus: "Required field"}) : this.setState({authorStatus: false}); if(this.state.numberIn === "") { this.setState({numberInStatus: "Required field"}); } else if (this.state.numberIn <= 0) { this.setState({numberInStatus: "Cannot be zero or negative"}); } else { this.setState({numberInStatus: false}); } if (this.state.title !== "" && this.state.author !== "" && this.state.numberIn > 0 && this.state.numberIn !== "") { this.addBook(); } } addBook() { libraryService.addBook({title: this.state.title, author: this.state.author, genre: this.state.genre, level: this.state.level, numberIn: this.state.numberIn}) .then(data => { this.setState({ titleStatus: data.status, authorStatus: false, genreStatus: false, levelStatus: false, numberInStatus: false }, this.handleAfterInsert) }); } handleAfterInsert() { if (this.state.titleStatus === false) { this.setState({ title: "", author: "", genre: "", level: "", numberIn: "", snackOpen: true }, this.props.findBooks); } } handleClear() { this.setState({ title: "", author: "", genre: "", level: "", numberIn: "", titleStatus: false, authorStatus: false, genreStatus: false, levelStatus: false, numberInStatus: false }); } closeSnackbar() { this.setState({snackOpen: false}); } render() { return ( <div> <Paper className="admin-paper"> <div className="title">Create New Book</div> <div className="flex flex-column align-center"> <TextField hintText="Enter Title (e.g., 1984)" floatingLabelText="Title *" errorText={this.state.titleStatus} onKeyDown={this.handleKeyDown.bind(this)} value={this.state.title} fullWidth={true} onChange={this.handleTitleChange.bind(this)}/> <TextField hintText="Enter Author (e.g., George Orwell)" floatingLabelText="Author *" errorText={this.state.authorStatus} onKeyDown={this.handleKeyDown.bind(this)} value={this.state.author} fullWidth={true} onChange={this.handleAuthorChange.bind(this)}/> <TextField hintText="Enter Genre (e.g., Classics)" floatingLabelText="Genre" errorText={this.state.genreStatus} onKeyDown={this.handleKeyDown.bind(this)} value={this.state.genre} fullWidth={true} onChange={this.handleGenreChange.bind(this)}/> <TextField hintText="Enter Reading Level (e.g., Z)" floatingLabelText="Reading Level" errorText={this.state.levelStatus} onKeyDown={this.handleKeyDown.bind(this)} value={this.state.level} fullWidth={true} onChange={this.handleLevelChange.bind(this)}/> <TextField hintText="Enter Number of Books (e.g., 2)" floatingLabelText="Number of Books *" type="number" min="0" step="1" errorText={this.state.numberInStatus} onKeyDown={this.handleKeyDown.bind(this)} value={this.state.numberIn} fullWidth={true} onChange={this.handleNumberInChange.bind(this)}/><br /> </div> <div className="flex justify-center"> <FlatButton label="Clear" type="submit" primary={true} onTouchTap={this.handleClear.bind(this)}/> <FlatButton label="Add Book" type="submit" primary={true} onTouchTap={this.handleAddBook.bind(this)}/> </div> <div className="flex justify-start"> <p className="required">* required field</p> </div> </Paper> <Snackbar open={this.state.snackOpen} message="Book added" action="Close" onActionTouchTap={this.closeSnackbar.bind(this)} autoHideDuration={4000} onRequestClose={this.closeSnackbar.bind(this)}/> </div> ); } }; export default AddBook;
fields/types/datearray/DateArrayFilter.js
dvdcastro/keystone
import React from 'react'; import { findDOMNode } from 'react-dom'; import moment from 'moment'; import DayPicker from 'react-day-picker'; import { FormField, FormInput, FormRow, FormSelect } from 'elemental'; const PRESENCE_OPTIONS = [ { label: 'At least one element', value: 'some' }, { label: 'No element', value: 'none' }, ]; const MODE_OPTIONS = [ { label: 'On', value: 'on' }, { label: 'After', value: 'after' }, { label: 'Before', value: 'before' }, { label: 'Between', value: 'between' }, ]; var DayPickerIndicator = React.createClass({ render () { return ( <span className="DayPicker-Indicator"> <span className="DayPicker-Indicator__border" /> <span className="DayPicker-Indicator__bg" /> </span> ); }, }); function getDefaultValue () { return { mode: MODE_OPTIONS[0].value, presence: PRESENCE_OPTIONS[0].value, value: moment(0, 'HH').format(), before: moment(0, 'HH').format(), after: moment(0, 'HH').format(), }; } var DateFilter = React.createClass({ displayName: 'DateFilter', propTypes: { filter: React.PropTypes.shape({ mode: React.PropTypes.oneOf(MODE_OPTIONS.map(i => i.value)), presence: React.PropTypes.string, }), }, statics: { getDefaultValue: getDefaultValue, }, getDefaultProps () { return { format: 'DD-MM-YYYY', filter: getDefaultValue(), value: moment().startOf('day').toDate(), }; }, getInitialState () { return { activeInputField: 'after', month: new Date(), // The month to display in the calendar }; }, componentDidMount () { // focus the text input if (this.props.filter.mode === 'between') { findDOMNode(this.refs[this.state.activeInputField]).focus(); } else { findDOMNode(this.refs.input).focus(); } }, updateFilter (value) { this.props.onChange({ ...this.props.filter, ...value }); }, selectPresence (presence) { this.updateFilter({ presence }); findDOMNode(this.refs.input).focus(); }, selectMode (mode) { this.updateFilter({ mode }); if (mode === 'between') { setTimeout(() => { findDOMNode(this.refs[this.state.activeInputField]).focus(); }, 200); } else { findDOMNode(this.refs.input).focus(); } }, handleInputChange (e) { const { value } = e.target; let { month } = this.state; // Change the current month only if the value entered by the user is a valid // date, according to the `L` format if (moment(value, 'L', true).isValid()) { month = moment(value, 'L').toDate(); } this.updateFilter({ value: value }); this.setState({ month }, this.showCurrentDate); }, setActiveField (field) { this.setState({ activeInputField: field, }); }, switchBetweenActiveInputFields (e, day, modifiers) { if (modifiers && modifiers.disabled) return; const { activeInputField } = this.state; const send = {}; send[activeInputField] = day; this.updateFilter(send); const newActiveField = (activeInputField === 'before') ? 'after' : 'before'; this.setState( { activeInputField: newActiveField }, () => { findDOMNode(this.refs[newActiveField]).focus(); } ); }, selectDay (e, day, modifiers) { if (modifiers && modifiers.disabled) return; this.updateFilter({ value: day }); }, showCurrentDate () { this.refs.daypicker.showMonth(this.state.month); }, renderControls () { let controls; const { field, filter } = this.props; const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0]; const placeholder = field.label + ' is ' + mode.label.toLowerCase() + '...'; // DayPicker stuff const modifiers = { selected: (day) => moment(filter.value).isSame(day), }; if (mode.value === 'between') { controls = ( <div> <FormRow> <FormField width="one-half"> <FormInput ref="after" placeholder="From" onFocus={(e) => { this.setActiveField('after'); }} value={moment(filter.after).format(this.props.format)} /> </FormField> <FormField width="one-half"> <FormInput ref="before" placeholder="To" onFocus={(e) => { this.setActiveField('before'); }} value={moment(filter.before).format(this.props.format)} /> </FormField> </FormRow> <div style={{ position: 'relative' }}> <DayPicker modifiers={modifiers} className="DayPicker--chrome" onDayClick={this.switchBetweenActiveInputFields} /> <DayPickerIndicator /> </div> </div> ); } else { controls = ( <div> <FormField> <FormInput ref="input" placeholder={placeholder} value={moment(filter.value).format(this.props.format)} onChange={this.handleInputChange} onFocus={this.showCurrentDate} /> </FormField> <div style={{ position: 'relative' }}> <DayPicker ref="daypicker" modifiers={modifiers} className="DayPicker--chrome" onDayClick={this.selectDay} /> <DayPickerIndicator /> </div> </div> ); } return controls; }, render () { const { filter } = this.props; const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0]; const presence = PRESENCE_OPTIONS.filter(i => i.value === filter.presence)[0]; return ( <div> <FormSelect options={PRESENCE_OPTIONS} onChange={this.selectPresence} value={presence.value} /> <FormSelect options={MODE_OPTIONS} onChange={this.selectMode} value={mode.value} /> {this.renderControls()} </div> ); }, }); module.exports = DateFilter;
shared/components/HTML/index.js
thehink/equilab-web
/* eslint-disable react/no-danger */ /* eslint-disable jsx-a11y/html-has-lang */ import React from 'react'; import PropTypes from 'prop-types'; /** * The is the HTML shell for our React Application. */ function HTML(props) { const { htmlAttributes, headerElements, bodyElements, appBodyString } = props; return ( <html {...htmlAttributes}> <head> {headerElements} </head> <body> <div id="app" dangerouslySetInnerHTML={{ __html: appBodyString }} /> {bodyElements} </body> </html> ); } HTML.propTypes = { // eslint-disable-next-line react/forbid-prop-types htmlAttributes: PropTypes.object, headerElements: PropTypes.node, bodyElements: PropTypes.node, appBodyString: PropTypes.string, }; HTML.defaultProps = { htmlAttributes: null, headerElements: null, bodyElements: null, appBodyString: '', }; // EXPORT export default HTML;
app/containers/ViewProfiles/index.js
theClubhouse-Augusta/JobWeasel-FrontEnd
/* * * ViewProfiles * */ import React from 'react'; import Helmet from 'react-helmet'; import {Link} from 'react-router-dom'; import './style.css'; import './styleM.css'; import '../../global.css'; import LeftIcon from 'react-icons/lib/fa/chevron-left'; import RightIcon from 'react-icons/lib/fa/chevron-right'; import Nav from 'components/Nav'; export default class ViewProfiles extends React.PureComponent { constructor () { super(); this.state = { search:"", searchResults:[], nextPage: 1, currentPage: 0, lastPage: 1, users:[] } } componentWillMount () { this.getUsers(); } getUsers = () => { let nextPage = this.state.nextPage; fetch('http://localhost:8000/api/getUsers?page='+nextPage, { method: 'GET' }) .then(function(response) { return response.json(); }) .then(function(json) { if(json.error) { console.log(json.error) } else { if(json.current_page != json.last_page) { nextPage = nextPage + 1; } this.setState({ nextPage: nextPage, lastPage: json.users.last_page, currentPage: json.users.current_page, searchResults: json.users.data }) } }.bind(this)); } previousPageclick = () => { if(this.state.nextPage > 1) { let pageNum = this.state.nextPage; pageNum = pageNum - 2; this.setState({ nextPage:pageNum }, function() { this.getUsers(); }) } } handleSearch = (event) => { this.setState({ search: event.target.value }) } previousPageclick = () => { if(this.state.nextPage > 1) { let pageNum = this.state.nextPage; pageNum = pageNum - 2; this.setState({ nextPage:pageNum }, function() { this.getUsers(); }) } } render() { return ( <div className="viewProfilesContainer"> <Helmet title="ViewProfiles" meta={[ { name: 'description', content: 'Description of ViewProfiles' }]}/> <Nav/> <div className="usersFullOverlay"> </div> <div className="usersListTitle">Users List </div> <div className="usersList"> <div className="usersDisplay"> {this.state.searchResults.map((t,i) => ( <Link key={i} to={`/Profile/${t.id}`} className="viewResult"> User: {t.name} <p>{t.location}</p> </Link> ))} </div> </div> <LeftIcon className="previousIcon" onClick={this.previousPageclick} /> <RightIcon className="nextIcon" onClick={this.getUsers} /> </div> ); } } ViewProfiles.contextTypes = { router: React.PropTypes.object };
src/svg-icons/file/create-new-folder.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileCreateNewFolder = (props) => ( <SvgIcon {...props}> <path d="M20 6h-8l-2-2H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-1 8h-3v3h-2v-3h-3v-2h3V9h2v3h3v2z"/> </SvgIcon> ); FileCreateNewFolder = pure(FileCreateNewFolder); FileCreateNewFolder.displayName = 'FileCreateNewFolder'; FileCreateNewFolder.muiName = 'SvgIcon'; export default FileCreateNewFolder;
src/example/Pages/Introduction/Features.js
mappmechanic/codelab-book
import React, { Component } from 'react'; import ReactMarkdown from 'react-markdown'; class Features extends Component { render() { const markdown = `## Features I want this repo to be useful to many Developers/Trainers, so just go through the existing set of features which you can use now or suggest new ones. Current Features: - Multi Level Dockable Menu for Easy Content Navigation - Configurable Menu Title & Book Title - JSON Driven CodeLab Book for Showing Pages - Supporting Basic React Components - Support for HTML Styled Pages - Supporting Code Highlight using highlight.js Module - Supporting MarkDown in any Page using [react-markdown](https://github.com/rexxars/react-markdown) module by [Espen](https://github.com/rexxars) Future Features: - Quick Navigation to Next & Previous - Status Marking - Presentation Link - Trainer/Author Dedicated Section - <Suggest_By_Creating_Issue>`; return ( <div> <ReactMarkdown source={markdown} /> </div> ); } } export default Features;
src/pages/kitson.js
vitorbarbosa19/ziro-online
import React from 'react' import BrandGallery from '../components/BrandGallery' export default () => ( <BrandGallery brand='Kitson' /> )
src/pages/layout.js
ShantanuShirpure/Portfolio
import React from 'react' import LeftNav from './../components/layout/leftNav' import ContentPane from './../components/layout/contentPane' export default class Layout extends React.Component { render() { // const { title } = this.props; return ( <div class="container-fluid"> <LeftNav/> <ContentPane/> </div> ); } }
packages/mineral-ui-icons/src/IconHttps.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 IconHttps(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z"/> </g> </Icon> ); } IconHttps.displayName = 'IconHttps'; IconHttps.category = 'action';
src/app/containers/BaseContainer.js
djstein/modern-react
import React, { Component } from 'react'; import BaseComponent from '../components/BaseComponent'; import { connect } from 'react-redux'; class PreviewContainer extends Component { render() { return <BaseComponent /> } } function mapStateToProps(state, ownProps) { return {} } export default connect(mapStateToProps)(PreviewContainer);
react-flux-mui/js/material-ui/src/svg-icons/image/flash-off.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFlashOff = (props) => ( <SvgIcon {...props}> <path d="M3.27 3L2 4.27l5 5V13h3v9l3.58-6.14L17.73 20 19 18.73 3.27 3zM17 10h-4l4-8H7v2.18l8.46 8.46L17 10z"/> </SvgIcon> ); ImageFlashOff = pure(ImageFlashOff); ImageFlashOff.displayName = 'ImageFlashOff'; ImageFlashOff.muiName = 'SvgIcon'; export default ImageFlashOff;
client/node_modules/react-error-overlay/lib/containers/StackTrace.js
bourdakos1/Visual-Recognition-Tool
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import StackFrame from './StackFrame'; import Collapsible from '../components/Collapsible'; import { isInternalFile } from '../utils/isInternalFile'; import { isBultinErrorName } from '../utils/isBultinErrorName'; var traceStyle = { fontSize: '1em', flex: '0 1 auto', minHeight: '0px', overflow: 'auto' }; var StackTrace = function (_Component) { _inherits(StackTrace, _Component); function StackTrace() { _classCallCheck(this, StackTrace); return _possibleConstructorReturn(this, (StackTrace.__proto__ || Object.getPrototypeOf(StackTrace)).apply(this, arguments)); } _createClass(StackTrace, [{ key: 'renderFrames', value: function renderFrames() { var _props = this.props, stackFrames = _props.stackFrames, errorName = _props.errorName, contextSize = _props.contextSize, launchEditorEndpoint = _props.launchEditorEndpoint; var renderedFrames = []; var hasReachedAppCode = false, currentBundle = [], bundleCount = 0; stackFrames.forEach(function (frame, index) { var fileName = frame.fileName, sourceFileName = frame._originalFileName; var isInternalUrl = isInternalFile(sourceFileName, fileName); var isThrownIntentionally = !isBultinErrorName(errorName); var shouldCollapse = isInternalUrl && (isThrownIntentionally || hasReachedAppCode); if (!isInternalUrl) { hasReachedAppCode = true; } var frameEle = React.createElement(StackFrame, { key: 'frame-' + index, frame: frame, contextSize: contextSize, critical: index === 0, showCode: !shouldCollapse, launchEditorEndpoint: launchEditorEndpoint }); var lastElement = index === stackFrames.length - 1; if (shouldCollapse) { currentBundle.push(frameEle); } if (!shouldCollapse || lastElement) { if (currentBundle.length === 1) { renderedFrames.push(currentBundle[0]); } else if (currentBundle.length > 1) { bundleCount++; renderedFrames.push(React.createElement( Collapsible, { key: 'bundle-' + bundleCount }, currentBundle )); } currentBundle = []; } if (!shouldCollapse) { renderedFrames.push(frameEle); } }); return renderedFrames; } }, { key: 'render', value: function render() { return React.createElement( 'div', { style: traceStyle }, this.renderFrames() ); } }]); return StackTrace; }(Component); export default StackTrace;
src/svg-icons/communication/call.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationCall = (props) => ( <SvgIcon {...props}> <path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/> </SvgIcon> ); CommunicationCall = pure(CommunicationCall); CommunicationCall.displayName = 'CommunicationCall'; CommunicationCall.muiName = 'SvgIcon'; export default CommunicationCall;
examples/src/components/Contributors.js
stephennyu/select-react
import React from 'react'; import Select from 'react-select'; const CONTRIBUTORS = require('../data/contributors'); const MAX_CONTRIBUTORS = 6; const ASYNC_DELAY = 500; const Contributors = React.createClass({ displayName: 'Contributors', propTypes: { label: React.PropTypes.string, }, getInitialState () { return { multi: true, value: [CONTRIBUTORS[0]], }; }, onChange (value) { this.setState({ value: value, }); }, switchToMulti () { this.setState({ multi: true, value: [this.state.value], }); }, switchToSingle () { this.setState({ multi: false, value: this.state.value[0], }); }, getContributors (input, callback) { input = input.toLowerCase(); var options = CONTRIBUTORS.filter(i => { return i.github.substr(0, input.length) === input; }); var data = { options: options.slice(0, MAX_CONTRIBUTORS), complete: options.length <= MAX_CONTRIBUTORS, }; setTimeout(function() { callback(null, data); }, ASYNC_DELAY); }, gotoContributor (value, event) { window.open('https://github.com/' + value.github); }, render () { return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select.Async multi={this.state.multi} value={this.state.value} onChange={this.onChange} onValueClick={this.gotoContributor} valueKey="github" labelKey="name" loadOptions={this.getContributors} /> <div className="checkbox-list"> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.multi} onChange={this.switchToMulti}/> <span className="checkbox-label">Multiselect</span> </label> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={!this.state.multi} onChange={this.switchToSingle}/> <span className="checkbox-label">Single Value</span> </label> </div> <div className="hint">This example implements custom label and value properties, async options and opens the github profiles in a new window when values are clicked</div> </div> ); } }); module.exports = Contributors;
lib/clients/index.js
openstardrive/flight-director
import React from 'react' import { connect } from 'react-redux' import Client from './client' require('./index.css') class Clients extends React.Component { render() { let clients = [<div key='none'>Not connected to server.</div>] if (this.props.clients.length > 0) { clients = this.props.clients.map(x => <Client key={x.id} {...x} />) } return ( <div id="clients"> <h2>Clients</h2> <div className="clientList"> {clients} </div> </div> ) } } const convertStateToProps = (state) => { return {clients: state.server.clients || [] } } export default connect(convertStateToProps)(Clients)
app/javascript/mastodon/features/ui/components/column_header.js
honpya/taketodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; export default class ColumnHeader extends React.PureComponent { static propTypes = { icon: PropTypes.string, type: PropTypes.string, active: PropTypes.bool, onClick: PropTypes.func, columnHeaderId: PropTypes.string, }; handleClick = () => { this.props.onClick(); } render () { const { icon, type, active, columnHeaderId } = this.props; let iconElement = ''; if (icon) { iconElement = <i className={`fa fa-fw fa-${icon} column-header__icon`} />; } return ( <h1 className={classNames('column-header', { active })} id={columnHeaderId || null}> <button onClick={this.handleClick}> {iconElement} {type} </button> </h1> ); } }
src/react-ultimate-pagination-bootstrap-4.js
ultimate-pagination/react-ultimate-pagination-bootstrap-4
import React from 'react'; import {createUltimatePagination, ITEM_TYPES} from 'react-ultimate-pagination'; const WrapperComponent = ({children}) => ( <ul className="pagination">{children}</ul> ); const withPreventDefault = (fn) => (event) => { event.preventDefault(); fn(); } const Page = ({value, isActive, onClick}) => ( <li className={isActive ? 'page-item active' : 'page-item'}> <a className="page-link" href="#" onClick={withPreventDefault(onClick)}>{value}</a> </li> ); const Ellipsis = ({onClick}) => ( <li className="page-item"> <a className="page-link" href="#" onClick={withPreventDefault(onClick)}>...</a> </li> ); const FirstPageLink = ({onClick}) => ( <li className="page-item"> <a className="page-link" href="#" onClick={withPreventDefault(onClick)}>&laquo;</a> </li> ); const PreviousPageLink = ({onClick}) => ( <li className="page-item"> <a className="page-link" href="#" onClick={withPreventDefault(onClick)}>&lsaquo;</a> </li> ); const NextPageLink = ({onClick}) => ( <li className="page-item"> <a className="page-link" href="#" onClick={withPreventDefault(onClick)}>&rsaquo;</a> </li> ); const LastPageLink = ({onClick}) => ( <li className="page-item"> <a className="page-link" href="#" onClick={withPreventDefault(onClick)}>&raquo;</a> </li> ); const itemTypeToComponent = { [ITEM_TYPES.PAGE]: Page, [ITEM_TYPES.ELLIPSIS]: Ellipsis, [ITEM_TYPES.FIRST_PAGE_LINK]: FirstPageLink, [ITEM_TYPES.PREVIOUS_PAGE_LINK]: PreviousPageLink, [ITEM_TYPES.NEXT_PAGE_LINK]: NextPageLink, [ITEM_TYPES.LAST_PAGE_LINK]: LastPageLink }; const UltimatePaginationBootstrap4 = createUltimatePagination({itemTypeToComponent, WrapperComponent}); export default UltimatePaginationBootstrap4;
src/main/resources/public/js/components/rating.js
SICTIAM/ozwillo-portal
'use strict'; import React from 'react'; import PropTypes from 'prop-types'; const Rating = require('react-rating'); export default class RatingWrapper extends React.PureComponent{ render() { const {rateable, rating} = this.props; let empty = React.createElement('img', { src: '/img/star-empty.png', className: 'icon' }); let full = React.createElement('img', { src: '/img/star-yellow.png', className: 'icon' }); return ( <Rating start={0} stop={5} step={1} readonly={!rateable} initialRate={rating} onChange={(rate) => this.props.rate(rate)} empty={empty} full={full}/> ); } }; RatingWrapper.propType ={ rating: PropTypes.number.isRequired, rateable: PropTypes.bool.isRequired, rate: PropTypes.func.isRequired };
client/components/Comments.js
profoundhub/FCC-Voting-App
import React from 'react'; const Comments = React.createClass({ renderComment(comment, i) { return ( <div className="comment" key={i}> <p> <strong>{comment.user}</strong> {comment.text} <button className="remove-comment">&times;</button> </p> </div> ) }, render() { return ( <div className="comments"> </div> ) } }); export default Comments;
app/components/CameraComponents/BigPicModal.js
MPDL/LabCam
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import { Platform, TouchableOpacity, Image, StatusBar, StyleSheet } from 'react-native'; import { isIphoneX } from '../iphoneXHelper'; class BigPicModal extends React.Component { render() { const { toggleBigPic, uri } = this.props; const photoLayerStyle = Platform.OS === 'android' ? styles.photoLayer : isIphoneX() ? styles.photoLayerIosX : styles.photoLayerIos; return ( <TouchableOpacity style={photoLayerStyle} onPress={toggleBigPic}> <Image style={styles.bigPic} source={{ uri }} /> </TouchableOpacity> ); } } BigPicModal.propTypes = { toggleBigPic: PropTypes.func.isRequired, uri: PropTypes.string.isRequired, }; const mapStateToProps = state => ({ netOption: state.upload.netOption, ocrTextOnPause: state.upload.ocrTextOnPause, }); export default connect(mapStateToProps)(BigPicModal); const styles = StyleSheet.create({ photoLayer: { position: 'absolute', top: StatusBar.currentHeight, left: 0, right: 0, bottom: 0, width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center', backgroundColor: 'black', zIndex: 99, }, photoLayerIos: { position: 'absolute', top: 24, left: 0, right: 0, bottom: 0, width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center', backgroundColor: 'black', zIndex: 99, }, photoLayerIosX: { position: 'absolute', top: 40, left: 0, right: 0, bottom: 0, width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center', backgroundColor: 'black', zIndex: 99, }, bigPic: { width: '100%', height: '100%', resizeMode: 'contain', }, });
packages/generator-react-server/generators/app/templates/pages/hello-world.js
doug-wade/react-server
import React from 'react'; import HelloWorld from '../components/hello-world'; export default class SimplePage { getElements() { return <HelloWorld/>; } getMetaTags() { return [ {charset: 'utf8'}, {'http-equiv': 'x-ua-compatible', 'content': 'ie=edge'}, {name: 'viewport', content: 'width=device-width, initial-scale=1'}, {name: 'description', content: 'hello world, powered by React Server'}, {name: 'generator', content: 'React Server'}, ]; } }
src/routes/Templates/components/Templates/Templates.js
prescottprue/devshare-site
import React from 'react' import classes from './Templates.scss' export const Templates = () => ( <div className={classes['Templates']}> <h4>Templates</h4> </div> ) export default Templates
app/components/IssueIcon/index.js
anhldbk/react-boilerplate
import React from 'react'; function IssueIcon(props) { return ( <svg height="1em" width="0.875em" className={props.className} > <path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z m1 3H6v5h2V4z m0 6H6v2h2V10z" /> </svg> ); } IssueIcon.propTypes = { className: React.PropTypes.string, }; export default IssueIcon;
src/pages/Calendar/index.js
bogas04/SikhJS
import React from 'react'; import Toolbar from '../../components/Toolbar'; export default () => ( <div> <Toolbar title="Sikh Calendar" /> <div>Work in progress</div> </div> );
examples/confirming-navigation/app.js
nvartolomei/react-router
import React from 'react' import { render } from 'react-dom' import { browserHistory, Router, Route, Link, withRouter } from 'react-router' const App = React.createClass({ render() { return ( <div> <ul> <li><Link to="/dashboard" activeClassName="active">Dashboard</Link></li> <li><Link to="/form" activeClassName="active">Form</Link></li> </ul> {this.props.children} </div> ) } }) const Dashboard = React.createClass({ render() { return <h1>Dashboard</h1> } }) const Form = withRouter( React.createClass({ componentWillMount() { this.props.router.setRouteLeaveHook( this.props.route, this.routerWillLeave ) }, getInitialState() { return { textValue: 'ohai' } }, routerWillLeave() { if (this.state.textValue) return 'You have unsaved information, are you sure you want to leave this page?' }, handleChange(event) { this.setState({ textValue: event.target.value }) }, handleSubmit(event) { event.preventDefault() this.setState({ textValue: '' }, () => { this.props.router.push('/') }) }, render() { return ( <div> <form onSubmit={this.handleSubmit}> <p>Click the dashboard link with text in the input.</p> <input type="text" ref="userInput" value={this.state.textValue} onChange={this.handleChange} /> <button type="submit">Go</button> </form> </div> ) } }) ) render(( <Router history={browserHistory}> <Route path="/" component={App}> <Route path="dashboard" component={Dashboard} /> <Route path="form" component={Form} /> </Route> </Router> ), document.getElementById('example'))
node_modules/re-base/examples/github-notetaker/app/components/Main.js
react-beer/the-beer-store-jsday-facisa
import React from 'react'; import { RouteHandler } from 'react-router'; import SearchGithub from './SearchGithub'; class Main extends React.Component{ render(){ return ( <div className="main-container"> <nav className="navbar navbar-default" role="navigation"> <div className="col-sm-7 col-sm-offset-2" style={{marginTop: 15}}> <SearchGithub /> </div> </nav> <div className="container"> <RouteHandler {...this.props}/> </div> </div> ) } }; export default Main;
docs/src/components/Common.js
oyvindhermansen/easy-state
import React from 'react'; import styled from 'styled-components'; import Link from 'gatsby-link'; const Container = styled.div` max-width: 60rem; width: 100%; padding: 0 1rem; margin: 0 auto; `; const Marginer = styled.div` margin: 2rem 0; `; const GridContainer = styled.div` display: flex; flex-wrap: wrap; justify-content: center; margin: 0 1rem; div { width: 33.33333%; padding: 1rem; @media all and (max-width: 966px) { width: 100%; } } `; const BaseLink = styled(({ activePath, ...rest }) => <Link {...rest} />)``; const BaseButton = BaseLink.extend` padding: 0.8125rem 2rem; font-family: sans-serif; text-decoration: none; cursor: pointer; transition: 0.15s ease-in-out; border-radius: 3px; box-shadow: 10px 10px 5px rgba(0, 0, 0, 0.2); display: inline-block; &:hover { box-shadow: 10px 10px 15px rgba(0, 0, 0, 0.4); } `; const PrimaryButton = BaseButton.extend` background-color: #eae151; color: #000000; `; const SecondaryButton = BaseButton.extend` background-color: #000000; color: #ffffff; `; const ExternalPrimaryButton = PrimaryButton.withComponent('a'); const ExternalSecondaryButton = SecondaryButton.withComponent('a'); export { BaseLink, PrimaryButton, SecondaryButton, ExternalPrimaryButton, ExternalSecondaryButton, Container, Marginer, GridContainer };
others/ant/antd/index1.js
fengnovo/diary
import React from 'react'; import ReactDOM from 'react-dom'; import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, AutoComplete } from 'antd'; const FormItem = Form.Item; const Option = Select.Option; const AutoCompleteOption = AutoComplete.Option; const residences = [{ value: 'zhejiang', label: 'Zhejiang', children: [{ value: 'hangzhou', label: 'Hangzhou', children: [{ value: 'xihu', label: 'West Lake', }], }], }, { value: 'jiangsu', label: 'Jiangsu', children: [{ value: 'nanjing', label: 'Nanjing', children: [{ value: 'zhonghuamen', label: 'Zhong Hua Men', }], }], }]; class RegistrationForm extends React.Component { state = { confirmDirty: false, autoCompleteResult: [], }; handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFieldsAndScroll((err, values) => { if (!err) { console.log('Received values of form: ', values); } }); } handleConfirmBlur = (e) => { const value = e.target.value; this.setState({ confirmDirty: this.state.confirmDirty || !!value }); } checkPassword = (rule, value, callback) => { const form = this.props.form; if (value && value !== form.getFieldValue('password')) { callback('Two passwords that you enter is inconsistent!'); } else { callback(); } } checkConfirm = (rule, value, callback) => { const form = this.props.form; if (value && this.state.confirmDirty) { form.validateFields(['confirm'], { force: true }); } callback(); } handleWebsiteChange = (value) => { let autoCompleteResult; if (!value) { autoCompleteResult = []; } else { autoCompleteResult = ['.com', '.org', '.net'].map(domain => `${value}${domain}`); } this.setState({ autoCompleteResult }); } render() { const { getFieldDecorator } = this.props.form; const { autoCompleteResult } = this.state; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 6 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 14 }, }, }; const tailFormItemLayout = { wrapperCol: { xs: { span: 24, offset: 0, }, sm: { span: 14, offset: 6, }, }, }; const prefixSelector = getFieldDecorator('prefix', { initialValue: '86', })( <Select style={{ width: 60 }}> <Option value="86">+86</Option> <Option value="87">+87</Option> </Select> ); const websiteOptions = autoCompleteResult.map(website => ( <AutoCompleteOption key={website}>{website}</AutoCompleteOption> )); return ( <Form onSubmit={this.handleSubmit}> <FormItem {...formItemLayout} label="E-mail" hasFeedback > {getFieldDecorator('email', { rules: [{ type: 'email', message: 'The input is not valid E-mail!', }, { required: true, message: 'Please input your E-mail!', }], })( <Input /> )} </FormItem> <FormItem {...formItemLayout} label="Password" hasFeedback > {getFieldDecorator('password', { rules: [{ required: true, message: 'Please input your password!', }, { validator: this.checkConfirm, }], })( <Input type="password" /> )} </FormItem> <FormItem {...formItemLayout} label="Confirm Password" hasFeedback > {getFieldDecorator('confirm', { rules: [{ required: true, message: 'Please confirm your password!', }, { validator: this.checkPassword, }], })( <Input type="password" onBlur={this.handleConfirmBlur} /> )} </FormItem> <FormItem {...formItemLayout} label={( <span> Nickname&nbsp; <Tooltip title="What do you want other to call you?"> <Icon type="question-circle-o" /> </Tooltip> </span> )} hasFeedback > {getFieldDecorator('nickname', { rules: [{ required: true, message: 'Please input your nickname!', whitespace: true }], })( <Input /> )} </FormItem> <FormItem {...formItemLayout} label="Habitual Residence" > {getFieldDecorator('residence', { initialValue: ['zhejiang', 'hangzhou', 'xihu'], rules: [{ type: 'array', required: true, message: 'Please select your habitual residence!' }], })( <Cascader options={residences} /> )} </FormItem> <FormItem {...formItemLayout} label="Phone Number" > {getFieldDecorator('phone', { rules: [{ required: true, message: 'Please input your phone number!' }], })( <Input addonBefore={prefixSelector} style={{ width: '100%' }} /> )} </FormItem> <FormItem {...formItemLayout} label="Website" > {getFieldDecorator('website', { rules: [{ required: true, message: 'Please input website!' }], })( <AutoComplete dataSource={websiteOptions} onChange={this.handleWebsiteChange} placeholder="website" > <Input /> </AutoComplete> )} </FormItem> <FormItem {...formItemLayout} label="Captcha" extra="We must make sure that your are a human." > <Row gutter={8}> <Col span={12}> {getFieldDecorator('captcha', { rules: [{ required: true, message: 'Please input the captcha you got!' }], })( <Input size="large" /> )} </Col> <Col span={12}> <Button size="large">Get captcha</Button> </Col> </Row> </FormItem> <FormItem {...tailFormItemLayout} style={{ marginBottom: 8 }}> {getFieldDecorator('agreement', { valuePropName: 'checked', })( <Checkbox>I have read the <a href="">agreement</a></Checkbox> )} </FormItem> <FormItem {...tailFormItemLayout}> <Button type="primary" htmlType="submit">Register</Button> </FormItem> </Form> ); } } const WrappedRegistrationForm = Form.create()(RegistrationForm); ReactDOM.render(<WrappedRegistrationForm />, document.getElementById('root'));
app/javascript/components/provider-dashboard-charts/provider-dashboard-utilization-chart/utilizationDonutChart.js
ManageIQ/manageiq-ui-classic
import React from 'react'; import PropTypes from 'prop-types'; import { DonutChart, AreaChart } from '@carbon/charts-react'; import { getConvertedData } from '../helpers'; import EmptyChart from '../emptyChart'; const UtilizationDonutChart = ({ data, config }) => { const cpuData = data.cpu ? data.cpu : data.xy_data.cpu; const donutChartData = [ { group: config.usageDataName, value: cpuData.used, }, { group: config.availableDataName, value: cpuData.total - cpuData.used, }, ]; const donutOptions = { donut: { center: { label: __('Cores Used'), number: cpuData.used, }, }, height: '230px', resizable: true, tooltip: { truncation: { type: 'none', }, }, }; const areaOptions = { grid: { x: { enabled: false, }, y: { enabled: false, }, }, axes: { bottom: { visible: false, mapsTo: 'date', scaleType: 'time', }, left: { visible: false, mapsTo: 'value', scaleType: 'linear', }, }, color: { gradient: { enabled: true, }, }, legend: { enabled: false, }, toolbar: { enabled: false, }, height: '150px', tooltip: { customHTML: config.sparklineTooltip(data), }, }; const areaChartData = getConvertedData(cpuData, config.units); return ( <div> <div className="utilization-trend-chart-pf"> <h3>{config.title}</h3> <div className="current-values"> <h1 className="available-count pull-left"> {cpuData.total - cpuData.used} </h1> <div className="available-text pull-left"> <span> {config.availableof} {''} <span className="available-text-total">{cpuData.total}</span> <span className="available-text-total">{config.units}</span> </span> </div> </div> </div> {cpuData.dataAvailable ? ( <div> <DonutChart data={donutChartData} options={donutOptions} /> <div className="sparkline-chart"> <AreaChart data={areaChartData} options={areaOptions} /> </div> </div> ) : <EmptyChart />} <span className={`trend-footer-pf ${!cpuData.dataAvailable ? 'chart-transparent-text' : ''}`}>{config.legendLeftText}</span> </div> ); // } }; UtilizationDonutChart.propTypes = { data: PropTypes.objectOf(PropTypes.any).isRequired, config: PropTypes.shape({ legendLeftText: PropTypes.string.isRequired, availableof: PropTypes.string.isRequired, title: PropTypes.string.isRequired, units: PropTypes.string.isRequired, usageDataName: PropTypes.string.isRequired, availableDataName: PropTypes.string.isRequired, sparklineTooltip: PropTypes.func.isRequired, }).isRequired, }; export default UtilizationDonutChart;
src/icons/ArrowGraphDownRight.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class ArrowGraphDownRight extends React.Component { render() { if(this.props.bare) { return <g> <polygon points="320,384 381.8,322.2 288.3,224 181.3,330.7 32,128 181.3,256 288.3,144 419.2,284.8 480,224 480,384 "></polygon> </g>; } return <IconBase> <polygon points="320,384 381.8,322.2 288.3,224 181.3,330.7 32,128 181.3,256 288.3,144 419.2,284.8 480,224 480,384 "></polygon> </IconBase>; } };ArrowGraphDownRight.defaultProps = {bare: false}
src/containers/settings/EditServiceScreen.js
meetfranz/franz
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { inject, observer } from 'mobx-react'; import { defineMessages, intlShape } from 'react-intl'; import UserStore from '../../stores/UserStore'; import RecipesStore from '../../stores/RecipesStore'; import ServicesStore from '../../stores/ServicesStore'; import SettingsStore from '../../stores/SettingsStore'; import FeaturesStore from '../../stores/FeaturesStore'; import Form from '../../lib/Form'; import ServiceError from '../../components/settings/services/ServiceError'; import EditServiceForm from '../../components/settings/services/EditServiceForm'; import ErrorBoundary from '../../components/util/ErrorBoundary'; import { required, url, oneRequired } from '../../helpers/validation-helpers'; import { getSelectOptions } from '../../helpers/i18n-helpers'; import { config as proxyFeature } from '../../features/serviceProxy'; import { config as spellcheckerFeature } from '../../features/spellchecker'; import { SPELLCHECKER_LOCALES } from '../../i18n/languages'; import globalMessages from '../../i18n/globalMessages'; const messages = defineMessages({ name: { id: 'settings.service.form.name', defaultMessage: '!!!Name', }, enableService: { id: 'settings.service.form.enableService', defaultMessage: '!!!Enable service', }, enableHibernation: { id: 'settings.service.form.enableHibernation', defaultMessage: '!!!Enable hibernation', }, enableNotification: { id: 'settings.service.form.enableNotification', defaultMessage: '!!!Enable Notifications', }, enableBadge: { id: 'settings.service.form.enableBadge', defaultMessage: '!!!Show unread message badges', }, enableAudio: { id: 'settings.service.form.enableAudio', defaultMessage: '!!!Enable audio', }, team: { id: 'settings.service.form.team', defaultMessage: '!!!Team', }, customUrl: { id: 'settings.service.form.customUrl', defaultMessage: '!!!Custom server', }, indirectMessages: { id: 'settings.service.form.indirectMessages', defaultMessage: '!!!Show message badge for all new messages', }, icon: { id: 'settings.service.form.icon', defaultMessage: '!!!Custom icon', }, enableDarkMode: { id: 'settings.service.form.enableDarkMode', defaultMessage: '!!!Enable Dark Mode', }, enableProxy: { id: 'settings.service.form.proxy.isEnabled', defaultMessage: '!!!Use Proxy', }, proxyHost: { id: 'settings.service.form.proxy.host', defaultMessage: '!!!Proxy Host/IP', }, proxyPort: { id: 'settings.service.form.proxy.port', defaultMessage: '!!!Port', }, proxyUser: { id: 'settings.service.form.proxy.user', defaultMessage: '!!!User', }, proxyPassword: { id: 'settings.service.form.proxy.password', defaultMessage: '!!!Password', }, }); export default @inject('stores', 'actions') @observer class EditServiceScreen extends Component { static contextTypes = { intl: intlShape, }; onSubmit(data) { const { action } = this.props.router.params; const { recipes, services } = this.props.stores; const { createService, updateService } = this.props.actions.service; const serviceData = data; serviceData.isMuted = !serviceData.isMuted; if (action === 'edit') { updateService({ serviceId: services.activeSettings.id, serviceData }); } else { createService({ recipeId: recipes.active.id, serviceData }); } } prepareForm(recipe, service, proxy) { const { intl, } = this.context; const { stores, router, } = this.props; const { action } = router.params; let defaultSpellcheckerLanguage = SPELLCHECKER_LOCALES[stores.settings.app.spellcheckerLanguage]; if (stores.settings.app.spellcheckerLanguage === 'automatic') { defaultSpellcheckerLanguage = intl.formatMessage(globalMessages.spellcheckerAutomaticDetectionShort); } const spellcheckerLanguage = getSelectOptions({ locales: SPELLCHECKER_LOCALES, resetToDefaultText: intl.formatMessage(globalMessages.spellcheckerSystemDefault, { default: defaultSpellcheckerLanguage }), automaticDetectionText: stores.settings.app.spellcheckerLanguage !== 'automatic' ? intl.formatMessage(globalMessages.spellcheckerAutomaticDetection) : '', }); const config = { fields: { name: { label: intl.formatMessage(messages.name), placeholder: intl.formatMessage(messages.name), value: service.id ? service.name : recipe.name, }, isEnabled: { label: intl.formatMessage(messages.enableService), value: service.isEnabled, default: true, }, isHibernationEnabled: { label: intl.formatMessage(messages.enableHibernation), value: action !== 'edit' ? recipe.autoHibernate : service.isHibernationEnabled, default: true, }, isNotificationEnabled: { label: intl.formatMessage(messages.enableNotification), value: service.isNotificationEnabled, default: true, }, isBadgeEnabled: { label: intl.formatMessage(messages.enableBadge), value: service.isBadgeEnabled, default: true, }, isMuted: { label: intl.formatMessage(messages.enableAudio), value: !service.isMuted, default: true, }, customIcon: { label: intl.formatMessage(messages.icon), value: service.hasCustomUploadedIcon ? service.icon : false, default: null, type: 'file', }, isDarkModeEnabled: { label: intl.formatMessage(messages.enableDarkMode), value: service.isDarkModeEnabled, default: stores.settings.app.darkMode, }, spellcheckerLanguage: { label: intl.formatMessage(globalMessages.spellcheckerLanguage), value: service.spellcheckerLanguage, options: spellcheckerLanguage, disabled: !stores.settings.app.enableSpellchecking, }, }, }; if (recipe.hasTeamId) { Object.assign(config.fields, { team: { label: intl.formatMessage(messages.team), placeholder: intl.formatMessage(messages.team), value: service.team, validators: [required], }, }); } if (recipe.hasCustomUrl) { Object.assign(config.fields, { customUrl: { label: intl.formatMessage(messages.customUrl), placeholder: 'https://', value: service.customUrl, validators: [required, url], }, }); } // More fine grained and use case specific validation rules if (recipe.hasTeamId && recipe.hasCustomUrl) { config.fields.team.validators = [oneRequired(['team', 'customUrl'])]; config.fields.customUrl.validators = [url, oneRequired(['team', 'customUrl'])]; } // If a service can be hosted and has a teamId or customUrl if (recipe.hasHostedOption && (recipe.hasTeamId || recipe.hasCustomUrl)) { if (config.fields.team) { config.fields.team.validators = []; } if (config.fields.customUrl) { config.fields.customUrl.validators = [url]; } } if (recipe.hasIndirectMessages) { Object.assign(config.fields, { isIndirectMessageBadgeEnabled: { label: intl.formatMessage(messages.indirectMessages), value: service.isIndirectMessageBadgeEnabled, default: true, }, }); } if (proxy.isEnabled) { const serviceProxyConfig = stores.settings.proxy[service.id] || {}; Object.assign(config.fields, { proxy: { name: 'proxy', label: 'proxy', fields: { isEnabled: { label: intl.formatMessage(messages.enableProxy), value: serviceProxyConfig.isEnabled, default: false, }, host: { label: intl.formatMessage(messages.proxyHost), value: serviceProxyConfig.host, default: '', }, port: { label: intl.formatMessage(messages.proxyPort), value: serviceProxyConfig.port, default: '', }, user: { label: intl.formatMessage(messages.proxyUser), value: serviceProxyConfig.user, default: '', }, password: { label: intl.formatMessage(messages.proxyPassword), value: serviceProxyConfig.password, default: '', type: 'password', }, }, }, }); } return new Form(config); } deleteService() { const { deleteService } = this.props.actions.service; const { action } = this.props.router.params; if (action === 'edit') { const { activeSettings: service } = this.props.stores.services; deleteService({ serviceId: service.id, redirect: '/settings/services', }); } } render() { const { recipes, services, user } = this.props.stores; const { action } = this.props.router.params; let recipe; let service = {}; let isLoading = false; if (action === 'add') { recipe = recipes.active; // TODO: render error message when recipe is `null` if (!recipe) { return ( <ServiceError /> ); } } else { service = services.activeSettings; isLoading = services.allServicesRequest.isExecuting; if (!isLoading && service) { recipe = service.recipe; } } if (isLoading) { return (<div>Loading...</div>); } if (!recipe) { return ( <div>something went wrong</div> ); } const form = this.prepareForm(recipe, service, proxyFeature); return ( <ErrorBoundary> <EditServiceForm action={action} recipe={recipe} service={service} user={user.data} form={form} status={services.actionStatus} isSaving={services.updateServiceRequest.isExecuting || services.createServiceRequest.isExecuting} isDeleting={services.deleteServiceRequest.isExecuting} onSubmit={d => this.onSubmit(d)} onDelete={() => this.deleteService()} isProxyFeatureEnabled={proxyFeature.isEnabled} isServiceProxyIncludedInCurrentPlan={proxyFeature.isIncludedInCurrentPlan} isSpellcheckerIncludedInCurrentPlan={spellcheckerFeature.isIncludedInCurrentPlan} /> </ErrorBoundary> ); } } EditServiceScreen.wrappedComponent.propTypes = { stores: PropTypes.shape({ user: PropTypes.instanceOf(UserStore).isRequired, recipes: PropTypes.instanceOf(RecipesStore).isRequired, services: PropTypes.instanceOf(ServicesStore).isRequired, settings: PropTypes.instanceOf(SettingsStore).isRequired, features: PropTypes.instanceOf(FeaturesStore).isRequired, }).isRequired, router: PropTypes.shape({ params: PropTypes.shape({ action: PropTypes.string.isRequired, }).isRequired, }).isRequired, actions: PropTypes.shape({ service: PropTypes.shape({ createService: PropTypes.func.isRequired, updateService: PropTypes.func.isRequired, deleteService: PropTypes.func.isRequired, }).isRequired, // settings: PropTypes.shape({ // update: PropTypes.func.isRequred, // }).isRequired, }).isRequired, };
js/jqwidgets/demos/react/app/passwordinput/customstrengthrendering/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxPasswordInput from '../../../jqwidgets-react/react_jqxpasswordinput.js'; class App extends React.Component { render() { // The passwordStrength enables you to override the built-in strength calculation. let passwordStrength = (password, characters, defaultStrength) => { let length = password.length; let letters = characters.letters; let numbers = characters.numbers; let specialKeys = characters.specialKeys; let strengthCoefficient = letters + numbers + 2 * specialKeys + letters * numbers * specialKeys; let strengthValue; if (length < 4) { strengthValue = 'Too short'; } else if (strengthCoefficient < 10) { strengthValue = 'Weak'; } else if (strengthCoefficient < 20) { strengthValue = 'Fair'; } else if (strengthCoefficient < 30) { strengthValue = 'Good'; } else { strengthValue = 'Strong'; }; return strengthValue; }; // The strengthTypeRenderer enables you to override the built-in rendering of the Strength tooltip. let strengthTypeRenderer = (password, characters, defaultStrength) => { let length = password.length; let letters = characters.letters; let numbers = characters.numbers; let specialKeys = characters.specialKeys; let strengthCoefficient = letters + numbers + 2 * specialKeys + letters * numbers / 2 + length; let strengthValue; let color; if (length < 8) { strengthValue = 'Too short'; color = 'rgb(170, 0, 51)'; } else if (strengthCoefficient < 20) { strengthValue = 'Weak'; color = 'rgb(170, 0, 51)'; } else if (strengthCoefficient < 30) { strengthValue = 'Fair'; color = 'rgb(255, 204, 51)'; } else if (strengthCoefficient < 40) { strengthValue = 'Good'; color = 'rgb(45, 152, 243)'; } else { strengthValue = 'Strong'; color = 'rgb(118, 194, 97)'; }; return '<div style="font-style: italic; font-weight: bold; color: "' + color + ';">' + strengthValue + '</div>'; }; return ( <JqxPasswordInput ref='passwordInput' width={200} height={25} placeHolder={'Enter password:'} showStrength={true} showStrengthPosition={'right'} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/components/common/Separator.js
gongmingqm10/Dribbble-ReactNative
import React from 'react'; import {View, StyleSheet} from 'react-native'; import {Colors} from '../../utils/Theme'; const Separator = ({style}) => ( <View style={[styles.line, style]}/> ); const styles = StyleSheet.create({ line: { height: 1, backgroundColor: Colors.lightGray } }); export default Separator;
frontend/Components/Header/Logo/index.js
shoumma/ReForum
import React, { Component } from 'react'; import styles from './styles'; const Logo = () => { return ( <div className={styles.logoContainer}> <div className={styles.logo}> <svg viewBox="0 0 100 100"xmlns="http://www.w3.org/2000/svg"> <g id="Group" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd"> <path d="M51.1388842,81.5721454 L69.5667388,100 L92.0066458,100 C96.4114635,100 100,96.4212534 100,92.0066458 L100,7.99335421 C100,3.58853654 96.4212534,0 92.0066458,0 L7.99335421,0 C3.58853654,0 0,3.57874658 0,7.99335421 L0,92.0066458 C0,96.4114635 3.57874658,100 7.99335421,100 L10.5882353,100 L10.5882353,44.7058824 C10.7474244,24.5366987 27.1464843,8.23529412 47.3529412,8.23529412 C67.6575276,8.23529412 84.1176471,24.6954136 84.1176471,45 C84.1176471,64.0263195 69.6647717,79.676989 51.1388842,81.5721454 Z M24.2232146,73.5788183 L24.1176471,73.6843859 L50.4332612,100 L24.1176471,100 L24.1176471,73.4929507 C24.1527823,73.521637 24.1879715,73.5502596 24.2232146,73.5788183 Z" id="Combined-Shape" fill="#F1C40F"></path> <circle id="Oval" fill="#F1C40F" cx="47.6470588" cy="45.2941176" r="23.5294118"></circle> </g> </svg> </div> <div className={styles.logoTitle}>ReForum</div> </div> ); }; export default Logo;
ReduxReactToDo/app/containers/App/index.js
michaelgichia/TODO-List
/** * * App.react.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import ReactDOM from 'react-dom'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function static propTypes = { children: React.PropTypes.node, }; render() { return ( <MuiThemeProvider> <div> {React.Children.toArray(this.props.children)} </div> </MuiThemeProvider> ); } }
src/record/RecordEditor.js
RoyalIcing/gateau
import R from 'ramda' import React from 'react' import { Seed } from 'react-seeds' import Choice from '../ui/Choice' import Field from '../ui/Field' import { recordField } from '../stylers' const types = [ { value: 'string', title: 'Text' }, { value: 'boolean', title: 'Yes / No' }, { value: 'number', title: 'Number' }, { value: 'array', title: 'List' }, { value: 'object', title: 'Record' } ] const valueEditorForType = R.cond([ [ R.equals('string'), R.always((string) => <Field value={ string } { ...recordField } />) ], [ R.equals('boolean'), R.always((boolean) => <Choice value={ boolean } items={[ { value: true, title: 'Yes' }, { value: false, title:' No' } ]} />) ], [ R.equals('number'), R.always((number) => <input type='number' value={ number } />) ], [ R.equals('array'), () => (items) => <div>{ items.map((item, index) => <Item key={ index } id={ index } value={ item } /> ) }</div> ], [ R.equals('object'), () => (object) => <RecordEditor object={ object } /> ] ]) const valueEditorForValue = R.converge( R.call, [ R.pipe( R.type, R.toLower, valueEditorForType ), R.identity ] ) function Item({ id, value }) { return ( <Seed column> <Seed row grow={ 1 }> <input value={ id } style={{ fontWeight: 'bold' }} /> <Choice value={ R.type(value).toLowerCase() } items={ types } /> </Seed> { valueEditorForValue(value) } </Seed> ) } export default function RecordEditor({ object, ...seedProps }) { return ( <Seed column { ...seedProps }> { Object.keys(object).map((key) => ( <Item key={ key } id={ key } value={ object[key] } /> )) } </Seed> ) }
examples/huge-apps/routes/Messages/components/Messages.js
RickyDan/react-router
import React from 'react'; class Messages extends React.Component { render () { return ( <div> <h2>Messages</h2> </div> ); } } export default Messages;
src/svg-icons/device/battery-alert.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryAlert = (props) => ( <SvgIcon {...props}> <path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM13 18h-2v-2h2v2zm0-4h-2V9h2v5z"/> </SvgIcon> ); DeviceBatteryAlert = pure(DeviceBatteryAlert); DeviceBatteryAlert.displayName = 'DeviceBatteryAlert'; DeviceBatteryAlert.muiName = 'SvgIcon'; export default DeviceBatteryAlert;
js/components/index.js
orionwei/mygit
/** * Created by orionwei on 2016/11/19. */ import React from 'react'; import Relay from 'react-relay'; import {IndexLink,Link} from 'react-router'; import resumeData from './../../public/resume'; import Resume from './resume'; import Header from './header'; class Index extends React.Component { render() { return ( <div className="center"> <Header/> <div className="marc"> <div className="mypic"></div> <Resume className="resume" name={resumeData.name} sex={resumeData.sex} birthday={resumeData.birthday||""} email={resumeData.email} number={resumeData.number} intern={resumeData.interns} project={resumeData.projects} education={resumeData.educations} honor={resumeData.honors} skill={resumeData.skills} /> </div> </div> ); } } export default Relay.createContainer(Index, { fragments: { film: () => Relay.QL` fragment on FilmsConnection { pageInfo{ startCursor } } `, }, });
node_modules/lite-server/node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
jibadano/71mb4
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
src/List/List.js
kmees/react-fabric
import React from 'react' import elementType from 'react-prop-types/lib/elementType' // import ListItem from '../ListItem' import fabricComponent from '../fabricComponent' import style from './List.scss' const List = ({ children, componentClass: Component, selectable, ...props }) => ( <Component data-fabric="List" {...props} styleName="ms-List"> { selectable ? React.Children.map(children, child => ( React.cloneElement(child, { selectable }) )) : children } </Component> ) List.displayName = 'List' List.propTypes = { children: React.PropTypes.node, // TODO Array of ListItems // children: React.PropTypes.oneOfType([ // React.PropTypes.instanceOf(ListItem), // React.PropTypes.arrayOf(React.PropTypes.instanceOf(ListItem)) // ]), componentClass: elementType, selectable: React.PropTypes.bool } List.defaultProps = { componentClass: 'ul', selectable: false } export default fabricComponent(List, style)
src/scenes/Layout/components/Representation/components/Week/components/DayOfWeek/DayOfWeek.js
czonios/schedule-maker-app
import React from 'react'; import { Header } from 'semantic-ui-react'; import './dayOfWeek.css'; import EditEvent from '../../../../services/EditEvent'; class DayOfWeek extends React.Component { constructor() { super(); this.state = { showModal: false }; this.setModal = this.setModal.bind(this); } setModal(event) { if (this.state.showModal) { this.setState({ showModal: false }); } else { this.setState({ showModal: true }); } } render() { return ( <div className="clickable" onClick={this.setModal.bind(this)}> <Header size="tiny">title for {this.props.time} {this.props.day}</Header> <p>description</p> { this.state.showModal ? <EditEvent setModal={this.setModal} event={this.props} /> : null } </div> ) } } export default DayOfWeek;
app/components/Home.js
sirgalleto/gearmanUI
// @flow import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './Home.css'; export default class Home extends Component { render() { return ( <div> <div className={styles.container} data-tid="container"> <h2>Home</h2> <Link to="/counter">to Counter</Link> </div> </div> ); } }
src/components/Modal/About.js
clhenrick/nyc-crash-mapper
import React from 'react'; import AboutCopy from '../AboutCopy'; export default () => ( <div className="modal-about"> <AboutCopy /> </div> );
boxroom/archive/backup-js-glow-2018-01-28/boxroom/archive/js-surface-2018-01-27/boxroom/archive/2018-01-11/src/main/js-surface-react.js
mcjazzyfunky/js-surface
import adaptReactLikeComponentSystem from './adaption/adaptReactLikeComponentSystem'; import React from 'react'; import ReactDOM from 'react-dom'; function reactMount(content, targetNode) { ReactDOM.render(content, targetNode); return () => ReactDOM.unmountComponentAtNode(targetNode); } const { createElement, defineComponent, isElement, mount, unmount, Adapter, Config } = adaptReactLikeComponentSystem({ name: 'react', api: { React, ReactDOM }, createElement: React.createElement, createFactory: React.createFactory, isValidElement: React.isValidElement, mount: reactMount, Component: React.Component, browserBased: true }); export { createElement, defineComponent, isElement, mount, unmount, Adapter, Config };
src/browser/auth/Email.js
TheoMer/Gyms-Of-The-World
// @flow import type { State } from '../../common/types'; import React from 'react'; import buttonsMessages from '../../common/app/buttonsMessages'; import emailMessages from '../../common/auth/emailMessages'; import { FormattedMessage, injectIntl } from 'react-intl'; import { compose } from 'ramda'; import { connect } from 'react-redux'; import { fields } from '../../common/lib/redux-fields'; import { resetPassword, signIn, signUp } from '../../common/auth/actions'; import { Form, focus } from '../components'; import { Box, Heading, Message, OutlineButton, TextInput, } from '../../common/components'; type EmailState = { forgetPasswordIsShown: boolean, recoveryEmailSent: boolean, }; type EmailProps = { disabled: boolean, fields: any, intl: $IntlShape, resetPassword: typeof resetPassword, signIn: typeof signIn, signUp: typeof signUp, }; // blog.mariusschulz.com/2016/03/20/how-to-remove-webkits-banana-yellow-autofill-background const overrideWebkitYellowAutofill = () => ({ WebkitBoxShadow: 'inset 0 0 0px 9999px white', }); const Button = ({ message, ...props }) => ( <FormattedMessage {...message}> {msg => ( <OutlineButton marginHorizontal={0.25} {...props}> {msg} </OutlineButton> )} </FormattedMessage> ); const Buttons = props => ( <Box flexDirection="row" flexWrap="wrap" marginVertical={1} marginHorizontal={-0.25} {...props} /> ); class Email extends React.Component { state: EmailState = { forgetPasswordIsShown: false, recoveryEmailSent: false, }; onFormSubmit = () => { if (this.state.forgetPasswordIsShown) { this.resetPassword(); } else { this.signInViaPassword(); } }; onSignInClick = () => { this.signInViaPassword(); }; onSignUpClick = () => { const { fields, signUp } = this.props; signUp('password', fields.$values()); }; onForgetPasswordClick = () => { const { forgetPasswordIsShown } = this.state; this.setState({ forgetPasswordIsShown: !forgetPasswordIsShown }); }; onResetPasswordClick = () => { this.resetPassword(); }; props: EmailProps; resetPassword() { const { fields, resetPassword } = this.props; const { email } = fields.$values(); resetPassword(email); this.setState({ forgetPasswordIsShown: false, recoveryEmailSent: true, }); } signInViaPassword() { const { fields, signIn } = this.props; signIn('password', fields.$values()); } render() { const { forgetPasswordIsShown, recoveryEmailSent } = this.state; const legendMessage = forgetPasswordIsShown ? emailMessages.passwordRecoveryLegend : emailMessages.emailLegend; const { disabled, fields, intl } = this.props; return ( <Form onSubmit={this.onFormSubmit}> <Box marginTop={1}> <Heading size={1}> {intl.formatMessage(legendMessage)} </Heading> <TextInput {...fields.email} disabled={disabled} marginBottom={1} maxLength={100} placeholder={intl.formatMessage(emailMessages.emailPlaceholder)} size={1} style={overrideWebkitYellowAutofill} /> <TextInput {...fields.password} disabled={forgetPasswordIsShown || disabled} maxLength={1000} placeholder={intl.formatMessage(emailMessages.passwordPlaceholder)} size={1} style={overrideWebkitYellowAutofill} type="password" /> </Box> {!forgetPasswordIsShown ? <Box> <Buttons> <Button disabled={disabled} message={buttonsMessages.signIn} onClick={this.onSignInClick} /> <Button disabled={disabled} message={buttonsMessages.signUp} onClick={this.onSignUpClick} /> <Button disabled={disabled} message={emailMessages.passwordForgotten} onClick={this.onForgetPasswordClick} /> </Buttons> {recoveryEmailSent && <FormattedMessage {...emailMessages.recoveryEmailSent}> {message => ( <Message backgroundColor="success" marginTop={1}> {message} </Message> )} </FormattedMessage>} </Box> : <Buttons> <Button disabled={disabled} message={emailMessages.resetPassword} onClick={this.onResetPasswordClick} /> <Button disabled={disabled} message={buttonsMessages.dismiss} onClick={this.onForgetPasswordClick} /> </Buttons>} </Form> ); } } export default compose( connect( (state: State) => ({ disabled: state.auth.formDisabled, error: state.auth.error, }), { resetPassword, signIn, signUp }, ), injectIntl, fields({ path: ['auth', 'email'], fields: ['email', 'password'], }), focus('error'), )(Email);
src/layouts/CoreLayout.js
daviferreira/react-redux-starter-kit
import React from 'react'; import 'styles/core.scss'; export default class CoreLayout extends React.Component { static propTypes = { children : React.PropTypes.element } constructor () { super(); } render () { return ( <div className='page-container'> <div className='view-container'> {this.props.children} </div> </div> ); } }
src/parser/shared/modules/spells/bfa/azeritetraits/EphemeralRecovery.js
sMteX/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS/index'; import TraitStatisticBox, { STATISTIC_ORDER } from 'interface/others/TraitStatisticBox'; import ItemManaGained from 'interface/others/ItemManaGained'; /** Casting a healing spell restores 12 mana over 8 sec. Stacks up to 2 times. Example Log: /report/qyzBLkQaXDJ7xdZN/5-Mythic+Taloc+-+Kill+(4:12)/23-포오서 */ class EphemeralRecovery extends Analyzer { manaGained = 0; procs = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.EPHEMERAL_RECOVERY.id); } on_toPlayer_energize(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.EPHEMERAL_RECOVERY_EFFECT.id) { return; } this.procs += 1; this.manaGained += event.resourceChange; } statistic() { return ( <TraitStatisticBox position={STATISTIC_ORDER.OPTIONAL()} trait={SPELLS.EPHEMERAL_RECOVERY.id} value={<ItemManaGained amount={this.manaGained} />} tooltip={`Total procs: ${this.procs}`} /> ); } } export default EphemeralRecovery;
web/client/configdev/src/config/HomeMenu.js
project-owner/Peppy
/* Copyright 2019-2022 Peppy Player peppy.player@gmail.com This file is part of Peppy Player. Peppy Player is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Peppy Player is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Peppy Player. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react'; import {FormControl} from '@material-ui/core'; import Factory from "../Factory"; export default class HomeMenu extends React.Component { render() { const { params, updateState, labels } = this.props; const items = ["radio", "audio-files", "audiobooks", "podcasts", "stream", "cd-player", "airplay", "spotify-connect", "collection", "bluetooth-sink"]; return ( <FormControl> {items.map((v) => {return Factory.createCheckbox(v, params, updateState, labels)})} </FormControl> ); } }
src/Screens/Settings.js
saurabhj/helpline-app
'use strict'; import React, { Component } from 'react'; import { StyleSheet, Text, View, Image, TextInput, Button, TouchableHighlight, TouchableOpacity, AsyncStorage, Alert, Platform, ScrollView, Share, } from 'react-native'; import { StackNavigator } from 'react-navigation'; import Communications from 'react-native-communications'; import DataStore from '../Data/DataStore'; import EmergencyContacts from '../Utils/EmergencyContactManager'; import EmergencyContactSetting from '../Components/EmergencyContactSetting'; const _feedbackEmail = 'feedback@mhtech.in'; const _appWebsite = 'https://mhtech.in'; class Settings extends Component { constructor(props, context) { super(props, context); this.state = { emergencyContacts: EmergencyContacts.getEmptyContacts(), currentDataVersion: '1.00', }; EmergencyContacts.fetchContacts(result => { this.setState({ emergencyContacts: result }); }); DataStore.getOfflineDataVersion(version => { this.setState({ currentDataVersion: version.toString() }); }); } static navigationOptions = { title: 'Settings', headerStyle: { backgroundColor: '#27ae60', }, headerTintColor: '#fff', }; onContactTouch(contactPriority) { this.props.navigation.navigate('ContactList', { navigation: this.props.navigation, contactPriority: contactPriority, }); } onDelete(contactPriority) { EmergencyContacts.deleteContact(contactPriority, contacts => { if (contacts !== null) { this.setState({ emergencyContacts: contacts, }); } else { Alert.alert( 'An error occurred while trying to remove the emergency contact. Please try again.' ); } }); } factoryResetData() { Alert.alert( 'Factory Reset Data?', 'Performing a factory reset will clear out all your favourite helplines and emergency contacts and restore the helpline data to the version shipped with the app.', [ { text: 'Reset', onPress: () => { AsyncStorage.clear(error => { this.setState({ emergencyContacts: EmergencyContacts.getEmptyContacts(), currentDataVersion: '1.00', }); Alert.alert( 'Data reset successfully', 'All data has been reset to factory settings.', [ { text: 'OK', onPress: () => { const { navigation } = this.props; navigation.goBack(); navigation.state.params.onFactoryReset(); }, }, ] ); }); }, }, { text: 'Cancel', onPress: () => {}, style: 'cancel' }, ], { cancelable: true } ); } shareAppDownload() { var message = [ 'Hey,', 'I wanted to share this app with you which contains a directory of Emotional Support Helplines from all over India.', '', 'Download it from: https://mhtech.in', ].join('\n'); Share.share({ message: message, title: 'Share details with a friend', }); } giveAppFeedback() { Communications.email( [_feedbackEmail], null, null, 'Feedback: Emotional Support Helpline Directory', ['Platform: ' + Platform.OS, '-----', ''].join('\n') ); } render() { return ( <View style={styles.container}> <ScrollView> <View style={styles.screenDetails}> <Text> Select up to 4 contacts that you would like to add as your emergency contact group. </Text> </View> <View style={styles.emergencyContacts}> <EmergencyContactSetting onDelete={this.onDelete.bind(this, 0)} onPress={this.onContactTouch.bind(this, 0)} name={this.state.emergencyContacts[0].name} phoneNumber={this.state.emergencyContacts[0].number} imageUrl={this.state.emergencyContacts[0].photo} backgroundColor="#fff" /> <EmergencyContactSetting onDelete={this.onDelete.bind(this, 1)} onPress={this.onContactTouch.bind(this, 1)} name={this.state.emergencyContacts[1].name} phoneNumber={this.state.emergencyContacts[1].number} imageUrl={this.state.emergencyContacts[1].photo} backgroundColor="#fff" /> <EmergencyContactSetting onDelete={this.onDelete.bind(this, 2)} onPress={this.onContactTouch.bind(this, 2)} name={this.state.emergencyContacts[2].name} phoneNumber={this.state.emergencyContacts[2].number} imageUrl={this.state.emergencyContacts[2].photo} backgroundColor="#fff" /> <EmergencyContactSetting onDelete={this.onDelete.bind(this, 3)} onPress={this.onContactTouch.bind(this, 3)} name={this.state.emergencyContacts[3].name} phoneNumber={this.state.emergencyContacts[3].number} imageUrl={this.state.emergencyContacts[3].photo} backgroundColor="#fff" /> </View> <View style={styles.feedbackButtonsContainer}> <TouchableOpacity onPress={this.shareAppDownload.bind(this)} style={styles.feedbackButton} > <Image style={styles.feedbackButtonIcon} source={require('../images/share-white.png')} /> <Text style={styles.feedbackButtonText}> Share App Download Link </Text> </TouchableOpacity> <TouchableOpacity onPress={this.giveAppFeedback.bind(this)} style={styles.feedbackButton} > <Image style={styles.feedbackButtonIcon} source={require('../images/feedback-white.png')} /> <Text style={styles.feedbackButtonText}> Give us Feedback </Text> </TouchableOpacity> <TouchableOpacity style={styles.feedbackButton} onPress={() => this.props.navigation.navigate('About')} > <Image style={styles.feedbackButtonIcon} source={require('../images/group-white.png')} /> <Text style={styles.feedbackButtonText}> About Us </Text> </TouchableOpacity> <TouchableOpacity style={styles.feedbackButton} onPress={() => this.props.navigation.navigate('Disclaimer')} > <Image style={styles.feedbackButtonIcon} source={require('../images/exclamation-triangle-white.png')} /> <Text style={styles.feedbackButtonText}> Disclaimer </Text> </TouchableOpacity> </View> <View style={styles.currentDataVersion}> <Text> Current data version:{' '} {this.state.currentDataVersion} </Text> <TouchableOpacity style={styles.factoryResetLink} onPress={this.factoryResetData.bind(this)} > <Text style={styles.clickableText}> Factory Reset Data </Text> </TouchableOpacity> </View> </ScrollView> </View> ); } } const styles = StyleSheet.create({ container: { paddingTop: 20, }, headerStyle: { backgroundColor: '#27ae60', color: '#fff', }, screenDetails: { paddingLeft: 20, paddingRight: 20, }, emergencyContacts: { marginTop: 20, }, currentDataVersion: { marginTop: 10, padding: 20, }, clickableText: { color: '#0080ff', textDecorationLine: 'underline', }, factoryResetLink: { marginTop: 5, }, feedbackButtonsContainer: { marginTop: 20, flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'center', }, feedbackButton: { flexDirection: 'row', backgroundColor: '#0080ff', justifyContent: 'center', alignItems: 'center', width: 300, marginBottom: 10, marginTop: 10, borderRadius: 3, height: 40, alignSelf: 'center', }, feedbackButtonText: { fontSize: 18, color: '#fff', }, feedbackButtonIcon: { width: 18, height: 18, marginRight: 10, }, }); export default Settings;
src/entypo/LocationPin.js
cox-auto-kc/react-entypo
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--LocationPin'; let EntypoLocationPin = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M10,2.009c-2.762,0-5,2.229-5,4.99c0,4.774,5,11,5,11s5-6.227,5-11C15,4.239,12.762,2.009,10,2.009z M10,9.76c-1.492,0-2.7-1.209-2.7-2.7s1.208-2.7,2.7-2.7c1.49,0,2.699,1.209,2.699,2.7S11.49,9.76,10,9.76z"/> </EntypoIcon> ); export default EntypoLocationPin;