path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
cm19/ReactJS/your-first-react-app-exercises-master/exercise-17/shared/Page.js
Brandon-J-Campbell/codemash
import React from 'react'; import classNames from 'classnames'; import ThemeContext from '../theme/context'; import styles from './Page.css'; export default function Page({ children }) { return ( <ThemeContext.Consumer> {({ theme }) => ( <div className={classNames(styles.page, styles[theme])}> <div className={styles.content}>{children}</div> </div> )} </ThemeContext.Consumer> ); }
Circle.js
oblador/react-native-progress
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Animated, StyleSheet, Text, View } from 'react-native'; import { Svg } from 'react-native-svg'; import Arc from './Shapes/Arc'; import withAnimation from './withAnimation'; const CIRCLE = Math.PI * 2; const AnimatedSvg = Animated.createAnimatedComponent(Svg); const AnimatedArc = Animated.createAnimatedComponent(Arc); const styles = StyleSheet.create({ container: { backgroundColor: 'transparent', overflow: 'hidden', }, }); export class ProgressCircle extends Component { static propTypes = { animated: PropTypes.bool, borderColor: PropTypes.string, borderWidth: PropTypes.number, color: PropTypes.string, children: PropTypes.node, direction: PropTypes.oneOf(['clockwise', 'counter-clockwise']), fill: PropTypes.string, formatText: PropTypes.func, indeterminate: PropTypes.bool, progress: PropTypes.oneOfType([ PropTypes.number, PropTypes.instanceOf(Animated.Value), ]), rotation: PropTypes.instanceOf(Animated.Value), showsText: PropTypes.bool, size: PropTypes.number, style: PropTypes.any, strokeCap: PropTypes.oneOf(['butt', 'square', 'round']), textStyle: PropTypes.any, thickness: PropTypes.number, unfilledColor: PropTypes.string, endAngle: PropTypes.number, allowFontScaling: PropTypes.bool, }; static defaultProps = { borderWidth: 1, color: 'rgba(0, 122, 255, 1)', direction: 'clockwise', formatText: progress => `${Math.round(progress * 100)}%`, progress: 0, showsText: false, size: 40, thickness: 3, endAngle: 0.9, allowFontScaling: true, }; constructor(props, context) { super(props, context); this.progressValue = 0; } componentDidMount() { if (this.props.animated) { this.props.progress.addListener(event => { this.progressValue = event.value; if (this.props.showsText || this.progressValue === 1) { this.forceUpdate(); } }); } } render() { const { animated, borderColor, borderWidth, color, children, direction, fill, formatText, indeterminate, progress, rotation, showsText, size, style, strokeCap, textStyle, thickness, unfilledColor, endAngle, allowFontScaling, ...restProps } = this.props; const border = borderWidth || (indeterminate ? 1 : 0); const radius = size / 2 - border; const offset = { top: border, left: border, }; const textOffset = border + thickness; const textSize = size - textOffset * 2; const Surface = rotation ? AnimatedSvg : Svg; const Shape = animated ? AnimatedArc : Arc; const progressValue = animated ? this.progressValue : progress; const angle = animated ? Animated.multiply(progress, CIRCLE) : progress * CIRCLE; return ( <View style={[styles.container, style]} {...restProps}> <Surface width={size} height={size} style={ indeterminate && rotation ? { transform: [ { rotate: rotation.interpolate({ inputRange: [0, 1], outputRange: ['0deg', '360deg'], }), }, ], } : undefined } > {unfilledColor && progressValue !== 1 ? ( <Shape fill={fill} radius={radius} offset={offset} startAngle={angle} endAngle={CIRCLE} direction={direction} stroke={unfilledColor} strokeWidth={thickness} /> ) : ( false )} {!indeterminate ? ( <Shape fill={fill} radius={radius} offset={offset} startAngle={0} endAngle={angle} direction={direction} stroke={color} strokeCap={strokeCap} strokeWidth={thickness} /> ) : ( false )} {border ? ( <Arc radius={size / 2} startAngle={0} endAngle={(indeterminate ? endAngle * 2 : 2) * Math.PI} stroke={borderColor || color} strokeCap={strokeCap} strokeWidth={border} /> ) : ( false )} </Surface> {!indeterminate && showsText ? ( <View style={{ position: 'absolute', left: textOffset, top: textOffset, width: textSize, height: textSize, borderRadius: textSize / 2, alignItems: 'center', justifyContent: 'center', }} > <Text style={[ { color, fontSize: textSize / 4.5, fontWeight: '300', }, textStyle, ]} allowFontScaling={allowFontScaling} > {formatText(progressValue)} </Text> </View> ) : ( false )} {children} </View> ); } } export default withAnimation(ProgressCircle);
src/components/Certificate.js
gndx/gresume-react
import React from 'react'; const Certificate = (props) => { const myCertificates = ( <div> {props.certificate.map((cert) => <div className='item' key={cert.name}> <h3>{cert.name} @ {cert.institution} <span>{cert.date}</span></h3> <p>{cert.description}</p> </div> )} </div> ); return ( <div className='title'> <i className='fa fa-trophy'></i> <h2>CERTIFICATES</h2> {myCertificates} </div> ) }; export default Certificate;
src/shared/components/schoolCard/schoolCard.js
tal87/operationcode_frontend
import React from 'react'; import PropTypes from 'prop-types'; import OutboundLink from 'shared/components/outboundLink/outboundLink'; import styles from './schoolCard.css'; const SchoolCard = ({ alt, GI, fullTime, hardware, link, logo, schoolAddress, schoolCity, schoolName, schoolState, }) => ( <OutboundLink href={link} analyticsEventLabel={`User clicked on <SchoolCard> ${schoolName} - ${schoolCity} location`} className={styles.schoolCardLink} > <div className={styles.schoolCard}> <div className={styles.schoolCardImage}> <img src={logo} alt={alt} className={styles.logo} /> </div> <div className={styles.schoolText}> <p> <span className={styles.schoolName}>{schoolName}</span> <br /> <span className={styles.schoolLocation}> {schoolAddress.includes('Online') ? ( <text> Online Available<br /> </text> ) : null} {schoolCity} {schoolCity ? ', ' : null} {schoolState} {schoolState ? <br /> : null} <br /> </span> </p> <p className={styles.schoolInfo}> GI Bill Accepted: <b>{GI}</b> <br /> Commitment: <b>{fullTime}</b> <br /> Hardware Included: <b>{hardware}</b> </p> </div> </div> </OutboundLink> ); SchoolCard.propTypes = { alt: PropTypes.string.isRequired, link: PropTypes.string.isRequired, schoolName: PropTypes.string.isRequired, schoolAddress: PropTypes.string.isRequired, schoolCity: PropTypes.string, schoolState: PropTypes.string, logo: PropTypes.string.isRequired, GI: PropTypes.string.isRequired, fullTime: PropTypes.string.isRequired, hardware: PropTypes.string.isRequired, }; SchoolCard.defaultProps = { schoolCity: null, schoolState: null, }; export default SchoolCard;
app/javascript/mastodon/features/explore/components/story.js
Ryanaka/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Blurhash from 'mastodon/components/blurhash'; import { accountsCountRenderer } from 'mastodon/components/hashtag'; import ShortNumber from 'mastodon/components/short_number'; import Skeleton from 'mastodon/components/skeleton'; import classNames from 'classnames'; export default class Story extends React.PureComponent { static propTypes = { url: PropTypes.string, title: PropTypes.string, publisher: PropTypes.string, sharedTimes: PropTypes.number, thumbnail: PropTypes.string, blurhash: PropTypes.string, }; state = { thumbnailLoaded: false, }; handleImageLoad = () => this.setState({ thumbnailLoaded: true }); render () { const { url, title, publisher, sharedTimes, thumbnail, blurhash } = this.props; const { thumbnailLoaded } = this.state; return ( <a className='story' href={url} target='blank' rel='noopener'> <div className='story__details'> <div className='story__details__publisher'>{publisher ? publisher : <Skeleton width={50} />}</div> <div className='story__details__title'>{title ? title : <Skeleton />}</div> <div className='story__details__shared'>{typeof sharedTimes === 'number' ? <ShortNumber value={sharedTimes} renderer={accountsCountRenderer} /> : <Skeleton width={100} />}</div> </div> <div className='story__thumbnail'> {thumbnail ? ( <React.Fragment> <div className={classNames('story__thumbnail__preview', { 'story__thumbnail__preview--hidden': thumbnailLoaded })}><Blurhash hash={blurhash} /></div> <img src={thumbnail} onLoad={this.handleImageLoad} alt='' role='presentation' /> </React.Fragment> ) : <Skeleton />} </div> </a> ); } }
src/Parser/Paladin/Holy/Modules/Talents/CrusadersMight.js
hasseboulen/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import SpellUsable from 'Parser/Core/Modules/SpellUsable'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; const COOLDOWN_REDUCTION_MS = 1500; class CrusadersMight extends Analyzer { static dependencies = { combatants: Combatants, spellUsable: SpellUsable, }; effectiveHolyShockReductionMs = 0; wastedHolyShockReductionMs = 0; effectiveLightOfDawnReductionMs = 0; wastedLightOfDawnReductionMs = 0; on_initialized() { this.active = this.combatants.selected.hasTalent(SPELLS.CRUSADERS_MIGHT_TALENT.id); } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.CRUSADER_STRIKE.id) { return; } const holyShockisOnCooldown = this.spellUsable.isOnCooldown(SPELLS.HOLY_SHOCK_CAST.id); if (holyShockisOnCooldown) { const reductionMs = this.spellUsable.reduceCooldown(SPELLS.HOLY_SHOCK_CAST.id, COOLDOWN_REDUCTION_MS); this.effectiveHolyShockReductionMs += reductionMs; this.wastedHolyShockReductionMs += COOLDOWN_REDUCTION_MS - reductionMs; } else { this.wastedHolyShockReductionMs += COOLDOWN_REDUCTION_MS; } const lightOfDawnisOnCooldown = this.spellUsable.isOnCooldown(SPELLS.LIGHT_OF_DAWN_CAST.id); if (lightOfDawnisOnCooldown) { const reductionMs = this.spellUsable.reduceCooldown(SPELLS.LIGHT_OF_DAWN_CAST.id, COOLDOWN_REDUCTION_MS); this.effectiveLightOfDawnReductionMs += reductionMs; this.wastedLightOfDawnReductionMs += COOLDOWN_REDUCTION_MS - reductionMs; } else { this.wastedLightOfDawnReductionMs += COOLDOWN_REDUCTION_MS; } } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.CRUSADERS_MIGHT_TALENT.id} />} value={( <span style={{ fontSize: '75%' }}> {(this.effectiveHolyShockReductionMs / 1000).toFixed(1)}s{' '} <SpellIcon id={SPELLS.HOLY_SHOCK_CAST.id} style={{ height: '1.3em', marginTop: '-.1em', }} /> {' '} {(this.effectiveLightOfDawnReductionMs / 1000).toFixed(1)}s{' '} <SpellIcon id={SPELLS.LIGHT_OF_DAWN_CAST.id} style={{ height: '1.3em', marginTop: '-.1em', }} /> </span> )} label="Cooldown reduction" /> ); } statisticOrder = STATISTIC_ORDER.OPTIONAL(75); } export default CrusadersMight;
pnpm-offline/.pnpm-store-offline/1/registry.npmjs.org/react-bootstrap/0.31.0/es/NavItem.js
JamieMason/npm-cache-benchmark
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import SafeAnchor from './SafeAnchor'; import createChainedFunction from './utils/createChainedFunction'; var propTypes = { active: PropTypes.bool, disabled: PropTypes.bool, role: PropTypes.string, href: PropTypes.string, onClick: PropTypes.func, onSelect: PropTypes.func, eventKey: PropTypes.any }; var defaultProps = { active: false, disabled: false }; var NavItem = function (_React$Component) { _inherits(NavItem, _React$Component); function NavItem(props, context) { _classCallCheck(this, NavItem); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } NavItem.prototype.handleClick = function handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, e); } } }; NavItem.prototype.render = function render() { var _props = this.props, active = _props.active, disabled = _props.disabled, onClick = _props.onClick, className = _props.className, style = _props.style, props = _objectWithoutProperties(_props, ['active', 'disabled', 'onClick', 'className', 'style']); delete props.onSelect; delete props.eventKey; // These are injected down by `<Nav>` for building `<SubNav>`s. delete props.activeKey; delete props.activeHref; if (!props.role) { if (props.href === '#') { props.role = 'button'; } } else if (props.role === 'tab') { props['aria-selected'] = active; } return React.createElement( 'li', { role: 'presentation', className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(SafeAnchor, _extends({}, props, { disabled: disabled, onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return NavItem; }(React.Component); NavItem.propTypes = propTypes; NavItem.defaultProps = defaultProps; export default NavItem;
src/Table.js
cgvarela/react-bootstrap
import React from 'react'; import classNames from 'classnames'; const Table = React.createClass({ propTypes: { striped: React.PropTypes.bool, bordered: React.PropTypes.bool, condensed: React.PropTypes.bool, hover: React.PropTypes.bool, responsive: React.PropTypes.bool }, getDefaultProps() { return { bordered: false, condensed: false, hover: false, responsive: false, striped: false }; }, render() { let classes = { 'table': true, 'table-striped': this.props.striped, 'table-bordered': this.props.bordered, 'table-condensed': this.props.condensed, 'table-hover': this.props.hover }; let table = ( <table {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </table> ); return this.props.responsive ? ( <div className="table-responsive"> {table} </div> ) : table; } }); export default Table;
src/client.js
krolow/react-redux-universal-hot-example
/* global __DEVTOOLS__ */ import 'babel/polyfill'; import React from 'react'; import BrowserHistory from 'react-router/lib/BrowserHistory'; import Location from 'react-router/lib/Location'; import createStore from './redux/create'; import ApiClient from './ApiClient'; import universalRouter from './universalRouter'; const history = new BrowserHistory(); const client = new ApiClient(); const dest = document.getElementById('content'); const store = createStore(client, window.__data); const location = new Location(document.location.pathname, document.location.search); universalRouter(location, history, store) .then(({component}) => { if (__DEVTOOLS__) { const { DevTools, DebugPanel, LogMonitor } = require('redux-devtools/lib/react'); console.info('You will see a "Warning: React attempted to reuse markup in a container but the checksum was' + ' invalid." message. That\'s because the redux-devtools are enabled.'); React.render(<div> {component} <DebugPanel top right bottom key="debugPanel"> <DevTools store={store} monitor={LogMonitor}/> </DebugPanel> </div>, dest); } else { React.render(component, dest); } }, (error) => { console.error(error); }); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger const reactRoot = window.document.getElementById('content'); if (!reactRoot || !reactRoot.firstChild || !reactRoot.firstChild.attributes || !reactRoot.firstChild.attributes['data-react-checksum']) { console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); } }
app/js/components/SearchBar.js
azazi-sa/dakiya
import React from 'react'; import PropTypes from 'prop-types'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; // actions import { fetchPackages } from '../actions/packages'; function dispatchActionToProps(dispatch) { return { fetchPackages: bindActionCreators(fetchPackages, dispatch), }; } function mapStateToProps() { return {}; } export class SearchBar extends React.Component { constructor() { super(); this.state = { searchName: '', error: false, errorMsg: '', timeoutToken: null, }; this.updateSearchInput = this.updateSearchInput.bind(this); this.search = this.search.bind(this); this.getError = this.getError.bind(this); this.setError = this.setError.bind(this); } getError() { return (this.state.error) ? <div className="error-text">{this.state.errorMsg}</div> : null; } updateSearchInput(e) { this.setState({ searchName: e.target.value, }); clearTimeout(this.state.timeoutToken); const token = setTimeout(this.search, 500); this.setState({ timeoutToken: token, }); } setError(err, msg = '') { this.setState({ error: err, errorMsg: msg, }); } search() { const term = this.state.searchName; const shouldFetch = term.length === 0 || term.length >= 3; this.setError(shouldFetch); if (shouldFetch) { this.props.fetchPackages(this.state.searchName); } else { this.setError(true, 'Please enter more than 3 characters'); } } render() { return ( <div className="search-bar"> <div className="search-component"> <input type="text" value={this.state.searchName} placeholder="Type in to search ..." onChange={this.updateSearchInput} /> <button onClick={this.search}> <i className="icon-search" /> Search </button> </div> {this.getError()} <div className="filters"> <div className="filter"> <label> <input type="checkbox" value="delivered" /> Delivered </label> </div> </div> </div> ); } } SearchBar.propTypes = { fetchPackages: PropTypes.func, }; export default connect(mapStateToProps, dispatchActionToProps)(SearchBar);
docs/src/examples/collections/Table/Variations/TableExampleSelectableInvertedRow.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Table } from 'semantic-ui-react' const TableExampleSelectableInvertedRow = () => ( <Table celled inverted selectable> <Table.Header> <Table.Row> <Table.HeaderCell>Name</Table.HeaderCell> <Table.HeaderCell>Status</Table.HeaderCell> <Table.HeaderCell>Notes</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row> <Table.Cell>John</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell textAlign='right'>None</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell textAlign='right'>Requires call</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jill</Table.Cell> <Table.Cell>Denied</Table.Cell> <Table.Cell textAlign='right'>None</Table.Cell> </Table.Row> </Table.Body> </Table> ) export default TableExampleSelectableInvertedRow
blueocean-material-icons/src/js/components/svg-icons/maps/satellite.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const MapsSatellite = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5 4.99h3C8 6.65 6.66 8 5 8V4.99zM5 12v-2c2.76 0 5-2.25 5-5.01h2C12 8.86 8.87 12 5 12zm0 6l3.5-4.5 2.5 3.01L14.5 12l4.5 6H5z"/> </SvgIcon> ); MapsSatellite.displayName = 'MapsSatellite'; MapsSatellite.muiName = 'SvgIcon'; export default MapsSatellite;
src/components/ShareExperience/common/TypeFormFooter.js
goodjoblife/GoodJobShare
import React from 'react'; import styles from './TypeFormFooter.module.css'; const TypeFormFooter = () => ( <div className={styles.footer}> 完成可解鎖全站 2 萬筆資訊 <span className={styles.unlockDuration}></span> </div> ); export default TypeFormFooter;
src/components/PortionManipulator/PortionManipulator.js
sars/appetini-front
import Button from 'components/Button/Button'; import { FormattedPlural } from 'react-intl'; import styles from './styles.scss'; import React from 'react'; export const PortionManipulator = ({availableCount, amount, onChangeAmount}) => { return ( <div className={styles.amountContainer}> <Button className={styles.amountButton} type="button" icon="remove" outlined mini flat onClick={() => onChangeAmount(amount - 1)}/> <div className={styles.amountText}> <div> <span>{amount}</span> &nbsp; <span className={styles.amountLabel}> <FormattedPlural value={amount} one="порция" few="порции" many="порций" other="порций"/> </span></div> {availableCount !== undefined && <div className={styles.avaliableAmount}>Доступно {availableCount}</div>} </div> <Button className={styles.amountButton} type="button" icon="add" outlined mini flat onClick={() => onChangeAmount(amount + 1)}/> </div> ); }; PortionManipulator.propTypes = { availableCount: React.PropTypes.number, amount: React.PropTypes.number.isRequired, onChangeAmount: React.PropTypes.func.isRequired }; export default PortionManipulator;
src/parser/priest/holy/CHANGELOG.js
sMteX/WoWAnalyzer
import React from 'react'; import { Khadaj, niseko, Yajinni, Zerotorescue } from 'CONTRIBUTORS'; import SpellLink from 'common/SpellLink'; import SPELLS from 'common/SPELLS'; export default [ { date: new Date('2019-04-09'), changes: <>Adding Holy Nova card and updating spreadsheet</>, contributors: [Khadaj], }, { date: new Date('2019-03-12'), changes: <>Fixed an error in the <SpellLink id={SPELLS.PRAYERFUL_LITANY.id} /> analyzer.</>, contributors: [Zerotorescue], }, { date: new Date('2018-12-18'), changes: <>Adding <SpellLink id={SPELLS.PROMISE_OF_DELIVERANCE.id} /> and <SpellLink id={SPELLS.DEATH_DENIED.id} />.</>, contributors: [Khadaj], }, { date: new Date('2018-11-05'), changes: 'Adding Renew suggestion.', contributors: [Khadaj], }, { date: new Date('2018-10-22'), changes: 'Adding mana efficiency tab.', contributors: [Khadaj], }, { date: new Date('2018-09-13'), changes: 'Adding Holy Priest Azerite traits.', contributors: [Khadaj], }, { date: new Date('2018-09-07'), changes: 'Creating Holy Priest spreadsheet export.', contributors: [Khadaj], }, { date: new Date('2018-09-06'), changes: 'Updating base Holy Priest checklist.', contributors: [Khadaj], }, { date: new Date('2018-07-28'), changes: <>Added suggestion for maintaining <SpellLink id={SPELLS.PERSEVERANCE_TALENT.id} /> and <SpellLink id={SPELLS.POWER_WORD_FORTITUDE.id} /> buffs.</>, contributors: [Yajinni], }, { date: new Date('2018-07-28'), changes: <>Added Stat box for <SpellLink id={SPELLS.COSMIC_RIPPLE_TALENT.id} />.</>, contributors: [Yajinni], }, { date: new Date('2018-07-26'), changes: <>Added Stat box for <SpellLink id={SPELLS.TRAIL_OF_LIGHT_TALENT.id} />.</>, contributors: [Yajinni], }, { date: new Date('2018-07-05'), changes: 'Updated Holy Priest spells for BFA and accounted for Holy Words cooldown reductions.', contributors: [niseko], }, ];
tests/format/flow-repo/react_modules/es6class-proptypes-callsite.js
prettier/prettier
/* @flow */ import React from 'react'; import Hello from './es6class-proptypes-module'; class HelloLocal extends React.Component<void, {name: string}, void> { defaultProps = {}; propTypes = { name: React.PropTypes.string.isRequired, }; render(): React.Element<*> { return <div>{this.props.name}</div>; } } class Callsite extends React.Component<void, {}, void> { render(): React.Element<*> { return ( <div> <Hello /> <HelloLocal /> </div> ); } } module.exports = Callsite;
src/templates/post.js
mccannsean421/mccannsean421.github.io
import React from 'react'; import Helmet from 'react-helmet'; export default function Template({data}) { const {markdownRemark: post} = data; //Retieving post from data.markdownRemark return ( <div> <div className="content-container"> <h1>{post.frontmatter.title}</h1> <div dangerouslySetInnerHTML={{__html: post.html}} /> </div> </div> ) } //GraphQL query to grab the post using the path export const postQuery = graphql` query blogPostByPath($path: String!) { markdownRemark(frontmatter: { path : { eq: $path } } ) { html frontmatter { path title } } } `
app/components/Toggle/index.js
alexsmartman/weather-react
/** * * LocaleToggle * */ import React from 'react'; import PropTypes from 'prop-types'; import Select from './Select'; import ToggleOption from '../ToggleOption'; function Toggle(props) { let content = (<option>--</option>); // If we have items, render them if (props.values) { content = props.values.map((value) => ( <ToggleOption key={value} value={value} message={props.messages[value]} /> )); } return ( <Select value={props.value} onChange={props.onToggle}> {content} </Select> ); } Toggle.propTypes = { onToggle: PropTypes.func, values: PropTypes.array, value: PropTypes.string, messages: PropTypes.object, }; export default Toggle;
app/react-icons/fa/venus-double.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaVenusDouble extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m40 11.8q0.2 3.5-1.2 6.5t-4.2 5-6 2.3v5.8h5q0.3 0 0.5 0.2t0.2 0.5v1.5q0 0.3-0.2 0.5t-0.5 0.2h-5v5q0 0.3-0.2 0.5t-0.5 0.2h-1.5q-0.3 0-0.5-0.2t-0.2-0.5v-5h-11.4v5q0 0.3-0.2 0.5t-0.5 0.2h-1.5q-0.3 0-0.5-0.2t-0.2-0.5v-5h-5q-0.3 0-0.5-0.2t-0.2-0.5v-1.5q0-0.3 0.2-0.5t0.5-0.2h5v-5.8q-3.3-0.3-6-2.3t-4.2-5-1.2-6.5q0.4-4.6 3.7-7.9t7.9-3.8q4.6-0.5 8.4 2.1 3.8-2.6 8.4-2.1 4.6 0.4 7.9 3.8t3.7 7.9z m-20 8q2.9-2.9 2.9-6.9t-2.9-7q-2.9 2.9-2.9 7t2.9 6.9z m-7.1 3.1q2.5 0 4.8-1.3-3.4-3.7-3.4-8.7 0-5 3.4-8.8-2.3-1.2-4.8-1.2-4.2 0-7.1 2.9t-2.9 7.1 2.9 7 7.1 3z m12.8 8.5v-5.8q-3-0.3-5.7-2.1-2.7 1.8-5.7 2.1v5.8h11.4z m1.4-8.5q4.2 0 7.1-3t2.9-7-2.9-7.1-7.1-2.9q-2.5 0-4.8 1.2 3.4 3.8 3.4 8.8 0 5-3.4 8.7 2.3 1.3 4.8 1.3z"/></g> </IconBase> ); } }
src/js/pages/FAQ.js
hadnazzar/ModernBusinessBootstrap-ReactComponent
import React from 'react'; import AccordionPanel from '../components/AccordionPanel'; import Subheading from '../components/Subheading'; export default class Layout extends React.Component { constructor() { super(); this.state = { title:"Welcome to Momoware!", }; } changeTitle(title){ this.setState({title}); } navigate() { console.log(this.props); } render() { return( <div> <AccordionPanel header="Lorem ipsum dolor sit amet, consectetur adipiscing elit?" content=" Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS." hrefNumber="#collapseOne" hrefId="collapseOne" /> <AccordionPanel header="Curabitur eget leo at velit imperdiet varius. In eu ipsum vitae velit congue iaculis vitae at risus?" content=" Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS." hrefNumber="#collapseTwo" hrefId="collapseTwo" /> <AccordionPanel header="Aenean consequat lorem ut felis ullamcorper?" content="Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS." hrefNumber="#collapseThree" hrefId="collapseThree" /> <AccordionPanel header="Lorem ipsum dolor sit amet, consectetur adipiscing elit?" content=" Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS." hrefNumber="#collapseFour" hrefId="collapseFour" /> <AccordionPanel header="Curabitur eget leo at velit imperdiet varius. In eu ipsum vitae velit congue iaculis vitae at risus?" content="Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS." hrefNumber="#collapseFive" hrefId="collapseFive" /> <AccordionPanel header="Aenean consequat lorem ut felis ullamcorper?" content="Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS." hrefNumber="#collapseSix" hrefId="collapseSix" /> <AccordionPanel header="Life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch." content=" Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS." hrefNumber="#collapseSeven" hrefId="collapseSeven" /> </div> ); } }
src/svg-icons/action/swap-vertical-circle.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSwapVerticalCircle = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM6.5 9L10 5.5 13.5 9H11v4H9V9H6.5zm11 6L14 18.5 10.5 15H13v-4h2v4h2.5z"/> </SvgIcon> ); ActionSwapVerticalCircle = pure(ActionSwapVerticalCircle); ActionSwapVerticalCircle.displayName = 'ActionSwapVerticalCircle'; ActionSwapVerticalCircle.muiName = 'SvgIcon'; export default ActionSwapVerticalCircle;
react-redux-tutorial/input-redux/src/index.js
react-scott/react-learn
import React from 'react' import { render } from 'react-dom' import { createStore } from 'redux' import { Provider } from 'react-redux' import App from './App' import inputApp from './reducers' let store = createStore(inputApp); render( <Provider store={store}> <App /> </Provider>, document.querySelector("#app") );
src/forms/NewConversationComposeForm/ReceiverSearchForm.js
llukasxx/school-organizer-front
import React from 'react' export class ReceiverSearch extends React.Component { constructor(props) { super(props) } render() { const { activeTab, query } = this.props let placeholder; switch(activeTab) { case 'students': placeholder = "Student name" break; case 'teachers': placeholder = "Teacher name" break; case 'groups': placeholder = "Group name" break; case 'lessons': placeholder = "Lesson name" break; } return ( <div className="input-group"> <span className="input-group-addon" id="sizing-addon1">Filter:</span> <input type="text" className="form-control" placeholder={placeholder} aria-describedby="sizing-addon1" {...query} onChange={(e) => { query.onChange(e) this.props.handleChange(e.target.value) }}/> </div> ) } } export default ReceiverSearch
app/javascript/components/collections/landing/SearchResults.js
avalonmediasystem/avalon
/* * Copyright 2011-2022, The Trustees of Indiana University and Northwestern * University. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * --- END LICENSE_HEADER BLOCK --- */ import React from 'react'; import '../Collection.scss'; import SearchResultsCard from './SearchResultsCard'; import CollectionFilterNoResults from '../CollectionsFilterNoResults'; import PropTypes from 'prop-types'; const SearchResults = ({ documents = [], baseUrl }) => { if (documents.length === 0) return ( <div style={{ paddingTop: '3rem' }}> <CollectionFilterNoResults /> </div> ); return ( <ul className="row list-unstyled search-within-search-results"> {documents.map((doc, index) => ( <li key={doc.id} className="col-sm-3"> <SearchResultsCard doc={doc} index={index} baseUrl={baseUrl} /> </li> ))} </ul> ); }; SearchResults.propTypes = { documents: PropTypes.array, baseUrl: PropTypes.string }; export default SearchResults;
server/sonar-web/src/main/js/apps/component-measures/details/drilldown/Breadcrumb.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 QualifierIcon from '../../../../components/shared/qualifier-icon'; import { isDiffMetric, formatLeak } from '../../utils'; import { formatMeasure } from '../../../../helpers/measures'; const Breadcrumb = ({ component, metric, onBrowse }) => { const handleClick = e => { e.preventDefault(); e.target.blur(); onBrowse(component); }; let inner; if (onBrowse) { inner = ( <a id={'component-measures-breadcrumb-' + component.key} href="#" onClick={handleClick}> {component.name} </a> ); } else { inner = <span>{component.name}</span>; } const value = isDiffMetric(metric) ? formatLeak(component.leak, metric) : formatMeasure(component.value, metric.type); return ( <span> <QualifierIcon qualifier={component.qualifier}/> &nbsp; {inner} {value != null && ( <span>{' (' + value + ')'}</span> )} </span> ); }; export default Breadcrumb;
app/javascript/mastodon/components/attachment_list.js
alarky/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; const filename = url => url.split('/').pop().split('#')[0].split('?')[0]; export default class AttachmentList extends ImmutablePureComponent { static propTypes = { media: ImmutablePropTypes.list.isRequired, }; render () { const { media } = this.props; return ( <div className='attachment-list'> <div className='attachment-list__icon'> <i className='fa fa-link' /> </div> <ul className='attachment-list__list'> {media.map(attachment => <li key={attachment.get('id')}> <a href={attachment.get('remote_url')} target='_blank' rel='noopener'>{filename(attachment.get('remote_url'))}</a> </li> )} </ul> </div> ); } }
app/javascript/mastodon/features/explore/results.js
maa123/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import { expandSearch } from 'mastodon/actions/search'; import Account from 'mastodon/containers/account_container'; import Status from 'mastodon/containers/status_container'; import { ImmutableHashtag as Hashtag } from 'mastodon/components/hashtag'; import { List as ImmutableList } from 'immutable'; import LoadMore from 'mastodon/components/load_more'; import LoadingIndicator from 'mastodon/components/loading_indicator'; const mapStateToProps = state => ({ isLoading: state.getIn(['search', 'isLoading']), results: state.getIn(['search', 'results']), }); const appendLoadMore = (id, list, onLoadMore) => { if (list.size >= 5) { return list.push(<LoadMore key={`${id}-load-more`} visible onClick={onLoadMore} />); } else { return list; } }; const renderAccounts = (results, onLoadMore) => appendLoadMore('accounts', results.get('accounts', ImmutableList()).map(item => ( <Account key={`account-${item}`} id={item} /> )), onLoadMore); const renderHashtags = (results, onLoadMore) => appendLoadMore('hashtags', results.get('hashtags', ImmutableList()).map(item => ( <Hashtag key={`tag-${item.get('name')}`} hashtag={item} /> )), onLoadMore); const renderStatuses = (results, onLoadMore) => appendLoadMore('statuses', results.get('statuses', ImmutableList()).map(item => ( <Status key={`status-${item}`} id={item} /> )), onLoadMore); export default @connect(mapStateToProps) class Results extends React.PureComponent { static propTypes = { results: ImmutablePropTypes.map, isLoading: PropTypes.bool, multiColumn: PropTypes.bool, dispatch: PropTypes.func.isRequired, }; state = { type: 'all', }; handleSelectAll = () => this.setState({ type: 'all' }); handleSelectAccounts = () => this.setState({ type: 'accounts' }); handleSelectHashtags = () => this.setState({ type: 'hashtags' }); handleSelectStatuses = () => this.setState({ type: 'statuses' }); handleLoadMoreAccounts = () => this.loadMore('accounts'); handleLoadMoreStatuses = () => this.loadMore('statuses'); handleLoadMoreHashtags = () => this.loadMore('hashtags'); loadMore (type) { const { dispatch } = this.props; dispatch(expandSearch(type)); } render () { const { isLoading, results } = this.props; const { type } = this.state; let filteredResults = ImmutableList(); if (!isLoading) { switch(type) { case 'all': filteredResults = filteredResults.concat(renderAccounts(results, this.handleLoadMoreAccounts), renderHashtags(results, this.handleLoadMoreHashtags), renderStatuses(results, this.handleLoadMoreStatuses)); break; case 'accounts': filteredResults = filteredResults.concat(renderAccounts(results, this.handleLoadMoreAccounts)); break; case 'hashtags': filteredResults = filteredResults.concat(renderHashtags(results, this.handleLoadMoreHashtags)); break; case 'statuses': filteredResults = filteredResults.concat(renderStatuses(results, this.handleLoadMoreStatuses)); break; } if (filteredResults.size === 0) { filteredResults = ( <div className='empty-column-indicator'> <FormattedMessage id='search_results.nothing_found' defaultMessage='Could not find anything for these search terms' /> </div> ); } } return ( <React.Fragment> <div className='account__section-headline'> <button onClick={this.handleSelectAll} className={type === 'all' && 'active'}><FormattedMessage id='search_results.all' defaultMessage='All' /></button> <button onClick={this.handleSelectAccounts} className={type === 'accounts' && 'active'}><FormattedMessage id='search_results.accounts' defaultMessage='People' /></button> <button onClick={this.handleSelectHashtags} className={type === 'hashtags' && 'active'}><FormattedMessage id='search_results.hashtags' defaultMessage='Hashtags' /></button> <button onClick={this.handleSelectStatuses} className={type === 'statuses' && 'active'}><FormattedMessage id='search_results.statuses' defaultMessage='Toots' /></button> </div> <div className='explore__search-results'> {isLoading ? <LoadingIndicator /> : filteredResults} </div> </React.Fragment> ); } }
src/components/component_navbar.js
paschalidi/shopping-cart-reactjs-redux
import React, { Component } from 'react'; import { connect } from 'react-redux' class NavigationBar extends Component { render() { return ( <div className="component-navbar"> <div className="navigation-bar"> <nav className="navbar navbar-default"> <div className="container-fluid"> <div className="navbar-header"> <a className="navbar-brand" href="#"> Shopping Chart </a> </div> <div className="collapse navbar-collapse"> <ul className="nav navbar-nav navbar-right"> <p className="navbar-text"> <span className="badge">{this.props.itemCounter}</span> </p> </ul> </div> </div> </nav> </div> </div> ); } } function mapsStateToProps(state) { return { itemCounter: state.itemCounter } } export default connect(mapsStateToProps)(NavigationBar)
react/features/calendar-sync/components/CalendarList.web.js
jitsi/jitsi-meet
// @flow import Spinner from '@atlaskit/spinner'; import React from 'react'; import { createCalendarClickedEvent, sendAnalytics } from '../../analytics'; import { translate } from '../../base/i18n'; import { Icon, IconPlusCalendar } from '../../base/icons'; import { AbstractPage } from '../../base/react'; import { connect } from '../../base/redux'; import { openSettingsDialog, SETTINGS_TABS } from '../../settings'; import { refreshCalendar } from '../actions'; import { ERRORS } from '../constants'; import CalendarListContent from './CalendarListContent'; declare var interfaceConfig: Object; /** * The type of the React {@code Component} props of {@link CalendarList}. */ type Props = { /** * The error object containing details about any error that has occurred * while interacting with calendar integration. */ _calendarError: ?Object, /** * Whether or not a calendar may be connected for fetching calendar events. */ _hasIntegrationSelected: boolean, /** * Whether or not events have been fetched from a calendar. */ _hasLoadedEvents: boolean, /** * Indicates if the list is disabled or not. */ disabled: boolean, /** * The Redux dispatch function. */ dispatch: Function, /** * The translate function. */ t: Function }; /** * Component to display a list of events from the user's calendar. */ class CalendarList extends AbstractPage<Props> { /** * Initializes a new {@code CalendarList} instance. * * @inheritdoc */ constructor(props) { super(props); // Bind event handlers so they are only bound once per instance. this._getRenderListEmptyComponent = this._getRenderListEmptyComponent.bind(this); this._onOpenSettings = this._onOpenSettings.bind(this); this._onKeyPressOpenSettings = this._onKeyPressOpenSettings.bind(this); this._onRefreshEvents = this._onRefreshEvents.bind(this); } /** * Implements React's {@link Component#render}. * * @inheritdoc */ render() { const { disabled } = this.props; return ( CalendarListContent ? <CalendarListContent disabled = { disabled } listEmptyComponent = { this._getRenderListEmptyComponent() } /> : null ); } /** * Returns a component for showing the error message related to calendar * sync. * * @private * @returns {React$Component} */ _getErrorMessage() { const { _calendarError = {}, t } = this.props; let errorMessageKey = 'calendarSync.error.generic'; let showRefreshButton = true; let showSettingsButton = true; if (_calendarError.error === ERRORS.GOOGLE_APP_MISCONFIGURED) { errorMessageKey = 'calendarSync.error.appConfiguration'; showRefreshButton = false; showSettingsButton = false; } else if (_calendarError.error === ERRORS.AUTH_FAILED) { errorMessageKey = 'calendarSync.error.notSignedIn'; showRefreshButton = false; } return ( <div className = 'meetings-list-empty'> <p className = 'description'> { t(errorMessageKey) } </p> <div className = 'calendar-action-buttons'> { showSettingsButton && <div className = 'button' onClick = { this._onOpenSettings }> { t('calendarSync.permissionButton') } </div> } { showRefreshButton && <div className = 'button' onClick = { this._onRefreshEvents }> { t('calendarSync.refresh') } </div> } </div> </div> ); } _getRenderListEmptyComponent: () => Object; /** * Returns a list empty component if a custom one has to be rendered instead * of the default one in the {@link NavigateSectionList}. * * @private * @returns {React$Component} */ _getRenderListEmptyComponent() { const { _calendarError, _hasIntegrationSelected, _hasLoadedEvents, t } = this.props; if (_calendarError) { return this._getErrorMessage(); } else if (_hasIntegrationSelected && _hasLoadedEvents) { return ( <div className = 'meetings-list-empty'> <p className = 'description'> { t('calendarSync.noEvents') } </p> <div className = 'button' onClick = { this._onRefreshEvents }> { t('calendarSync.refresh') } </div> </div> ); } else if (_hasIntegrationSelected && !_hasLoadedEvents) { return ( <div className = 'meetings-list-empty'> <Spinner invertColor = { true } isCompleting = { false } size = 'medium' /> </div> ); } return ( <div className = 'meetings-list-empty'> <div className = 'meetings-list-empty-image'> <img alt = { t('welcomepage.logo.calendar') } src = './images/calendar.svg' /> </div> <div className = 'description'> { t('welcomepage.connectCalendarText', { app: interfaceConfig.APP_NAME, provider: interfaceConfig.PROVIDER_NAME }) } </div> <div className = 'meetings-list-empty-button' onClick = { this._onOpenSettings } onKeyPress = { this._onKeyPressOpenSettings } role = 'button'> <Icon className = 'meetings-list-empty-icon' src = { IconPlusCalendar } /> <span>{ t('welcomepage.connectCalendarButton') }</span> </div> </div> ); } _onOpenSettings: () => void; /** * Opens {@code SettingsDialog}. * * @private * @returns {void} */ _onOpenSettings() { sendAnalytics(createCalendarClickedEvent('connect')); this.props.dispatch(openSettingsDialog(SETTINGS_TABS.CALENDAR)); } _onKeyPressOpenSettings: (Object) => void; /** * KeyPress handler for accessibility. * * @param {Object} e - The key event to handle. * * @returns {void} */ _onKeyPressOpenSettings(e) { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); this._onOpenSettings(); } } _onRefreshEvents: () => void; /** * Gets an updated list of calendar events. * * @private * @returns {void} */ _onRefreshEvents() { this.props.dispatch(refreshCalendar(true)); } } /** * Maps (parts of) the Redux state to the associated props for the * {@code CalendarList} component. * * @param {Object} state - The Redux state. * @private * @returns {{ * _calendarError: Object, * _hasIntegrationSelected: boolean, * _hasLoadedEvents: boolean * }} */ function _mapStateToProps(state) { const { error, events, integrationType, isLoadingEvents } = state['features/calendar-sync']; return { _calendarError: error, _hasIntegrationSelected: Boolean(integrationType), _hasLoadedEvents: Boolean(events) || !isLoadingEvents }; } export default translate(connect(_mapStateToProps)(CalendarList));
src/svg-icons/action/add-shopping-cart.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAddShoppingCart = (props) => ( <SvgIcon {...props}> <path d="M11 9h2V6h3V4h-3V1h-2v3H8v2h3v3zm-4 9c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zm10 0c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2zm-9.83-3.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.86-7.01L19.42 4h-.01l-1.1 2-2.76 5H8.53l-.13-.27L6.16 6l-.95-2-.94-2H1v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.13 0-.25-.11-.25-.25z"/> </SvgIcon> ); ActionAddShoppingCart = pure(ActionAddShoppingCart); ActionAddShoppingCart.displayName = 'ActionAddShoppingCart'; ActionAddShoppingCart.muiName = 'SvgIcon'; export default ActionAddShoppingCart;
src/components/RootHomeComponent.js
Neitsch/pd-tournament
import React from 'react'; import Relay from 'react-relay'; class RootHomeComponent extends React.Component { static propTypes = { viewer: React.PropTypes.any, } constructor(props) { super(props); this.state = { loggedIn: false, }; } render() { if (this.state.loggedIn) { return <span>{this.props.viewer.user.id}</span>; } return <span>Pls log in</span>; } } const RootHomeComponentContainer = Relay.createContainer(RootHomeComponent, { fragments: { viewer: () => Relay.QL` fragment on ReindexViewer { user { id } } `, }, }); export default RootHomeComponentContainer;
src/svg-icons/image/crop-rotate.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCropRotate = (props) => ( <SvgIcon {...props}> <path d="M7.47 21.49C4.2 19.93 1.86 16.76 1.5 13H0c.51 6.16 5.66 11 11.95 11 .23 0 .44-.02.66-.03L8.8 20.15l-1.33 1.34zM12.05 0c-.23 0-.44.02-.66.04l3.81 3.81 1.33-1.33C19.8 4.07 22.14 7.24 22.5 11H24c-.51-6.16-5.66-11-11.95-11zM16 14h2V8c0-1.11-.9-2-2-2h-6v2h6v6zm-8 2V4H6v2H4v2h2v8c0 1.1.89 2 2 2h8v2h2v-2h2v-2H8z"/> </SvgIcon> ); ImageCropRotate = pure(ImageCropRotate); ImageCropRotate.displayName = 'ImageCropRotate'; ImageCropRotate.muiName = 'SvgIcon'; export default ImageCropRotate;
src/filters/Number.js
opensourcegeek/react-bootstrap-table
import React from 'react'; import classSet from 'classnames'; import Const from '../Const'; const legalComparators = ["=", ">", ">=", "<", "<=", "!="]; class NumberFilter extends React.Component { constructor(props) { super(props); this.numberComparators = this.props.numberComparators || legalComparators; this.timeout = null; this.state = { isPlaceholderSelected: (this.props.defaultValue == undefined || this.props.defaultValue.number == undefined || (this.props.options && this.props.options.indexOf(this.props.defaultValue.number) == -1)) }; this.onChangeNumber = this.onChangeNumber.bind(this); this.onChangeNumberSet = this.onChangeNumberSet.bind(this); this.onChangeComparator = this.onChangeComparator.bind(this); } onChangeNumber(event) { if (this.refs.numberFilterComparator.value === "") { return; } if (this.timeout) { clearTimeout(this.timeout); } const self = this; const filterValue = event.target.value; this.timeout = setTimeout(function() { self.props.filterHandler({number: filterValue, comparator: self.refs.numberFilterComparator.value}, Const.FILTER_TYPE.NUMBER); }, self.props.delay); } onChangeNumberSet(event) { this.setState({isPlaceholderSelected: (event.target.value === "")}); if (this.refs.numberFilterComparator.value === "") { return; } this.props.filterHandler({number: event.target.value, comparator: this.refs.numberFilterComparator.value}, Const.FILTER_TYPE.NUMBER); } onChangeComparator(event) { if (this.refs.numberFilter.value === "") { return; } this.props.filterHandler({number: this.refs.numberFilter.value, comparator: event.target.value}, Const.FILTER_TYPE.NUMBER); } getComparatorOptions() { let optionTags = []; optionTags.push(<option key="-1"></option>); for (let i = 0; i < this.numberComparators.length; i++) { optionTags.push(<option key={i} value={this.numberComparators[i]}>{this.numberComparators[i]}</option>); }; return optionTags; } getNumberOptions() { let optionTags = []; const options = this.props.options; optionTags.push(<option key="-1" value="">{this.props.placeholder || `Select ${this.props.columnName}...`}</option>); for (let i = 0; i < options.length; i++) { optionTags.push(<option key={i} value={options[i]}>{options[i]}</option>); }; return optionTags; } componentDidMount() { if (this.refs.numberFilterComparator.value && this.refs.numberFilter.value) { this.props.filterHandler({number: this.refs.numberFilter.value, comparator: this.refs.numberFilterComparator.value}, Const.FILTER_TYPE.NUMBER); } } componentWillUnmount() { clearTimeout(this.timeout); } render() { var selectClass = classSet("select-filter", "number-filter-input", "form-control", { "placeholder-selected": this.state.isPlaceholderSelected }); return ( <div className="filter number-filter"> <select ref="numberFilterComparator" className="number-filter-comparator form-control" onChange={this.onChangeComparator} defaultValue={(this.props.defaultValue) ? this.props.defaultValue.comparator : ""}> {this.getComparatorOptions()} </select> {(this.props.options) ? <select ref="numberFilter" className={selectClass} onChange={this.onChangeNumberSet} defaultValue={(this.props.defaultValue) ? this.props.defaultValue.number : ""}> {this.getNumberOptions()} </select> : <input ref="numberFilter" type="number" className="number-filter-input form-control" placeholder={this.props.placeholder || `Enter ${this.props.columnName}...`} onChange={this.onChangeNumber} defaultValue={(this.props.defaultValue) ? this.props.defaultValue.number : ""} />} </div> ); } }; NumberFilter.propTypes = { filterHandler: React.PropTypes.func.isRequired, options: React.PropTypes.arrayOf(React.PropTypes.number), defaultValue: React.PropTypes.shape({ number: React.PropTypes.number, comparator: React.PropTypes.oneOf(legalComparators) }), delay: React.PropTypes.number, numberComparators: function(props, propName) { if (!props[propName]) { return; } for (let i = 0; i < props[propName].length; i++) { let comparatorIsValid = false; for (let j = 0; j < legalComparators.length; j++) { if (legalComparators[j] === props[propName][i]) { comparatorIsValid = true; break; } } if (!comparatorIsValid) { return new Error(`Number comparator provided is not supported. Use only ${legalComparators}`); } } }, placeholder: React.PropTypes.string, columnName: React.PropTypes.string }; NumberFilter.defaultProps = { delay: Const.FILTER_DELAY }; export default NumberFilter;
src/propTypes/EdgeInsetsPropType.js
omeid/react-native-mock
/** * https://github.com/facebook/react-native/blob/master/Libraries/StyleSheet/EdgeInsetsPropType.js */ import React from 'react'; const { PropTypes } = React; var EdgeInsetsPropType = PropTypes.shape({ top: PropTypes.number, left: PropTypes.number, bottom: PropTypes.number, right: PropTypes.number, }); module.exports = EdgeInsetsPropType;
src/components/import/ImportMandatoryField.js
secretin/secretin-app
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Input from 'components/utilities/Input'; class ImportMandatoryField extends Component { static propTypes = { field: PropTypes.object, onChange: PropTypes.func, }; constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); } handleChange({ value }) { const params = { field: this.props.field, value, }; this.props.onChange(params); } render() { return ( <Input ref={ref => { this.input = ref; }} label={this.props.field.name} name={this.props.field.name} value={this.props.field.value} onChange={this.handleChange} type={this.props.field.type} /> ); } } export default ImportMandatoryField;
app/javascript/mastodon/features/ui/components/column_subheading.js
tateisu/mastodon
import React from 'react'; import PropTypes from 'prop-types'; const ColumnSubheading = ({ text }) => { return ( <div className='column-subheading'> {text} </div> ); }; ColumnSubheading.propTypes = { text: PropTypes.string.isRequired, }; export default ColumnSubheading;
node_modules/node_modules/recharts/demo/component/RadialBarChart.js
SerendpityZOEY/Fixr-RelevantCodeSearch
import React from 'react'; import { RadialBarChart, RadialBar, Cell, Legend, Tooltip, ResponsiveContainer } from 'recharts'; import { changeNumberOfData } from './utils'; import { scaleOrdinal, schemeCategory10 } from 'd3-scale'; const colors = scaleOrdinal(schemeCategory10).range(); const data = [ { name: '18-24', uv: 31.47, pv: 2400, fill: '#8884d8' }, { name: '25-29', uv: 26.69, pv: 4500, fill: '#83a6ed' }, { name: '30-34', uv: 15.69, pv: -1398, fill: '#8dd1e1' }, { name: '35-39', uv: 8.22, pv: 2800, fill: '#82ca9d' }, { name: '40-49', uv: 8.63, pv: 1908, fill: '#a4de6c' }, { name: '50+', uv: 2.63, pv: -2800, fill: '#d0ed57' }, { name: 'unknow', uv: 6.67, pv: 4800, fill: '#ffc658' }, ]; const initilaState = { data }; export default React.createClass({ getInitialState() { return initilaState; }, handleChangeData() { this.setState(() => _.mapValues(initilaState, changeNumberOfData)); }, render () { const { data } = this.state; const style = { lineHeight: '24px', left: 300, }; const label = { orientation: 'outer' }; return ( <div className='radial-bar-charts'> <a href="javascript: void(0);" className="btn update" onClick={this.handleChangeData} > change data </a> <br/> <p>RadialBarChart</p> <div className="radial-bar-chart-wrapper"> <RadialBarChart width={500} height={300} cx={150} cy={150} innerRadius={20} outerRadius={140} barSize={10} data={data}> <RadialBar minAngle={15} label={label} background dataKey="uv"> { data.map((entry, index) => ( <Cell key={`cell-${index}`} fill={colors[index]}/> )) } </RadialBar> <Legend iconSize={10} width={120} height={140} layout="vertical" verticalAlign="middle" wrapperStyle={style} /> <Tooltip/> </RadialBarChart> </div> <p>RadialBarChart with positive and negative value</p> <div className="radial-bar-chart-wrapper"> <RadialBarChart width={500} height={300} cx={150} cy={150} innerRadius={20} outerRadius={140} data={data}> <RadialBar startAngle={90} endAngle={-270} label={label} background dataKey="pv" /> <Legend iconSize={10} width={120} height={140} layout="vertical" verticalAlign="middle" wrapperStyle={style} /> <Tooltip/> </RadialBarChart> </div> <p>RadialBarChart wrapped by ResponsiveContainer</p> <div className="radial-bar-chart-wrapper"> <ResponsiveContainer> <RadialBarChart data={data} cx="50%" cy="90%" innerRadius="20%" outerRadius="90%" > <RadialBar minAngle={15} label={label} background dataKey="uv" /> <Legend iconSize={10} width={120} height={140} layout="vertical" verticalAlign="middle" wrapperStyle={style} /> </RadialBarChart> </ResponsiveContainer> </div> </div> ); } });
src/app.js
richard-leagh/evolution-calc
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import Header from './components/Header'; import PokeStore from './stores/PokeStore'; import VisibleCurrentInfo from './containers/VisibleCurrentInfo'; import VisibleEvolveInfo from './containers/VisibleEvolveInfo'; import VisiblePokeSelectForm from './containers/VisiblePokeSelectForm'; import actions from './actions/Actions'; const App = () => { return ( <div> <Header/> <VisiblePokeSelectForm/> <VisibleEvolveInfo/> <VisibleCurrentInfo/> </div> ); }; const render = () => { ReactDOM.render( <Provider store={PokeStore}> <App /> </Provider>, document.getElementById('root') ); }; render(); console.log("hello WOrld");
src/containers/weather/searchbar.js
MeKyleH/ReactPortfolioStuff
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchWeather } from '../../actions/index'; class SearchBar extends Component { constructor(props) { super(props); this.state = { term: '' }; this.onInputChange = this.onInputChange.bind(this); this.onFormSubmit = this.onFormSubmit.bind(this); } onInputChange(event) { this.setState({ term: event.target.value }) } onFormSubmit(event) { event.preventDefault(); this.props.fetchWeather(this.state.term); this.setState({ term: '' }); } render() { return ( <form onSubmit={this.onFormSubmit} className="input-group"> <input placeholder="Enter city to get a five day forecast" className="form-control" value={this.state.term} onChange={this.onInputChange} /> <span className="input-group-btn"> <button type="submit" className="btn btn-secondary">Submit</button> </span> </form> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchWeather }, dispatch); } export default connect(null, mapDispatchToProps)(SearchBar);
src/components/examples/exampleImg.js
Jguardado/ComponentBase
import React, { Component } from 'react'; export default class Picture extends Component { constructor(props) { super(props); } render() { return ( <div className='center'> <legend className='headingtext'>Example Picture</legend> <img className='picture' src='/src/images/myFace-min.jpg'/> </div> ); } }
Libraries/Components/WebView/WebView.ios.js
thotegowda/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule WebView * @noflow */ 'use strict'; var ActivityIndicator = require('ActivityIndicator'); var EdgeInsetsPropType = require('EdgeInsetsPropType'); var React = require('React'); var PropTypes = require('prop-types'); var ReactNative = require('ReactNative'); var StyleSheet = require('StyleSheet'); var Text = require('Text'); var UIManager = require('UIManager'); var View = require('View'); var ViewPropTypes = require('ViewPropTypes'); var ScrollView = require('ScrollView'); var deprecatedPropType = require('deprecatedPropType'); var invariant = require('fbjs/lib/invariant'); var keyMirror = require('fbjs/lib/keyMirror'); var processDecelerationRate = require('processDecelerationRate'); var requireNativeComponent = require('requireNativeComponent'); var resolveAssetSource = require('resolveAssetSource'); var RCTWebViewManager = require('NativeModules').WebViewManager; var BGWASH = 'rgba(255,255,255,0.8)'; var RCT_WEBVIEW_REF = 'webview'; var WebViewState = keyMirror({ IDLE: null, LOADING: null, ERROR: null, }); const NavigationType = keyMirror({ click: true, formsubmit: true, backforward: true, reload: true, formresubmit: true, other: true, }); const JSNavigationScheme = 'react-js-navigation'; type ErrorEvent = { domain: any, code: any, description: any, } type Event = Object; const DataDetectorTypes = [ 'phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all', ]; var defaultRenderLoading = () => ( <View style={styles.loadingView}> <ActivityIndicator /> </View> ); var defaultRenderError = (errorDomain, errorCode, errorDesc) => ( <View style={styles.errorContainer}> <Text style={styles.errorTextTitle}> Error loading page </Text> <Text style={styles.errorText}> {'Domain: ' + errorDomain} </Text> <Text style={styles.errorText}> {'Error Code: ' + errorCode} </Text> <Text style={styles.errorText}> {'Description: ' + errorDesc} </Text> </View> ); /** * `WebView` renders web content in a native view. * *``` * import React, { Component } from 'react'; * import { WebView } from 'react-native'; * * class MyWeb extends Component { * render() { * return ( * <WebView * source={{uri: 'https://github.com/facebook/react-native'}} * style={{marginTop: 20}} * /> * ); * } * } *``` * * You can use this component to navigate back and forth in the web view's * history and configure various properties for the web content. */ class WebView extends React.Component { static JSNavigationScheme = JSNavigationScheme; static NavigationType = NavigationType; static propTypes = { ...ViewPropTypes, html: deprecatedPropType( PropTypes.string, 'Use the `source` prop instead.' ), url: deprecatedPropType( PropTypes.string, 'Use the `source` prop instead.' ), /** * Loads static html or a uri (with optional headers) in the WebView. */ source: PropTypes.oneOfType([ PropTypes.shape({ /* * The URI to load in the `WebView`. Can be a local or remote file. */ uri: PropTypes.string, /* * The HTTP Method to use. Defaults to GET if not specified. * NOTE: On Android, only GET and POST are supported. */ method: PropTypes.string, /* * Additional HTTP headers to send with the request. * NOTE: On Android, this can only be used with GET requests. */ headers: PropTypes.object, /* * The HTTP body to send with the request. This must be a valid * UTF-8 string, and will be sent exactly as specified, with no * additional encoding (e.g. URL-escaping or base64) applied. * NOTE: On Android, this can only be used with POST requests. */ body: PropTypes.string, }), PropTypes.shape({ /* * A static HTML page to display in the WebView. */ html: PropTypes.string, /* * The base URL to be used for any relative links in the HTML. */ baseUrl: PropTypes.string, }), /* * Used internally by packager. */ PropTypes.number, ]), /** * Function that returns a view to show if there's an error. */ renderError: PropTypes.func, // view to show if there's an error /** * Function that returns a loading indicator. */ renderLoading: PropTypes.func, /** * Function that is invoked when the `WebView` has finished loading. */ onLoad: PropTypes.func, /** * Function that is invoked when the `WebView` load succeeds or fails. */ onLoadEnd: PropTypes.func, /** * Function that is invoked when the `WebView` starts loading. */ onLoadStart: PropTypes.func, /** * Function that is invoked when the `WebView` load fails. */ onError: PropTypes.func, /** * Boolean value that determines whether the web view bounces * when it reaches the edge of the content. The default value is `true`. * @platform ios */ bounces: PropTypes.bool, /** * A floating-point number that determines how quickly the scroll view * decelerates after the user lifts their finger. You may also use the * string shortcuts `"normal"` and `"fast"` which match the underlying iOS * settings for `UIScrollViewDecelerationRateNormal` and * `UIScrollViewDecelerationRateFast` respectively: * * - normal: 0.998 * - fast: 0.99 (the default for iOS web view) * @platform ios */ decelerationRate: ScrollView.propTypes.decelerationRate, /** * Boolean value that determines whether scrolling is enabled in the * `WebView`. The default value is `true`. * @platform ios */ scrollEnabled: PropTypes.bool, /** * Controls whether to adjust the content inset for web views that are * placed behind a navigation bar, tab bar, or toolbar. The default value * is `true`. */ automaticallyAdjustContentInsets: PropTypes.bool, /** * The amount by which the web view content is inset from the edges of * the scroll view. Defaults to {top: 0, left: 0, bottom: 0, right: 0}. */ contentInset: EdgeInsetsPropType, /** * Function that is invoked when the `WebView` loading starts or ends. */ onNavigationStateChange: PropTypes.func, /** * A function that is invoked when the webview calls `window.postMessage`. * Setting this property will inject a `postMessage` global into your * webview, but will still call pre-existing values of `postMessage`. * * `window.postMessage` accepts one argument, `data`, which will be * available on the event object, `event.nativeEvent.data`. `data` * must be a string. */ onMessage: PropTypes.func, /** * Boolean value that forces the `WebView` to show the loading view * on the first load. */ startInLoadingState: PropTypes.bool, /** * The style to apply to the `WebView`. */ style: ViewPropTypes.style, /** * Determines the types of data converted to clickable URLs in the web view’s content. * By default only phone numbers are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes: PropTypes.oneOfType([ PropTypes.oneOf(DataDetectorTypes), PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), ]), /** * Boolean value to enable JavaScript in the `WebView`. Used on Android only * as JavaScript is enabled by default on iOS. The default value is `true`. * @platform android */ javaScriptEnabled: PropTypes.bool, /** * Boolean value to enable third party cookies in the `WebView`. Used on * Android Lollipop and above only as third party cookies are enabled by * default on Android Kitkat and below and on iOS. The default value is `true`. * @platform android */ thirdPartyCookiesEnabled: PropTypes.bool, /** * Boolean value to control whether DOM Storage is enabled. Used only in * Android. * @platform android */ domStorageEnabled: PropTypes.bool, /** * Set this to provide JavaScript that will be injected into the web page * when the view loads. */ injectedJavaScript: PropTypes.string, /** * Sets the user-agent for the `WebView`. * @platform android */ userAgent: PropTypes.string, /** * Boolean that controls whether the web content is scaled to fit * the view and enables the user to change the scale. The default value * is `true`. */ scalesPageToFit: PropTypes.bool, /** * Function that allows custom handling of any web view requests. Return * `true` from the function to continue loading the request and `false` * to stop loading. * @platform ios */ onShouldStartLoadWithRequest: PropTypes.func, /** * Boolean that determines whether HTML5 videos play inline or use the * native full-screen controller. The default value is `false`. * * **NOTE** : In order for video to play inline, not only does this * property need to be set to `true`, but the video element in the HTML * document must also include the `webkit-playsinline` attribute. * @platform ios */ allowsInlineMediaPlayback: PropTypes.bool, /** * Boolean that determines whether HTML5 audio and video requires the user * to tap them before they start playing. The default value is `true`. */ mediaPlaybackRequiresUserAction: PropTypes.bool, /** * Function that accepts a string that will be passed to the WebView and * executed immediately as JavaScript. */ injectJavaScript: PropTypes.func, /** * Specifies the mixed content mode. i.e WebView will allow a secure origin to load content from any other origin. * * Possible values for `mixedContentMode` are: * * - `'never'` (default) - WebView will not allow a secure origin to load content from an insecure origin. * - `'always'` - WebView will allow a secure origin to load content from any other origin, even if that origin is insecure. * - `'compatibility'` - WebView will attempt to be compatible with the approach of a modern web browser with regard to mixed content. * @platform android */ mixedContentMode: PropTypes.oneOf([ 'never', 'always', 'compatibility' ]), }; static defaultProps = { scalesPageToFit: true, }; state = { viewState: WebViewState.IDLE, lastErrorEvent: (null: ?ErrorEvent), startInLoadingState: true, }; componentWillMount() { if (this.props.startInLoadingState) { this.setState({viewState: WebViewState.LOADING}); } } render() { var otherView = null; if (this.state.viewState === WebViewState.LOADING) { otherView = (this.props.renderLoading || defaultRenderLoading)(); } else if (this.state.viewState === WebViewState.ERROR) { var errorEvent = this.state.lastErrorEvent; invariant( errorEvent != null, 'lastErrorEvent expected to be non-null' ); otherView = (this.props.renderError || defaultRenderError)( errorEvent.domain, errorEvent.code, errorEvent.description ); } else if (this.state.viewState !== WebViewState.IDLE) { console.error( 'RCTWebView invalid state encountered: ' + this.state.loading ); } var webViewStyles = [styles.container, styles.webView, this.props.style]; if (this.state.viewState === WebViewState.LOADING || this.state.viewState === WebViewState.ERROR) { // if we're in either LOADING or ERROR states, don't show the webView webViewStyles.push(styles.hidden); } var onShouldStartLoadWithRequest = this.props.onShouldStartLoadWithRequest && ((event: Event) => { var shouldStart = this.props.onShouldStartLoadWithRequest && this.props.onShouldStartLoadWithRequest(event.nativeEvent); RCTWebViewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier); }); var decelerationRate = processDecelerationRate(this.props.decelerationRate); var source = this.props.source || {}; if (this.props.html) { source.html = this.props.html; } else if (this.props.url) { source.uri = this.props.url; } const messagingEnabled = typeof this.props.onMessage === 'function'; var webView = <RCTWebView ref={RCT_WEBVIEW_REF} key="webViewKey" style={webViewStyles} source={resolveAssetSource(source)} injectedJavaScript={this.props.injectedJavaScript} bounces={this.props.bounces} scrollEnabled={this.props.scrollEnabled} decelerationRate={decelerationRate} contentInset={this.props.contentInset} automaticallyAdjustContentInsets={this.props.automaticallyAdjustContentInsets} onLoadingStart={this._onLoadingStart} onLoadingFinish={this._onLoadingFinish} onLoadingError={this._onLoadingError} messagingEnabled={messagingEnabled} onMessage={this._onMessage} onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} scalesPageToFit={this.props.scalesPageToFit} allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback} mediaPlaybackRequiresUserAction={this.props.mediaPlaybackRequiresUserAction} dataDetectorTypes={this.props.dataDetectorTypes} />; return ( <View style={styles.container}> {webView} {otherView} </View> ); } /** * Go forward one page in the web view's history. */ goForward = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.goForward, null ); }; /** * Go back one page in the web view's history. */ goBack = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.goBack, null ); }; /** * Reloads the current page. */ reload = () => { this.setState({viewState: WebViewState.LOADING}); UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.reload, null ); }; /** * Stop loading the current page. */ stopLoading = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.stopLoading, null ); }; /** * Posts a message to the web view, which will emit a `message` event. * Accepts one argument, `data`, which must be a string. * * In your webview, you'll need to something like the following. * * ```js * document.addEventListener('message', e => { document.title = e.data; }); * ``` */ postMessage = (data) => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.postMessage, [String(data)] ); }; /** * Injects a javascript string into the referenced WebView. Deliberately does not * return a response because using eval() to return a response breaks this method * on pages with a Content Security Policy that disallows eval(). If you need that * functionality, look into postMessage/onMessage. */ injectJavaScript = (data) => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.injectJavaScript, [data] ); }; /** * We return an event with a bunch of fields including: * url, title, loading, canGoBack, canGoForward */ _updateNavigationState = (event: Event) => { if (this.props.onNavigationStateChange) { this.props.onNavigationStateChange(event.nativeEvent); } }; /** * Returns the native `WebView` node. */ getWebViewHandle = (): any => { return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]); }; _onLoadingStart = (event: Event) => { var onLoadStart = this.props.onLoadStart; onLoadStart && onLoadStart(event); this._updateNavigationState(event); }; _onLoadingError = (event: Event) => { event.persist(); // persist this event because we need to store it var {onError, onLoadEnd} = this.props; onError && onError(event); onLoadEnd && onLoadEnd(event); console.warn('Encountered an error loading page', event.nativeEvent); this.setState({ lastErrorEvent: event.nativeEvent, viewState: WebViewState.ERROR }); }; _onLoadingFinish = (event: Event) => { var {onLoad, onLoadEnd} = this.props; onLoad && onLoad(event); onLoadEnd && onLoadEnd(event); this.setState({ viewState: WebViewState.IDLE, }); this._updateNavigationState(event); }; _onMessage = (event: Event) => { var {onMessage} = this.props; onMessage && onMessage(event); } } var RCTWebView = requireNativeComponent('RCTWebView', WebView, { nativeOnly: { onLoadingStart: true, onLoadingError: true, onLoadingFinish: true, onMessage: true, messagingEnabled: PropTypes.bool, }, }); var styles = StyleSheet.create({ container: { flex: 1, }, errorContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: BGWASH, }, errorText: { fontSize: 14, textAlign: 'center', marginBottom: 2, }, errorTextTitle: { fontSize: 15, fontWeight: '500', marginBottom: 10, }, hidden: { height: 0, flex: 0, // disable 'flex:1' when hiding a View }, loadingView: { backgroundColor: BGWASH, flex: 1, justifyContent: 'center', alignItems: 'center', height: 100, }, webView: { backgroundColor: '#ffffff', } }); module.exports = WebView;
src/components/video-detail.js
hectorcoronado/react-youtube-videoplayer
import React from 'react'; /* Like in VideoListItem, we can destructure the props object by passing in {video} as an argument to this functional component, thereby automatically declaring a variable with the same name that gives us access to props.video. */ const VideoDetail = ({video}) => { // Check if we haven't yet fetched (or finished fetching) video data from YouTube, show this div: if(!video) { return <div>Loading...</div> } // Otherwise, show this: // everything after video. is something that is coming back to us from the YouTube obj: const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe className="embed-responsive-item" src={url}></iframe> </div> <div className="details"> {/* ...same as above, with the videoId variable, everything after video. is part of the returned object from YouTube: */} <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ); }; export default VideoDetail;
examples/huge-apps/routes/Course/components/Nav.js
davertron/react-router
import React from 'react'; import { Link } from 'react-router'; import AnnouncementsRoute from '../routes/Announcements'; import AssignmentsRoute from '../routes/Assignments'; import GradesRoute from '../routes/Grades'; const styles = {}; styles.nav = { borderBottom: '1px solid #aaa' }; styles.link = { display: 'inline-block', padding: 10, textDecoration: 'none', }; styles.activeLink = Object.assign({}, styles.link, { //color: 'red' }); class Nav extends React.Component { render () { var { course } = this.props; var pages = [ ['announcements', 'Announcements'], ['assignments', 'Assignments'], ['grades', 'Grades'], ]; return ( <nav style={styles.nav}> {pages.map((page, index) => ( <Link key={page[0]} activeStyle={index === 0 ? Object.assign({}, styles.activeLink, { paddingLeft: 0 }) : styles.activeLink} style={index === 0 ? Object.assign({}, styles.link, { paddingLeft: 0 }) : styles.link } to={`/course/${course.id}/${page[0]}`} >{page[1]}</Link> ))} </nav> ); } } export default Nav;
examples/js/cell-edit/custom-cell-edit-table.js
powerhome/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-alert: 0 */ /* eslint guard-for-in: 0 */ /* eslint no-unused-vars: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; const currencies = [ 'USD', 'GBP', 'EUR' ]; const regions = [ 'North', 'South', 'East', 'West' ]; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: { amount: 2100 + i, currency: currencies[i % currencies.length] }, regions: regions.slice(0, (i % regions.length) + 1) }); } } addProducts(5); const cellEditProp = { mode: 'click' }; class NameEditor extends React.Component { constructor(props) { super(props); this.updateData = this.updateData.bind(this); this.state = { name: props.defaultValue, open: true }; } focus() { this.refs.inputRef.focus(); } updateData() { this.props.onUpdate(this.state.name); } close = () => { this.setState({ open: false }); this.props.onUpdate(this.props.defaultValue); } render() { const fadeIn = this.state.open ? 'in' : ''; const display = this.state.open ? 'block' : 'none'; return ( <div className={ `modal fade ${fadeIn}` } id='myModal' role='dialog' style={ { display } }> <div className='modal-dialog'> <div className='modal-content'> <div className='modal-body'> <input ref='inputRef' className={ ( this.props.editorClass || '') + ' form-control editor edit-text' } style={ { display: 'inline', width: '50%' } } type='text' value={ this.state.name } onChange={ e => { this.setState({ name: e.currentTarget.value }); } } /> </div> <div className='modal-footer'> <button type='button' className='btn btn-primary' onClick={ this.updateData }>Save</button> <button type='button' className='btn btn-default' onClick={ this.close }>Close</button> </div> </div> </div> </div> ); } } class PriceEditor extends React.Component { constructor(props) { super(props); this.updateData = this.updateData.bind(this); this.state = { amount: props.defaultValue.amount, currency: props.defaultValue.currency }; } focus() { this.refs.inputRef.focus(); } updateData() { this.props.onUpdate({ amount: this.state.amount, currency: this.state.currency }); } render() { return ( <span> <input ref='inputRef' className={ ( this.props.editorClass || '') + ' form-control editor edit-text' } style={ { display: 'inline', width: '50%' } } type='text' value={ this.state.amount } onKeyDown={ this.props.onKeyDown } onChange={ (ev) => { this.setState({ amount: parseInt(ev.currentTarget.value, 10) }); } } /> <select value={ this.state.currency } onKeyDown={ this.props.onKeyDown } onChange={ (ev) => { this.setState({ currency: ev.currentTarget.value }); } } > { currencies.map(currency => (<option key={ currency } value={ currency }>{ currency }</option>)) } </select> <button className='btn btn-info btn-xs textarea-save-btn' onClick={ this.updateData }> save </button> </span> ); } } class RegionsEditor extends React.Component { constructor(props) { super(props); this.updateData = this.updateData.bind(this); this.state = { regions: props.defaultValue }; this.onToggleRegion = this.onToggleRegion.bind(this); } focus() { } onToggleRegion(event) { const region = event.currentTarget.name; if (this.state.regions.indexOf(region) < 0) { this.setState({ regions: this.state.regions.concat([ region ]) }); } else { this.setState({ regions: this.state.regions.filter(r => r !== region) }); } } updateData() { this.props.onUpdate(this.state.regions); } render() { const regionCheckBoxes = regions.map(region => ( <span key={ `span-${region}` }> <input type='checkbox' key={ region } name={ region } checked={ this.state.regions.indexOf(region) > -1 } onKeyDown={ this.props.onKeyDown } onChange={ this.onToggleRegion } /> <label key={ `label-${region}` } htmlFor={ region }>{ region }</label> </span> )); return ( <span ref='inputRef'> { regionCheckBoxes } <button className='btn btn-info btn-xs textarea-save-btn' onClick={ this.updateData }> save </button> </span> ); } } function priceFormatter(cell, row) { return `<i class='glyphicon glyphicon-${cell.currency.toLowerCase()}'></i> ${cell.amount}`; } const regionsFormatter = (cell, row) => (<span>{ (cell || []).join(',') }</span>); /* The getElement function take two arguments, 1. onUpdate: if you want to apply the modified data, call this function 2. props: contain customEditorParameters, whole row data, defaultValue and attrs */ const createNameEditor = (onUpdate, props) => (<NameEditor onUpdate={ onUpdate } {...props}/>); const createPriceEditor = (onUpdate, props) => (<PriceEditor onUpdate={ onUpdate } {...props}/>); const createRegionsEditor = (onUpdate, props) => (<RegionsEditor onUpdate={ onUpdate } {...props}/>); export default class CustomCellEditTable extends React.Component { render() { return ( <BootstrapTable data={ products } cellEdit={ cellEditProp }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name' customEditor={ { getElement: createNameEditor } }> Product Name </TableHeaderColumn> <TableHeaderColumn dataField='price' dataFormat={ priceFormatter } customEditor={ { getElement: createPriceEditor, customEditorParameters: { currencies: currencies } } }> Product Price </TableHeaderColumn> <TableHeaderColumn dataField='regions' dataFormat={ regionsFormatter } customEditor={ { getElement: createRegionsEditor } }> Regions </TableHeaderColumn> </BootstrapTable> ); } }
src/javascript/components/Footer.js
Yanagiya/SOS_HAKATHON_TEMLATE
import React, { Component } from 'react'; const styles = { layout: { height: '100px' }, footerText: { textAlign: 'right', padding: '40px 0', fontSize: '10px' } }; export default class Footer extends Component { render() { return ( <div style={styles.layout}> <div style={styles.footerText}> Contribute to the <a href='https://github.com/knowbody/redux-react-router-example-app' target='_blank' style={{textDecoration: 'none'}}> project on GitHub</a>. </div> </div> ); } }
frontend/js/components/ecosystems/SurveyCreatorCandidates.js
wbprice/okcandidate-platform
'use strict'; import React, { Component } from 'react'; import Card from './../atoms/Card'; class SurveyCreatorCandidates extends Component { render() { return ( <Card> <pre>SurveyCreatorCandidates</pre> </Card> ); } } SurveyCreatorCandidates.propTypes = {}; export default SurveyCreatorCandidates;
app/javascript/mastodon/features/ui/components/block_modal.js
lindwurm/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { injectIntl, FormattedMessage } from 'react-intl'; import { makeGetAccount } from '../../../selectors'; import Button from '../../../components/button'; import { closeModal } from '../../../actions/modal'; import { blockAccount } from '../../../actions/accounts'; import { initReport } from '../../../actions/reports'; const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = state => ({ account: getAccount(state, state.getIn(['blocks', 'new', 'account_id'])), }); return mapStateToProps; }; const mapDispatchToProps = dispatch => { return { onConfirm(account) { dispatch(blockAccount(account.get('id'))); }, onBlockAndReport(account) { dispatch(blockAccount(account.get('id'))); dispatch(initReport(account)); }, onClose() { dispatch(closeModal()); }, }; }; export default @connect(makeMapStateToProps, mapDispatchToProps) @injectIntl class BlockModal extends React.PureComponent { static propTypes = { account: PropTypes.object.isRequired, onClose: PropTypes.func.isRequired, onBlockAndReport: PropTypes.func.isRequired, onConfirm: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; componentDidMount() { this.button.focus(); } handleClick = () => { this.props.onClose(); this.props.onConfirm(this.props.account); } handleSecondary = () => { this.props.onClose(); this.props.onBlockAndReport(this.props.account); } handleCancel = () => { this.props.onClose(); } setRef = (c) => { this.button = c; } render () { const { account } = this.props; return ( <div className='modal-root__modal block-modal'> <div className='block-modal__container'> <p> <FormattedMessage id='confirmations.block.message' defaultMessage='Are you sure you want to block {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} /> </p> </div> <div className='block-modal__action-bar'> <Button onClick={this.handleCancel} className='block-modal__cancel-button'> <FormattedMessage id='confirmation_modal.cancel' defaultMessage='Cancel' /> </Button> <Button onClick={this.handleSecondary} className='confirmation-modal__secondary-button'> <FormattedMessage id='confirmations.block.block_and_report' defaultMessage='Block & Report' /> </Button> <Button onClick={this.handleClick} ref={this.setRef}> <FormattedMessage id='confirmations.block.confirm' defaultMessage='Block' /> </Button> </div> </div> ); } }
src/renderer/react.js
yoo2001818/resumegen
import React from 'react'; import Helmet from 'react-helmet'; import { renderToStaticMarkup } from 'react-dom/server'; import serialize from 'serialize-javascript'; import App from '../client/component/app'; export default function renderReact(link, metadata, files, publicPath, assetsByChunkName, footer ) { return new Promise((resolve, reject) => { let tree = ( <App state={metadata} /> ); let result = renderToStaticMarkup(tree); let head = Helmet.rewind(); // OK, then wrap the data into HTML let assets = assetsByChunkName.main; if (!Array.isArray(assets)) assets = [assets]; let html = `<!doctype html> <html> <head> ${head.title.toString()} ${head.meta.toString()} ${head.link.toString()} ${ assets .filter(path => path.endsWith('.css')) .map(path => `<link rel="stylesheet" href="${publicPath + path}" />`) .join('') } </head> <body> <div id="root"> ${result} </div> <script> window.__INITIAL_STATE__ = ${serialize(metadata)} </script> ${ assets .filter(() => false) // Don't use JS - it is completely static. .filter(path => path.endsWith('.js')) .map(path => `<script src="${publicPath + path}"></script>`) .join('') } ${footer} </body> </html>`; resolve(html); }); }
src/containers/Home.js
matapang/virtualraceph2
import React, { Component } from 'react'; import { withRouter, Link } from 'react-router-dom'; import AppLayout from '../components/AppLayout'; import Dashboard from './Dashboard'; import { PageHeader, ListGroup, ListGroupItem, } from 'react-bootstrap'; import { invokeApig } from '../libs/awsLib'; import './Home.css'; class Home extends Component { constructor(props) { super(props); this.state = { isLoading: false, notes: [], }; } async componentDidMount() { if (this.props.userToken === null) { return; } this.setState({ isLoading: true }); try { const results = await this.notes(); this.setState({ notes: results }); } catch(e) { alert(e); } this.setState({ isLoading: false }); } notes() { return invokeApig({ path: '/posts' }, this.props.userToken); } renderNotesList(notes) { return [{}].concat(notes).map((note, i) => ( i !== 0 ? ( <ListGroupItem key={note.noteId} href={`/notes/${note.noteId}`} onClick={this.handleNoteClick} header={note.content.trim().split('\n')[0]}> { "Created: " + (new Date(note.createdAt)).toLocaleString() } </ListGroupItem> ) : ( <ListGroupItem key="new" href="/notes/new" onClick={this.handleNoteClick}> <h4><b>{'\uFF0B'}</b> Create a new note</h4> </ListGroupItem> ) )); } handleNoteClick = (event) => { event.preventDefault(); this.props.history.push(event.currentTarget.getAttribute('href')); } renderLander() { return ( <div className="lander"> <h1>Virtual Race PH</h1> <p>Run for a CAUSE</p> <div> <Link to="/login" className="btn btn-info btn-lg">Login</Link> <Link to="/signup" className="btn btn-success btn-lg">Signup</Link> </div> </div> ); } renderNotes() { return ( <div className="notes"> <PageHeader>Your Notes</PageHeader> <ListGroup> { ! this.state.isLoading && this.renderNotesList(this.state.notes) } </ListGroup> </div> ); } render() { return ( <div className="Home"> { this.props.userToken === null ? this.renderLander() : <Dashboard /> } </div> ); } } export default withRouter(Home);
src/svg-icons/action/http.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionHttp = (props) => ( <SvgIcon {...props}> <path d="M4.5 11h-2V9H1v6h1.5v-2.5h2V15H6V9H4.5v2zm2.5-.5h1.5V15H10v-4.5h1.5V9H7v1.5zm5.5 0H14V15h1.5v-4.5H17V9h-4.5v1.5zm9-1.5H18v6h1.5v-2h2c.8 0 1.5-.7 1.5-1.5v-1c0-.8-.7-1.5-1.5-1.5zm0 2.5h-2v-1h2v1z"/> </SvgIcon> ); ActionHttp = pure(ActionHttp); ActionHttp.displayName = 'ActionHttp'; ActionHttp.muiName = 'SvgIcon'; export default ActionHttp;
src/svg-icons/notification/power.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationPower = (props) => ( <SvgIcon {...props}> <path d="M16.01 7L16 3h-2v4h-4V3H8v4h-.01C7 6.99 6 7.99 6 8.99v5.49L9.5 18v3h5v-3l3.5-3.51v-5.5c0-1-1-2-1.99-1.99z"/> </SvgIcon> ); NotificationPower = pure(NotificationPower); NotificationPower.displayName = 'NotificationPower'; NotificationPower.muiName = 'SvgIcon'; export default NotificationPower;
node_modules/@material-ui/core/esm/LinearProgress/LinearProgress.js
pcclarke/civ-techs
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import warning from 'warning'; import withStyles from '../styles/withStyles'; import { lighten } from '../styles/colorManipulator'; var TRANSITION_DURATION = 4; // seconds export var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: { position: 'relative', overflow: 'hidden', height: 4 }, /* Styles applied to the root & bar2 element if `color="primary"`; bar2 if `variant-"buffer"`. */ colorPrimary: { backgroundColor: lighten(theme.palette.primary.light, 0.6) }, /* Styles applied to the root & bar2 elements if `color="secondary"`; bar2 if `variant="buffer"`. */ colorSecondary: { backgroundColor: lighten(theme.palette.secondary.light, 0.4) }, /* Styles applied to the root element if `variant="determinate"`. */ determinate: {}, /* Styles applied to the root element if `variant="indeterminate"`. */ indeterminate: {}, /* Styles applied to the root element if `variant="buffer"`. */ buffer: { backgroundColor: 'transparent' }, /* Styles applied to the root element if `variant="query"`. */ query: { transform: 'rotate(180deg)' }, /* Styles applied to the additional bar element if `variant="buffer"`. */ dashed: { position: 'absolute', marginTop: 0, height: '100%', width: '100%', animation: 'buffer 3s infinite linear', // Backward compatible logic between JSS v9 and v10. // To remove with the release of Material-UI v4 animationName: '$buffer' }, /* Styles applied to the additional bar element if `variant="buffer"` & `color="primary"`. */ dashedColorPrimary: { backgroundImage: "radial-gradient(".concat(lighten(theme.palette.primary.light, 0.6), " 0%, ").concat(lighten(theme.palette.primary.light, 0.6), " 16%, transparent 42%)"), backgroundSize: '10px 10px', backgroundPosition: '0px -23px' }, /* Styles applied to the additional bar element if `variant="buffer"` & `color="secondary"`. */ dashedColorSecondary: { backgroundImage: "radial-gradient(".concat(lighten(theme.palette.secondary.light, 0.4), " 0%, ").concat(lighten(theme.palette.secondary.light, 0.6), " 16%, transparent 42%)"), backgroundSize: '10px 10px', backgroundPosition: '0px -23px' }, /* Styles applied to the layered bar1 & bar2 elements. */ bar: { width: '100%', position: 'absolute', left: 0, bottom: 0, top: 0, transition: 'transform 0.2s linear', transformOrigin: 'left' }, /* Styles applied to the bar elements if `color="primary"`; bar2 if `variant` not "buffer". */ barColorPrimary: { backgroundColor: theme.palette.primary.main }, /* Styles applied to the bar elements if `color="secondary"`; bar2 if `variant` not "buffer". */ barColorSecondary: { backgroundColor: theme.palette.secondary.main }, /* Styles applied to the bar1 element if `variant="indeterminate or query"`. */ bar1Indeterminate: { width: 'auto', animation: 'mui-indeterminate1 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite', // Backward compatible logic between JSS v9 and v10. // To remove with the release of Material-UI v4 animationName: '$mui-indeterminate1' }, /* Styles applied to the bar1 element if `variant="determinate"`. */ bar1Determinate: { transition: "transform .".concat(TRANSITION_DURATION, "s linear") }, /* Styles applied to the bar1 element if `variant="buffer"`. */ bar1Buffer: { zIndex: 1, transition: "transform .".concat(TRANSITION_DURATION, "s linear") }, /* Styles applied to the bar2 element if `variant="indeterminate or query"`. */ bar2Indeterminate: { width: 'auto', animation: 'mui-indeterminate2 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) infinite', // Backward compatible logic between JSS v9 and v10. // To remove with the release of Material-UI v4 animationName: '$mui-indeterminate2', animationDelay: '1.15s' }, /* Styles applied to the bar2 element if `variant="buffer"`. */ bar2Buffer: { transition: "transform .".concat(TRANSITION_DURATION, "s linear") }, // Legends: // || represents the viewport // - represents a light background // x represents a dark background '@keyframes mui-indeterminate1': { // |-----|---x-||-----||-----| '0%': { left: '-35%', right: '100%' }, // |-----|-----||-----||xxxx-| '60%': { left: '100%', right: '-90%' }, '100%': { left: '100%', right: '-90%' } }, '@keyframes mui-indeterminate2': { // |xxxxx|xxxxx||-----||-----| '0%': { left: '-200%', right: '100%' }, // |-----|-----||-----||-x----| '60%': { left: '107%', right: '-8%' }, '100%': { left: '107%', right: '-8%' } }, '@keyframes buffer': { '0%': { opacity: 1, backgroundPosition: '0px -23px' }, '50%': { opacity: 0, backgroundPosition: '0px -23px' }, '100%': { opacity: 1, backgroundPosition: '-200px -23px' } } }; }; /** * ## ARIA * * If the progress bar is describing the loading progress of a particular region of a page, * you should use `aria-describedby` to point to the progress bar, and set the `aria-busy` * attribute to `true` on that region until it has finished loading. */ var LinearProgress = React.forwardRef(function LinearProgress(props, ref) { var classes = props.classes, classNameProp = props.className, _props$color = props.color, color = _props$color === void 0 ? 'primary' : _props$color, value = props.value, valueBuffer = props.valueBuffer, _props$variant = props.variant, variant = _props$variant === void 0 ? 'indeterminate' : _props$variant, other = _objectWithoutProperties(props, ["classes", "className", "color", "value", "valueBuffer", "variant"]); var className = clsx(classes.root, color === 'primary' && classes.colorPrimary, color === 'secondary' && classes.colorSecondary, variant === 'determinate' && classes.determinate, variant === 'indeterminate' && classes.indeterminate, variant === 'buffer' && classes.buffer, variant === 'query' && classes.query, classNameProp); var dashedClass = clsx(classes.dashed, color === 'primary' && classes.dashedColorPrimary, color === 'secondary' && classes.dashedColorSecondary); var bar1ClassName = clsx(classes.bar, color === 'primary' && classes.barColorPrimary, color === 'secondary' && classes.barColorSecondary, (variant === 'indeterminate' || variant === 'query') && classes.bar1Indeterminate, variant === 'determinate' && classes.bar1Determinate, variant === 'buffer' && classes.bar1Buffer); var bar2ClassName = clsx(classes.bar, (variant === 'indeterminate' || variant === 'query') && classes.bar2Indeterminate, variant === 'buffer' && [color === 'primary' && classes.colorPrimary, color === 'secondary' && classes.colorSecondary, classes.bar2Buffer], variant !== 'buffer' && [color === 'primary' && classes.barColorPrimary, color === 'secondary' && classes.barColorSecondary]); var rootProps = {}; var inlineStyles = { bar1: {}, bar2: {} }; if (variant === 'determinate' || variant === 'buffer') { if (value !== undefined) { rootProps['aria-valuenow'] = Math.round(value); inlineStyles.bar1.transform = "translateX(".concat(value - 100, "%)"); } else { process.env.NODE_ENV !== "production" ? warning(false, 'Material-UI: you need to provide a value property ' + 'when using the determinate or buffer variant of LinearProgress .') : void 0; } } if (variant === 'buffer') { if (valueBuffer !== undefined) { inlineStyles.bar2.transform = "translateX(".concat((valueBuffer || 0) - 100, "%)"); } else { process.env.NODE_ENV !== "production" ? warning(false, 'Material-UI: you need to provide a valueBuffer property ' + 'when using the buffer variant of LinearProgress.') : void 0; } } return React.createElement("div", _extends({ className: className, role: "progressbar" }, rootProps, { ref: ref }, other), variant === 'buffer' ? React.createElement("div", { className: dashedClass }) : null, React.createElement("div", { className: bar1ClassName, style: inlineStyles.bar1 }), variant === 'determinate' ? null : React.createElement("div", { className: bar2ClassName, style: inlineStyles.bar2 })); }); process.env.NODE_ENV !== "production" ? LinearProgress.propTypes = { /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. */ color: PropTypes.oneOf(['primary', 'secondary']), /** * The value of the progress indicator for the determinate and buffer variants. * Value between 0 and 100. */ value: PropTypes.number, /** * The value for the buffer variant. * Value between 0 and 100. */ valueBuffer: PropTypes.number, /** * The variant to use. * Use indeterminate or query when there is no progress value. */ variant: PropTypes.oneOf(['determinate', 'indeterminate', 'buffer', 'query']) } : void 0; export default withStyles(styles, { name: 'MuiLinearProgress' })(LinearProgress);
github-battle-es6/app/components/Nav.js
josedab/react-exercises
import React from 'react'; import {NavLink} from 'react-router-dom'; function Nav(){ return ( <ul className='nav'> <li> <NavLink exact activeClassName='active' to='/'> Home </NavLink> </li> <li> <NavLink activeClassName='active' to='/battle'> Battle </NavLink> </li> <li> <NavLink activeClassName='active' to='/popular'> Popular </NavLink> </li> </ul> ); } export default Nav;
examples/with-global-stylesheet/pages/index.js
nikvm/next.js
import React from 'react' import stylesheet from './style.scss' // or, if you work with plain css // import stylesheet from './style.css' export default () => <div> <style dangerouslySetInnerHTML={{ __html: stylesheet }} /> <p>ciao</p> </div>
modules/Link.js
stshort/react-router
import React from 'react' import invariant from 'invariant' import { routerShape } from './PropTypes' import { ContextSubscriber } from './ContextUtils' const { bool, object, string, func, oneOfType } = React.PropTypes function isLeftClickEvent(event) { return event.button === 0 } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey) } // TODO: De-duplicate against hasAnyProperties in createTransitionManager. function isEmptyObject(object) { for (const p in object) if (Object.prototype.hasOwnProperty.call(object, p)) return false return true } function resolveToLocation(to, router) { return typeof to === 'function' ? to(router.location) : to } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets the value of its * activeClassName prop. * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along location state and/or query string parameters * in the state/query props, respectively. * * <Link ... query={{ show: true }} state={{ the: 'state' }} /> */ const Link = React.createClass({ mixins: [ ContextSubscriber('router') ], contextTypes: { router: routerShape }, propTypes: { to: oneOfType([ string, object, func ]), query: object, hash: string, state: object, activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, onClick: func, target: string }, getDefaultProps() { return { onlyActiveOnIndex: false, style: {} } }, handleClick(event) { if (this.props.onClick) this.props.onClick(event) if (event.defaultPrevented) return const { router } = this.context invariant( router, '<Link>s rendered outside of a router context cannot navigate.' ) if (isModifiedEvent(event) || !isLeftClickEvent(event)) return // If target prop is set (e.g. to "_blank"), let browser handle link. /* istanbul ignore if: untestable with Karma */ if (this.props.target) return event.preventDefault() router.push(resolveToLocation(this.props.to, router)) }, render() { const { to, activeClassName, activeStyle, onlyActiveOnIndex, ...props } = this.props // Ignore if rendered outside the context of router to simplify unit testing. const { router } = this.context if (router) { // If user does not specify a `to` prop, return an empty anchor tag. if (!to) { return <a {...props} /> } const toLocation = resolveToLocation(to, router) props.href = router.createHref(toLocation) if (activeClassName || (activeStyle != null && !isEmptyObject(activeStyle))) { if (router.isActive(toLocation, onlyActiveOnIndex)) { if (activeClassName) { if (props.className) { props.className += ` ${activeClassName}` } else { props.className = activeClassName } } if (activeStyle) props.style = { ...props.style, ...activeStyle } } } } return <a {...props} onClick={this.handleClick} /> } }) export default Link
src/Routes.js
gramulos/EpsilonGroups
import React from 'react'; import { ReactRouter, Router, Route, Link } from 'react-router'; import cTemplate from './pages/client/Template'; import cProducts from './pages/client/Products'; import cProductDetails from './pages/client/ProductDetails'; import cServices from './pages/client/Services'; import c3DPrinter from './pages/client/3dPrinter'; import cContacts from './pages/client/ContactUs'; import cNotFound from './pages/client/404' const Routes = ( <Router> <Route path="/" component={cTemplate}> <Route path="products" component={cProducts} /> <Route path="software" component={cProducts} /> <Route path="software/:product" component={cProductDetails} /> <Route path="hardware/:product" component={c3DPrinter} /> <Route path="services" component={cServices} /> <Route path="contact_us" component={cContacts} /> <Route path="*" component={cNotFound} /> </Route> </Router> ); export default Routes;
src/svg-icons/maps/local-phone.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalPhone = (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> ); MapsLocalPhone = pure(MapsLocalPhone); MapsLocalPhone.displayName = 'MapsLocalPhone'; MapsLocalPhone.muiName = 'SvgIcon'; export default MapsLocalPhone;
lib/components/content/ListBlock.js
limscoder/react-present
import React from 'react'; import PropTypes from 'prop-types'; export default class ListBlock extends React.Component { static propTypes = { items: PropTypes.arrayOf(PropTypes.node), title: PropTypes.node }; render() { let items = this.props.items || []; items = items.concat(this.props.children || []); return ( <div className="rcp-ListBlock"> <h2 className="rcp-ListBlock--Title">{this.props.title}</h2> <ul className="rcp-ListBlock--List"> {items.map((item, idx) => <li key={idx}>{item}</li>)} </ul> </div> ); } }
client/src/components/App.js
alexandernanberg/luncha
import React from 'react' import { Provider } from 'mobx-react' import { BrowserRouter as Router, Route, Switch } from 'react-router-dom/es' import Helmet from 'react-helmet' import styled from 'styled-components' import Header from './Header' import Footer from './Footer' import routes from '../routes' import ScrollTop from './ScrollTop' import stores from '../stores' import withGlobalStyle from './hoc/withGlobalStyle' const Container = styled.div` display: flex; flex-direction: column; min-height: 100vh; ` const App = () => ( <Provider {...stores}> <Router> <Container> <Helmet titleTemplate="%s – Luncha" defaultTitle="Luncha – Hitta nya recept och inspirera ditt matlagande" /> <ScrollTop /> <Header /> <Switch> {routes.map(({ id, ...props }) => ( <Route key={id} {...props} /> ))} </Switch> <Footer /> </Container> </Router> </Provider> ) export default withGlobalStyle(App)
app/javascript/mastodon/features/picture_in_picture/components/header.js
gol-cha/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import IconButton from 'mastodon/components/icon_button'; import { Link } from 'react-router-dom'; import Avatar from 'mastodon/components/avatar'; import DisplayName from 'mastodon/components/display_name'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ close: { id: 'lightbox.close', defaultMessage: 'Close' }, }); const mapStateToProps = (state, { accountId }) => ({ account: state.getIn(['accounts', accountId]), }); export default @connect(mapStateToProps) @injectIntl class Header extends ImmutablePureComponent { static propTypes = { accountId: PropTypes.string.isRequired, statusId: PropTypes.string.isRequired, account: ImmutablePropTypes.map.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { account, statusId, onClose, intl } = this.props; return ( <div className='picture-in-picture__header'> <Link to={`/@${account.get('acct')}/${statusId}`} className='picture-in-picture__header__account'> <Avatar account={account} size={36} /> <DisplayName account={account} /> </Link> <IconButton icon='times' onClick={onClose} title={intl.formatMessage(messages.close)} /> </div> ); } }
src/lib/validation.js
terakilobyte/socketreact
/* Simple serial "one by one" sync/async promises based validation. */ import Promise from 'bluebird'; import React from 'react'; import validator from 'validator'; export class ValidationError extends Error { constructor(message: string, prop: string) { super(); this.message = message; this.prop = prop; } } export function focusInvalidField(component) { return (error) => { if (error instanceof ValidationError) { if (!error.prop) return; const node = React.findDOMNode(component); if (!node) return; const el = node.querySelector(`[name=${error.prop}]`); if (!el) return; el.focus(); return; } throw error; }; } export default class Validation { constructor(object: Object) { this._object = object; this._prop = null; this._validator = validator; this.promise = Promise.resolve(); } custom(callback: Function, {required} = {}) { const prop = this._prop; const value = this._object[prop]; const object = this._object; this.promise = this.promise.then(() => { if (required && !this._isEmptyString(value)) return; callback(value, prop, object); }); return this; } _isEmptyString(value) { return !this._validator.toString(value).trim(); } prop(prop: string) { this._prop = prop; return this; } required(getRequiredMessage?) { return this.custom((value, prop) => { const msg = getRequiredMessage ? getRequiredMessage(prop, value) : this.getRequiredMessage(prop, value); throw new ValidationError(msg, prop); }, {required: true}); } getRequiredMessage(prop, value) { return `Please fill out '${prop}' field.`; } email() { return this.custom((value, prop) => { if (this._validator.isEmail(value)) return; throw new ValidationError( this.getEmailMessage(prop, value), prop ); }); } getEmailMessage() { return `Email address is not valid.`; } simplePassword() { return this.custom((value, prop) => { const minLength = 5; if (value.length >= minLength) return; throw new ValidationError( this.getSimplePasswordMessage(minLength), prop ); }); } getSimplePasswordMessage(minLength) { return `Password must contain at least ${minLength} characters.`; } }
app/assets/javascripts/src/components/sessions/loginPage.js
talum/creamery
import React from 'react' import ReactCSSTransitionGroup from 'react-addons-css-transition-group' import { connect } from 'react-redux' import Form from '../sharedComponents/Form' import InputField from '../sharedComponents/InputField' import SubmitButton from '../sharedComponents/SubmitButton' import { debounce } from 'lodash' import { logInUser } from '../../actions/sessions' class LoginPage extends React.Component { constructor(props) { super(props) this.state = this.initialState() this.validateForm = debounce(Form.validateForm.bind(this), 200) this.registerField = Form.registerField.bind(this) this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) this.fields = [] } initialState() { return { credentials: { email: '', password: '' } } } componentDidUpdate() { this.validateForm() } handleChange(event) { const field = event.target.name const credentials = this.state.credentials credentials[field] = event.target.value this.setState({credentials: credentials}) } handleSubmit(event) { event.preventDefault() this.props.dispatch(logInUser(this.state.credentials)) // submit action } render() { return( <ReactCSSTransitionGroup transitionName="fade" transitionAppear={true} transitionAppearTimeout={500} transitionEnterTimeout={500} transitionLeaveTimeout={500}> <div> <h1 className="util--padding-ls">Login</h1> <div className="module">{ this.props.sessions.errors }</div> <form onSubmit={this.handleSubmit}> <div className="module"> <InputField name={"email"} value={this.state.credentials.email} placeholder={"email"} handleChange={this.handleChange} isRequired={true} validateForm={this.validateForm} registerField={this.registerField} /> </div> <div className="module"> <InputField name={"password"} inputType={"password"} value={this.state.credentials.password} placeholder={"password"} handleChange={this.handleChange} isRequired={true} validateForm={this.validateForm} registerField={this.registerField} /> </div> <div className="module"> <SubmitButton isDisabled={!this.state.isValid} handleSubmit={this.handleSubmit} /> </div> </form> </div> </ReactCSSTransitionGroup> ) } } const mapStateToProps = (state) => { return { sessions: state.sessions } } export default connect(mapStateToProps, null)(LoginPage)
src/client/home/index.react.js
laxplaer/este
import Component from '../components/component.react'; import DocumentTitle from 'react-document-title'; import React from 'react'; import {FormattedHTMLMessage} from 'react-intl'; import {Link} from 'react-router'; export default class HomeIndex extends Component { static propTypes = { msg: React.PropTypes.object.isRequired } render() { const {msg: {home: msg}} = this.props; return ( <DocumentTitle title={msg.title}> <div className="home-page"> <p> <FormattedHTMLMessage message={msg.infoHtml} />{' '} <Link to="todos">{msg.todos}</Link>. </p> </div> </DocumentTitle> ); } }
packages/core/admin/admin/src/pages/SettingsPage/pages/Webhooks/EditView/components/EventInput/index.js
wistityhq/strapi
import React from 'react'; import PropTypes from 'prop-types'; import { FieldLabel } from '@strapi/design-system/Field'; import { Stack } from '@strapi/design-system/Stack'; import { Typography } from '@strapi/design-system/Typography'; import { useFormikContext } from 'formik'; import { useIntl } from 'react-intl'; import styled from 'styled-components'; import EventRow from './EventRow'; import formatValue from './utils/formatValue'; const StyledTable = styled.table` td { height: ${52 / 16}rem; width: 10%; vertical-align: middle; text-align: center; } tbody tr:nth-child(odd) { background: ${({ theme }) => theme.colors.neutral100}; } tbody tr td:first-child { padding-left: ${({ theme }) => theme.spaces[7]}; } `; const displayedData = { headers: { default: [ 'Settings.webhooks.events.create', 'Settings.webhooks.events.update', 'app.utils.delete', ], draftAndPublish: [ 'Settings.webhooks.events.create', 'Settings.webhooks.events.update', 'app.utils.delete', 'app.utils.publish', 'app.utils.unpublish', ], }, events: { default: { entry: ['entry.create', 'entry.update', 'entry.delete'], media: ['media.create', 'media.update', 'media.delete'], }, draftAndPublish: { entry: ['entry.create', 'entry.update', 'entry.delete', 'entry.publish', 'entry.unpublish'], media: ['media.create', 'media.update', 'media.delete'], }, }, }; const EventInput = ({ isDraftAndPublish }) => { const headersName = isDraftAndPublish ? displayedData.headers.draftAndPublish : displayedData.headers.default; const events = isDraftAndPublish ? displayedData.events.draftAndPublish : displayedData.events.default; const { formatMessage } = useIntl(); const { values, handleChange: onChange } = useFormikContext(); const inputName = 'events'; const inputValue = values.events; const disabledEvents = []; const formattedValue = formatValue(inputValue); const handleChange = ({ target: { name, value } }) => { let set = new Set(inputValue); if (value) { set.add(name); } else { set.delete(name); } onChange({ target: { name: inputName, value: Array.from(set) } }); }; const handleChangeAll = ({ target: { name, value } }) => { let set = new Set(inputValue); if (value) { events[name].forEach(event => { if (!disabledEvents.includes(event)) { set.add(event); } }); } else { events[name].forEach(event => set.delete(event)); } onChange({ target: { name: inputName, value: Array.from(set) } }); }; return ( <Stack size={1}> <FieldLabel> {formatMessage({ id: 'Settings.webhooks.form.events', defaultMessage: 'Events', })} </FieldLabel> <StyledTable> <thead> <tr> <td /> {headersName.map(header => { if (header === 'app.utils.publish' || header === 'app.utils.unpublish') { return ( <td key={header} title={formatMessage({ id: 'Settings.webhooks.event.publish-tooltip', defaultMessage: 'This event only exists for contents with Draft/Publish system enabled', })} > <Typography variant="sigma" textColor="neutral600"> {formatMessage({ id: header, defaultMessage: header })} </Typography> </td> ); } return ( <td key={header}> <Typography variant="sigma" textColor="neutral600"> {formatMessage({ id: header, defaultMessage: header })} </Typography> </td> ); })} </tr> </thead> <tbody> {Object.keys(events).map(event => { return ( <EventRow disabledEvents={disabledEvents} key={event} name={event} events={events[event]} inputValue={formattedValue[event]} handleChange={handleChange} handleChangeAll={handleChangeAll} /> ); })} </tbody> </StyledTable> </Stack> ); }; EventInput.propTypes = { isDraftAndPublish: PropTypes.bool.isRequired, }; export default EventInput;
src/Survey/Complex/Default/Samples/Taxon.js
NERC-CEH/irecord-app
import React from 'react'; import PropTypes from 'prop-types'; import { observer } from 'mobx-react'; import AppHeader from 'Components/Header'; import TaxonSearch, { TaxonSearchFilters } from 'Components/TaxonSearch'; import Sample from 'sample'; import Occurrence from 'occurrence'; import surveyConfig from 'common/config/surveys/complex/default'; import { IonPage, NavContext } from '@ionic/react'; import AppMain from 'Components/Main'; import { success } from 'helpers/toast'; @observer class Controller extends React.Component { static propTypes = { match: PropTypes.object, history: PropTypes.object, appModel: PropTypes.object, savedSamples: PropTypes.array.isRequired, }; static contextType = NavContext; constructor(props) { super(props); const { id, smpId } = this.props.match.params; this.surveySample = this.props.savedSamples.find(({ cid }) => cid === id); const subSample = this.surveySample.samples.find( ({ cid }) => cid === smpId ); this.state = { subSample, }; } getNewSample = async taxon => surveyConfig.smp.create(Sample, Occurrence, taxon, this.surveySample); onSpeciesSelected = async (taxon, editBtnClicked) => { const { match, history } = this.props; const { subSample } = this.state; const isNew = !subSample; const occID = match.params.occId; if (isNew) { const newSubSample = await this.getNewSample(taxon); if (editBtnClicked) { const url = match.url.replace('/new', ''); history.replace(`${url}/${newSubSample.cid}`); return; } let name = taxon.scientific_name; if (taxon.found_in_name >= 0) { name = taxon.common_names[taxon.found_in_name]; } success(`${t('Added')} ${name}`, 500); return; } if (occID) { const occ = subSample.occurrences.find(({ cid }) => cid === occID); subSample.removeOldTaxonAttributes(occ, taxon); occ.attrs.taxon = taxon; } else { const [occ] = subSample.occurrences; subSample.removeOldTaxonAttributes(occ, taxon); occ.attrs.taxon = taxon; await occ.save(); } this.context.goBack(); }; render() { const { appModel } = this.props; const { subSample } = this.state; const isNew = !subSample; const searchNamesOnly = appModel.get('searchNamesOnly'); const selectedFilters = appModel.get('taxonGroupFilters'); return ( <IonPage> <AppHeader title={t('Species')} rightSlot={<TaxonSearchFilters appModel={appModel} />} /> <AppMain> <TaxonSearch onSpeciesSelected={this.onSpeciesSelected} showEditButton={isNew} informalGroups={selectedFilters} namesFilter={searchNamesOnly} resetOnSelect /> </AppMain> </IonPage> ); } } export default Controller;
examples/wms/wmspopup.js
boundlessgeo/sdk
import React from 'react'; import SdkPopup from '@boundlessgeo/sdk/components/map/popup'; /** * Show the WMS GetFeatureInfo feature in a popup. */ export default class WMSPopup extends SdkPopup { render() { const content = []; for (let i = 0, ii = this.props.features.length; i < ii; ++i) { const feature = this.props.features[i]; const keys = Object.keys(feature.properties); for (let j = 0, jj = keys.length; j < jj; ++j) { const key = `${i}-${keys[j]}`; content.push( <li key={key}> <span className='title'>{keys[j]}</span> - <span className='value'>{feature.properties[keys[j]]}</span> </li>); } } return this.renderPopup(( <div className='sdk-popup-content'> <ul> { content } </ul> </div> )); } }
dev/dispenseApp/pages/requestCode.js
Thr1ve/Dispense
import React from 'react' import RequestCodeForm from '../../components/atoms/requestCodeForm.js' import Mui from 'material-ui' import {r, DefaultMixin, QueryRequest} from 'react-rethinkdb' let { Paper } = Mui let requestCode = React.createClass({ mixins: [DefaultMixin], contextTypes: { router: React.PropTypes.func }, observe (props, state) { // FIX: This should be optional; if we already have all the products, we don't need to query the server for them // - can we return {} instead of a QueryRequest here or will that break things ? // - Yes we can, thanks to 'this.data.product &&' in line 45 // Turn our route into a number ( can't query with string ) let prodId = parseInt(this.context.router.getCurrentParams().productId, 10) // Get the product from the server return { product: new QueryRequest({ query: r.table('products').filter({productId: prodId}), initial: [] }) } }, render () { let title, isbn13 // SLOPPY ? // If we have the product, display it if (this.data.product && this.data.product._value.length > 0) { title = this.data.product._value[0].title isbn13 = this.data.product._value[0].isbn13 } else { // If we don't have the product, display empty space so we don't break things title = ' ' isbn13 = ' ' } return ( <div> <Paper zDepth={2} style={{width: '95%', marginRight: 'auto', marginLeft: 'auto'}}> <h2 className='mui-font-style-headline' style={{textAlign: 'center'}}>{title}</h2> <h4 style={{textAlign: 'center'}}>{isbn13}</h4> </Paper> <RequestCodeForm productId={this.context.router.getCurrentParams().productId} /> </div> ) } }) module.exports = requestCode
admin/client/App/components/Navigation/Secondary/index.js
helloworld3q3q/keystone
/** * The secondary navigation links to inidvidual lists of a section */ import React from 'react'; import { connect } from 'react-redux'; import { Container } from 'elemental'; import { FormattedMessage } from 'react-intl'; import { setActiveList, } from '../../../screens/List/actions/active'; import SecondaryNavItem from './NavItem'; var SecondaryNavigation = React.createClass({ displayName: 'SecondaryNavigation', propTypes: { currentListKey: React.PropTypes.string, lists: React.PropTypes.array.isRequired, }, getInitialState () { return {}; }, // Handle resizing and hide this nav on mobile (i.e. < 768px) screens componentDidMount () { this.handleResize(); window.addEventListener('resize', this.handleResize); }, componentWillUnmount () { window.removeEventListener('resize', this.handleResize); }, handleResize () { this.setState({ navIsVisible: this.props.lists && Object.keys(this.props.lists).length > 0 && window.innerWidth >= 768, }); }, // Render the navigation renderNavigation (lists) { const navigation = Object.keys(lists).map((key) => { const list = lists[key]; // Get the link and the classname const href = list.external ? list.path : `${Keystone.adminPath}/${list.path}`; const isActive = this.props.currentListKey && this.props.currentListKey === list.path; const className = isActive ? 'active' : null; const onClick = (evt) => { // If it's the currently active navigation item and we're not on the item view, // clear the query params on click if (isActive && !this.props.itemId) { evt.preventDefault(); this.props.dispatch( setActiveList(this.props.currentList, this.props.currentListKey) ); } }; return ( <SecondaryNavItem key={list.path} path={list.path} className={className} href={href} onClick={onClick} > <FormattedMessage id={list.label}/> </SecondaryNavItem> ); }); return ( <ul className="app-nav app-nav--secondary app-nav--left"> {navigation} </ul> ); }, render () { if (!this.state.navIsVisible) return null; return ( <nav className="secondary-navbar"> <Container clearfix> {this.renderNavigation(this.props.lists)} </Container> </nav> ); }, }); module.exports = connect((state) => { return { currentList: state.lists.currentList, }; })(SecondaryNavigation);
client/modules/core/components/.stories/newpost.js
hacksong2016/angel
import React from 'react'; import { storiesOf, action } from '@kadira/storybook'; import NewPost from '../newpost'; storiesOf('core.NewPost', module) .add('default view', () => { return ( <NewPost create={action('create post')} /> ); }) .add('with error', () => { const error = 'This is the error message'; return ( <NewPost error={error} create={action('create post')} /> ); });
react/features/welcome/components/LocalVideoTrackUnderlay.native.js
bgrozev/jitsi-meet
// @flow import React, { Component } from 'react'; import { View } from 'react-native'; import { VideoTrack } from '../../base/media'; import { TintedView } from '../../base/react'; import { connect } from '../../base/redux'; import { getLocalVideoTrack } from '../../base/tracks'; import styles from './styles'; /** * The type of the React {@code Component} props of * {@link LocalVideoTrackUnderlay}. */ type Props = { /** * The redux representation of the local participant's video track. */ _localVideoTrack: Object, /** * React Elements to display within the component. */ children: React$Node, /** * The style, if any, to apply to {@link LocalVideoTrackUnderlay} in * addition to its default style. */ style: Object }; /** * Implements a React {@code Component} which underlays the local video track, * if any, underneath its children. */ class LocalVideoTrackUnderlay extends Component<Props> { /** * Implements React's {@link Component#render()}. * * @inheritdoc * @override * @returns {ReactElement} */ render() { return ( <View style = { [ styles.localVideoTrackUnderlay, this.props.style ] }> <VideoTrack videoTrack = { this.props._localVideoTrack } /> <TintedView> { this.props.children } </TintedView> </View> ); } } /** * Maps (parts of) the redux state to the React {@code Component} props of * {@code LocalVideoTrackUnderlay}. * * @param {Object} state - The redux state. * @private * @returns {{ * _localVideoTrack: (Track|undefined) * }} */ function _mapStateToProps(state) { return { _localVideoTrack: getLocalVideoTrack(state['features/base/tracks']) }; } export default connect(_mapStateToProps)(LocalVideoTrackUnderlay);
src/react.js
rwillrich/redux
import React from 'react'; import createAll from './components/createAll'; export const { Provider, Connector, provide, connect } = createAll(React);
docs/app/Examples/collections/Table/Variations/TableExampleInvertedColors.js
vageeshb/Semantic-UI-React
import React from 'react' import { Table } from 'semantic-ui-react' const colors = [ 'red', 'orange', 'yellow', 'olive', 'green', 'teal', 'blue', 'violet', 'purple', 'pink', 'brown', 'grey', 'black', ] const TableExampleInvertedColors = () => ( <div> {colors.map(color => ( <Table color={color} key={color} inverted> <Table.Header> <Table.Row> <Table.HeaderCell>Food</Table.HeaderCell> <Table.HeaderCell>Calories</Table.HeaderCell> <Table.HeaderCell>Protein</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row> <Table.Cell>Apples</Table.Cell> <Table.Cell>200</Table.Cell> <Table.Cell>0g</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Orange</Table.Cell> <Table.Cell>310</Table.Cell> <Table.Cell>0g</Table.Cell> </Table.Row> </Table.Body> </Table> ))} </div> ) export default TableExampleInvertedColors
src/routes/UIElement/layer/index.js
zhangjingge/sse-antd-admin
import React from 'react' import { layer } from '../../../components' import { Table, Row, Col, Button, Card } from 'antd' let Enum = { default: 1, } const IcoPage = () => { const handleButtonClick = (key) => { if (key === Enum.default) { layer.open({ title: '默认弹层', content: <div style={{ height: 360 }}>弹层内容</div>, }) } } return (<div className="content-inner"> <Row gutter={32}> <Col lg={8} md={12}> <Card title="默认"> <Button type="primary" onClick={handleButtonClick.bind(null, Enum.default)}>打开一个Layer</Button> </Card> </Col> </Row> <h2 style={{ margin: '16px 0' }}>API</h2> <div style={{ margin: '16px 0' }}> <h2 style={{ margin: '4px 0' }}>layer.open(config)</h2> config对象与<a href="https://ant.design/components/modal-cn/#API" target="_blank">Modal</a>的参数基本一致,config属性如下。 注意:1.visible属性一般不需要设置;2.afterClose无效,layer.close()可代替;3.layer.open()返回一个唯一的layer Id </div> <Row> <Col lg={18} md={24}> <Table rowKey={(record, key) => key} pagination={false} bordered scroll={{ x: 800 }} columns={[ { title: '参数', dataIndex: 'props', }, { title: '说明', dataIndex: 'desciption', }, { title: '类型', dataIndex: 'type', }, { title: '默认值', dataIndex: 'default', }, ]} dataSource={[ { props: 'content', desciption: '内容', type: 'string|ReactNode', default: '无', }, { props: 'title', desciption: '标题', type: 'string|ReactNode', default: '标题', }, { props: 'confirmLoading', desciption: '确定按钮 loading ', type: 'boolean', default: '无', }, { props: 'closable', desciption: '是否显示右上角的关闭按钮', type: 'boolean', default: '无', }, { props: 'onOk', desciption: '点击确定回调', type: 'function(e)', default: '无', }, { props: 'onCancel', desciption: '点击遮罩层或右上角叉或取消按钮的回调', type: 'function(e)', default: '"无"', }, { props: 'width', desciption: '宽度', type: 'string|number', default: '520', }, { props: 'okText', desciption: '确认按钮文字', type: 'string', default: '无', }, { props: 'cancelText', desciption: '取消按钮文字', type: 'string', default: '无', }, { props: 'maskClosable', desciption: '点击蒙层是否允许关闭', type: 'boolean', default: 'true', }, { props: 'style', desciption: '可用于设置浮层的样式,调整浮层位置等', type: 'object', default: '-', }, { props: 'wrapClassName', desciption: '对话框外层容器的类名', type: 'string', default: '-', }, ]} /> </Col> </Row> <div style={{ margin: '16px 0' }}> <h2 style={{ margin: '4px 0' }}>layer.close(index)</h2> 当index有值时,关闭指定Id的layer;当index无值时,关闭最顶层layer </div> <div style={{ margin: '16px 0' }}> <h2 style={{ margin: '4px 0' }}>layer.closeAll()</h2> 关闭所有的layer </div> </div>) } export default IcoPage
8-css-inline/src/AddTodo.js
mariusz-malinowski/tutorial-react
import React, { Component } from 'react'; import {connect} from 'react-redux'; import {enterTodoName, addTodo} from './actions'; class AddTodo extends Component { onFormSubmit = (evt) => { evt.preventDefault(); this.props.dispatch(addTodo()); } render() { return ( <form onSubmit={this.onFormSubmit}> <input type="text" value={this.props.todoName} onChange={evt => this.props.dispatch(enterTodoName(evt.target.value))} /> </form> ); } }; export default connect(state => state)(AddTodo);
src/client/react/index.js
nloomans/rooster.hetmml.nl
/** * Copyright (C) 2018 Noah Loomans * * This file is part of rooster.hetmml.nl. * * rooster.hetmml.nl 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. * * rooster.hetmml.nl 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 rooster.hetmml.nl. If not, see <http://www.gnu.org/licenses/>. * */ import 'babel-polyfill'; import 'whatwg-fetch'; import React from 'react'; import ReactDOM from 'react-dom'; import { createStore, applyMiddleware, compose as reduxCompose } from 'redux'; import { connectRouter, routerMiddleware } from 'connected-react-router'; import thunk from 'redux-thunk'; import moment from 'moment'; import createHistory from 'history/createBrowserHistory'; import reducer from './store/reducers'; import App from './App'; import './index.scss'; // Set the locale for moment.js to dutch. This ensures that the correct week // number logic is used. moment.locale('nl'); const history = createHistory(); const compose = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || reduxCompose; const store = createStore( connectRouter(history)(reducer), // Redux devtools extension // https://github.com/zalmoxisus/redux-devtools-extension compose( applyMiddleware( routerMiddleware(history), thunk, ), ), ); ReactDOM.render( <App store={store} history={history} />, document.querySelector('#root'), ); // We only want to focus the input on page load. NOT on a in-javascript // redirect. This is because that is when people usually want to start typing. document.querySelector('#searchInput').focus();
cloudapp/src/app/WeatherData.js
jbrichau/PoolBuddy
import React from 'react'; import request from 'superagent'; import { TimeSeries } from 'pondjs'; import { Resizable, Charts, ChartContainer, ChartRow, YAxis, ValueAxis, LineChart, styler } from "react-timeseries-charts"; class WeatherData extends React.Component { constructor(props) { super(props); this.state = { data: new TimeSeries({ name: "weather", columns: [ "time", "tempc", "windkmh", "windkmh2mavg", "pressure", "humidity", ], points: [], }), }; } componentDidMount() { this.fetchData(); } fetchData() { request .post("/weatherdata") .set("Content-Type", "application/json") .send({}) .end((err, res) => { const timeseries = new TimeSeries({ name: "weather", columns: [ "time", "tempc", "windkmh", "windkmh2mavg", "windgustkmh10m", "pressure", "humidity", "dailyrainmm", ], points: res.body[2].map((d) => [ (d.timestamp = new Date(d.timestamp).getTime()), d.tempc, d.windkmh, d.windkmh2mavg, d.windgustkmh10m, d.pressure, d.humidity, d.dailyrainmm, ]), }); this.setState({ data: timeseries, tracker: null }); }); } handleTrackerChanged = (t) => { this.setState({ tracker: t }); }; renderChart(dataKey, label, color) { // Get the value at the current tracker position for the ValueAxis let value = "--"; let v = null; if (this.state.tracker) v = this.state.data.atTime(this.state.tracker).get(dataKey); else v = this.state.data.atLast().get(dataKey); if (v) value = parseInt(v, 10); else if (v==0) value = "0"; return ( <ChartRow height="100"> <YAxis id={dataKey} label={label} labelOffset={-5} min={this.state.data.min(dataKey)} max={this.state.data.max(dataKey)} type="linear" format=",.1f" /> <Charts> <LineChart axis={dataKey} series={this.state.data} columns={[dataKey]} style={styler([{ key: dataKey, color: color, strokeWidth: 4 }])} /> </Charts> <ValueAxis id={`${dataKey}_valueaxis`} visible={true} value={value} detail={label} width={80} min={0} max={35} /> </ChartRow> ); } render() { if (!this.state.data) return <h1> Data fetch error </h1>; else if (this.state.data.size() == 0) return <h1> Waiting for weather data... </h1>; else return ( <Resizable> <ChartContainer timeRange={this.state.data.timerange()} onTrackerChanged={this.handleTrackerChanged} trackerPosition={this.state.tracker} > {this.renderChart("tempc", "Temp °C", "steelblue")} {this.renderChart("pressure", "Pressure mbar", "#F68B24")} {this.renderChart("humidity", "Humidity %", "#ff47ff")} {this.renderChart("windkmh", "Wind kmh", "green")} {this.renderChart("windkmh2mavg", "Wind avg kmh", "green")} {this.renderChart("windgustkmh10m", "Wind gust kmh", "green")} {this.renderChart("dailyrainmm", "Rain mm", "steelblue")} </ChartContainer> </Resizable> ); } } export default WeatherData;
blueocean-material-icons/src/js/components/svg-icons/action/lock-outline.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionLockOutline = (props) => ( <SvgIcon {...props}> <path d="M12 17c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm6-9h-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-2zM8.9 6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1v2H8.9V6zM18 20H6V10h12v10z"/> </SvgIcon> ); ActionLockOutline.displayName = 'ActionLockOutline'; ActionLockOutline.muiName = 'SvgIcon'; export default ActionLockOutline;
src/index.js
dbaronov/weather-widget-react-noredux
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import axios from 'axios'; import Header from './components/header'; import NotificationBar from './components/notification_bar'; import SearchBar from './components/search_bar'; import SummaryTitle from './components/summary_title'; import SummaryToday from './components/summary_today'; import Forecast from './components/forecast'; class App extends Component { constructor(props) { super(props); this.state = { data: null, weKnow: null, forecastFor: 3, city: null, country: null, summary: null, temp: null, humidity: null, pressure: null, wind: null, daysForecast: [] } // Get data for default location 'London' to start with this.getLocationData('London', this.state.forecastFor); this.onAlter = this.onAlter.bind(this); } getLocationData(city, forecastFor) { this.serverRequest = axios .get("//api.apixu.com/v1/forecast.json?key=603b6f7fd7e34d1c869132709172302&q=" + city + '&days=' + forecastFor) .then( (result) => { this.setState({ data: result.data, weKnow: 'We know where you are!', city: result.data.location.name, country: result.data.location.country, summary: result.data.current.condition.text, temp: result.data.current.temp_c, humidity: result.data.current.humidity, pressure: result.data.current.pressure_mb, wind: result.data.current.wind_mph, daysForecast: result.data.forecast.forecastday }); }); } onAlter(forecastFor) { this.getLocationData(this.state.city, forecastFor); } render() { return ( <div className="container weather-widget"> <div className="row"> <Header/> <NotificationBar weknow={this.state.weKnow} /> </div> <div className="row"> <SearchBar city={this.state.city} forecastFor={this.state.forecastFor} country={this.state.country} onAlter={this.onAlter}/> </div> <div className="row"> <SummaryTitle /> </div> <div className="row"> <SummaryToday summary={this.state.summary} temp={this.state.temp} humidity={this.state.humidity} pressure={this.state.pressure} wind={this.state.wind} /> </div> <div className="row"> <div className="weather-widget__forecast"> <div className="weather-widget__forecast-header"> <ul className="weather-widget__forecast-headers col-lg-12"> <li className="weather-widget__forecast-headers__item col-lg-2">Date</li> <li className="weather-widget__forecast-headers__item col-lg-4">Summary</li> <li className="weather-widget__forecast-headers__item col-lg-2">Temp</li> <li className="weather-widget__forecast-headers__item col-lg-2">Humidity</li> <li className="weather-widget__forecast-headers__item col-lg-2">Wind</li> </ul> </div> <div className="weather-widget__forecast-stats"> <ul className="weather-widget__forecast-stats__items"> <Forecast days={this.state.daysForecast} /> </ul> </div> </div> </div> </div> ) } } ReactDOM.render(<App />, document.querySelector('.container'));
client/components/layout/index.js
ShannChiang/meteor-react-redux-base
import React from 'react'; import Nav from '../../containers/layout/nav'; import Footer from './footer'; export default (props) => ( <div className="landing-page"> <Nav /> {props.children} {/*<Footer />*/} </div> );
test/test_helper.js
martinpeck/yt-react-app
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
app/javascript/mastodon/features/blocks/index.js
tootsuite/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { debounce } from 'lodash'; import PropTypes from 'prop-types'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import AccountContainer from '../../containers/account_container'; import { fetchBlocks, expandBlocks } from '../../actions/blocks'; import ScrollableList from '../../components/scrollable_list'; const messages = defineMessages({ heading: { id: 'column.blocks', defaultMessage: 'Blocked users' }, }); const mapStateToProps = state => ({ accountIds: state.getIn(['user_lists', 'blocks', 'items']), hasMore: !!state.getIn(['user_lists', 'blocks', 'next']), isLoading: state.getIn(['user_lists', 'blocks', 'isLoading'], true), }); export default @connect(mapStateToProps) @injectIntl class Blocks extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, accountIds: ImmutablePropTypes.list, hasMore: PropTypes.bool, isLoading: PropTypes.bool, intl: PropTypes.object.isRequired, multiColumn: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchBlocks()); } handleLoadMore = debounce(() => { this.props.dispatch(expandBlocks()); }, 300, { leading: true }); render () { const { intl, accountIds, hasMore, multiColumn, isLoading } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = <FormattedMessage id='empty_column.blocks' defaultMessage="You haven't blocked any users yet." />; return ( <Column bindToDocument={!multiColumn} icon='ban' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <ScrollableList scrollKey='blocks' onLoadMore={this.handleLoadMore} hasMore={hasMore} isLoading={isLoading} emptyMessage={emptyMessage} bindToDocument={!multiColumn} > {accountIds.map(id => <AccountContainer key={id} id={id} />, )} </ScrollableList> </Column> ); } }
app/javascript/mastodon/features/standalone/public_timeline/index.js
anon5r/mastonon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../../ui/containers/status_list_container'; import { expandPublicTimeline } from '../../../actions/timelines'; import Column from '../../../components/column'; import ColumnHeader from '../../../components/column_header'; import { defineMessages, injectIntl } from 'react-intl'; import { connectPublicStream } from '../../../actions/streaming'; const messages = defineMessages({ title: { id: 'standalone.public_title', defaultMessage: 'A look inside...' }, }); @connect() @injectIntl export default class PublicTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleHeaderClick = () => { this.column.scrollTop(); } setRef = c => { this.column = c; } componentDidMount () { const { dispatch } = this.props; dispatch(expandPublicTimeline()); this.disconnect = dispatch(connectPublicStream()); } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } handleLoadMore = maxId => { this.props.dispatch(expandPublicTimeline({ maxId })); } render () { const { intl } = this.props; return ( <Column ref={this.setRef}> <ColumnHeader icon='globe' title={intl.formatMessage(messages.title)} onClick={this.handleHeaderClick} /> <StatusListContainer timelineId='public' onLoadMore={this.handleLoadMore} scrollKey='standalone_public_timeline' trackScroll={false} /> </Column> ); } }
packages/idyll-docs/pages/docs/components/npm.js
idyll-lang/idyll
import React from 'react'; import Link from 'next/link'; import markdown from 'markdown-in-js'; import Layout from '../../../components/layout'; const Content = () => markdown` # Installing Components from NPM Additional components can be installed via [npm](https://npmjs.com). ## Suggested Components - [Apparatus](https://github.com/idyll-lang/idyll-apparatus-component) - [Vega Lite](https://github.com/idyll-lang/idyll-vega-lite) ## Details Because Idyll is built on top of React, any React component can be used in Idyll. If you install a component using \`npm\`, Idyll will automatically be able to find it without any additional configuration. For example: ~~~ $ npm install some-react-component ~~~ This could then be used in your markup as ~~~ [SomeReactComponent /] ~~~ Internally, this is equivalent to \`require('some-react-component')\`. If you need to access a property of the imported module, you can do it like this: ~~~ [SomeReactComponent.nested.Property /] ~~~ This is equivalent to \`require('some-react-component').nested.Property\`. `; export default ({ url }) => ( <Layout url={url} title={'Idyll Documentation | NPM Components'}> <Content /> <p> Continue to{' '} <Link href="/docs/components/custom"> <a>custom components</a> </Link> . </p> </Layout> );
src/components/GlyphButton.js
gearz-lab/react-metaform
import React from 'react'; import Button from 'react-bootstrap/lib/Button.js'; import Glyphicon from 'react-bootstrap/lib/Glyphicon.js'; let GlyphButton = React.createClass({ propTypes: { bsStyle: React.PropTypes.string, bsSize: React.PropTypes.string, text: React.PropTypes.string, glyph: React.PropTypes.string.isRequired, onClick: React.PropTypes.func }, handleSave: function () { if (this.props.onClick) { this.props.onClick(); } }, render: function () { let text = this.props.text ? <span style={{marginLeft:6}}>{this.props.text}</span> : null; return <Button bsStyle={this.props.bsStyle} bsSize={this.props.bsSize} onClick={this.handleSave}> <Glyphicon glyph={this.props.glyph}/> {text} </Button>; } }); export default GlyphButton;
wordpuzzle/src/layout/reply-and-response.js
prabakaranrvp/CodeGame
import React from 'react'; import { DIFFICULTY_MAP } from '../constants.js' export default class ReplyAndResponse extends React.Component { render() { return this.props.won? this.renderWonMessage() : this.renderInputContainer(); } renderInputContainer() { let chances = this.props.chances - this.props.guessedWords.length; let chancesText = (<label htmlFor="txt-guess"> You have <strong>{chances}</strong> chances left </label>); if(chances === 0) chancesText = (<label>You have used all your chances</label>); return ( <div className="game__input-container"> {chancesText} {this.renderInput(chances)} {this.renderError()} </div> ); } renderInput(chances) { let maxLength = DIFFICULTY_MAP[this.props.difficulty]; let animateIconClass = ''; if(this.props.animateAddIcon){ animateIconClass = 'animate-add'; setTimeout(() => { this.props.updateSingleState('animateAddIcon', false) }, 1000); } if(chances > 0) { return ( <div className="reply-container"> <button className="btn-toggle-panel" onClick={(e) => this.props.updateSingleState('togglePanel', !this.props.togglePanel)}> A </button> <input id="txt-guess" type="text" autoComplete="off" autoFocus={true} maxLength={maxLength} placeholder={`Guess ${maxLength} letter word`} onKeyUp={(e) => this.checkForAddition(e)} /> <button className={`btn-add ${this.props.animateInputClass + ' ' + animateIconClass}`} onClick={() => this.props.addGuess()}> <div></div> </button> </div> ); } else if (this.props.coins >= 5 && !this.props.showResult) { return this.renderAddChances(); } else { return this.renderResult(); } } renderAddChances() { return ( <div className="add-chances-container"> <span className="add-chance" onClick={(e) => this.props.addChance()}>Add 5 more chances for 5 coins </span> or <span className="show-answer" onClick={(e) => this.props.updateSingleState('showResult', true)}>Show answer?</span> </div> ); } renderError(){ return (this.props.errorMsg.length) ? (<span className="animated fadeInDown fast" dangerouslySetInnerHTML={{__html: this.props.errorMsg}} ></span>) : (<span className="element-inline-middle soft-hide">No Errors</span>); } renderWonMessage() { return ( <div className="won-message"> <span className="element-inline-middle">WOW! You guessed is right!!! It is&nbsp;</span> <a className="element-inline-middle link animated flash" href={`https://www.thefreedictionary.com/${this.props.word}`} target="_blank" rel="noopener noreferrer" > {this.props.word.toUpperCase()} </a> <div className="link" onClick={(e) => this.props.reloadGame()}>Play again</div> </div> ) } renderResult() { return ( <div className="result-container"> <span className="result">The word is </span> <a className="result link" href={`https://www.thefreedictionary.com/${this.props.word}`} target="_blank"> {this.props.word.toUpperCase()} </a> <div className="link" onClick={(e) => this.props.reloadGame()}>Retry again</div> </div> ) } checkForAddition(e){ if(e.keyCode === 13) this.props.addGuess(); } }
6.webpack/message/index.js
zhufengnodejs/201608node
require('bootstrap/dist/css/bootstrap.css'); import MessageBox from './components/MessageBox.js'; import React from 'react'; import ReactDOM from 'react-dom'; //此DB模块是用来对消息进行查询 添加 和删除的 //数据存储手段是多样化的,有可能 是localStorage http接口 import http from './http.js'; //db.list;列出所有的消息 //db.add;添加一个消息,返回最新的消息数组 //db.remove;删除一个消息,返回最新的消息数组 ReactDOM.render(<MessageBox model={http}/>,document.getElementById('app'));
app/containers/SwaggerPage/index.js
interra/data-generate
/* * SwaggerPage * * List all the features */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Helmet } from 'react-helmet'; import { FormattedMessage } from 'react-intl'; import { createStructuredSelector } from 'reselect'; import { compose } from 'redux'; import injectSaga from 'utils/injectSaga'; import injectReducer from 'utils/injectReducer'; import { makeSelectSwagger, makeSelectSwaggerLoading, makeSelectSwaggerError } from './selectors'; import reducer from './reducer'; import saga from './saga'; import { actionLoadSwagger } from './actions'; import SwaggerUI from './Swagger'; import './index.css'; import PageContainer from 'components/PageContainer'; import Breadcrumb from 'components/Breadcrumb'; import H1 from 'components/H1'; export class SwaggerPage extends React.Component { // eslint-disable-line react/prefer-stateless-function componentWillMount() { const { swagger, error, loading, loadSwagger } = this.props; if (swagger === false && error === false && loading === false) { loadSwagger(); } } render() { const { swagger, error, loading } = this.props; const swaggerProps = { swagger, loading, error, } const breadcrumbs = [{ title: 'Home', loc: '/', icon: 'home' },{ title: 'API', loc: '/api' }]; return ( <PageContainer> <Helmet> <title>API</title> <meta name="description" content="API" /> </Helmet> <Breadcrumb breadcrumbs={breadcrumbs} /> <p>The following is a <a href="http://swagger.io">swagger</a> rendered defintion of the Interra API.</p> <SwaggerUI {...swaggerProps} /> </PageContainer> ); } } SwaggerPage.propTypes = { dispatch: PropTypes.func, swagger: PropTypes.oneOfType([ PropTypes.object, PropTypes.bool, ]), loading: PropTypes.bool, error: PropTypes.oneOfType([ PropTypes.object, PropTypes.bool, ]), // Dispatch. loadSwagger: PropTypes.func, }; const mapStateToProps = createStructuredSelector({ swagger: makeSelectSwagger(), loading: makeSelectSwaggerLoading(), error: makeSelectSwaggerError(), }); function mapDispatchToProps(dispatch) { return { loadSwagger: () => dispatch(actionLoadSwagger()), }; } const withConnect = connect(mapStateToProps, mapDispatchToProps); const withReducer = injectReducer({ key: 'api', reducer }); const withSaga = injectSaga({ key: 'api', saga }); export default compose( withReducer, withSaga, withConnect, )(SwaggerPage);
ui/src/components/IconButton/IconButton.js
LearningLocker/learninglocker
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { compose, setPropTypes, defaultProps } from 'recompose'; import styled from 'styled-components'; const Button = styled.button` width: 33px; margin: 0 1px; `; const enhanceIconButton = compose( setPropTypes({ title: PropTypes.string.isRequired, icon: PropTypes.string.isRequired, onClick: PropTypes.func.isRequired, disabled: PropTypes.bool, }), defaultProps({ disabled: false, }), ); const renderIconButton = ({ title, onClick, disabled, icon }) => ( <Button className={classNames('btn btn-sm btn-inverse')} title={title} onClick={onClick} disabled={disabled} > <span><i className={icon} /></span> </Button> ); export default enhanceIconButton(renderIconButton);
examples/real-world/containers/Root.js
af/redux
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { Router, Route } from 'react-router'; import configureStore from '../store/configureStore'; import App from './App'; import UserPage from './UserPage'; import RepoPage from './RepoPage'; const store = configureStore(); export default class Root extends Component { render() { return ( <div> <Provider store={store}> {() => <Router history={this.props.history}> <Route path='/' component={App}> <Route path='/:login/:name' component={RepoPage} /> <Route path='/:login' component={UserPage} /> </Route> </Router> } </Provider> </div> ); } }
app/containers/BrowseHeader/index.js
ReelTalkers/reeltalk-web
/** * * BrowseHeader * */ import React from 'react' import Relay from 'react-relay' import UniversalSearch from 'containers/UniversalSearch' import Header from 'components/Header' import Logo from 'components/Logo' import styles from './styles.css' function BrowseHeader(props) { return ( <div className={styles.browseHeader}> <Header> <Logo className={styles.logo} /> <UniversalSearch viewer={props.viewer} /> <div className={styles.userDropdown}>gziegan</div> </Header> </div> ) } export default Relay.createContainer(BrowseHeader, { fragments: { viewer: () => Relay.QL` fragment on Query { ${UniversalSearch.getFragment('viewer')} } ` } })
packages/wix-style-react/src/ContactItemBuilder/docs/index.js
wix/wix-style-react
import React from 'react'; import { storiesOf } from '@storybook/react'; import Markdown from 'wix-storybook-utils/Markdown'; import TabbedView from 'wix-storybook-utils/TabbedView'; import CodeExample from 'wix-storybook-utils/CodeExample'; import Readme from './README.md'; import Example from './Example'; import ExampleRaw from '!raw-loader!./Example'; import { Category } from '../../../stories/storiesHierarchy'; storiesOf(`${Category.DEPRECATED}`, module).add('ContactItemBuilder', () => ( <TabbedView tabs={['Usage']}> <div> <Markdown source={Readme} /> <CodeExample title="Standard" code={ExampleRaw}> <Example /> </CodeExample> <div style={{ paddingTop: '230px' }} /> </div> </TabbedView> ));
src/routes/main/landing/index.js
labzero/lunch
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import LayoutContainer from '../../../components/Layout/LayoutContainer'; import renderIfLoggedOut from '../../helpers/renderIfLoggedOut'; import Landing from './Landing'; export default (context) => { const state = context.store.getState(); return renderIfLoggedOut(state, () => ({ chunks: ['landing'], component: ( <LayoutContainer path={context.pathname}> <Landing /> </LayoutContainer> ), fullTitle: 'Lunch – Team voting for nearby restaurants', })); };
app/src/Menu.js
struz/smash-move-viewer
import React, { Component } from 'react'; import ReactGA from 'react-ga'; ReactGA.initialize('UA-107697636-1'); class Menu extends Component { constructor(props) { super(props); this.state = { moveViewerLink: this.props.moveViewerLink }; this.handleChange = this.handleChange.bind(this); } componentWillReceiveProps(nextProps) { if (nextProps.moveViewerLink !== this.state.moveViewerLink) { this.setState(function(prevState, props) { prevState.moveViewerLink = nextProps.moveViewerLink; return prevState; }); } } handleChange(e) { var url = e.target.value; if (!url) return; if (url.startsWith("#")) { window.location.hash = url; } else if (url.includes("twitter.com")) { /* Track twitter clicks */ ReactGA.outboundLink({ label: 'Twitter' }, function () { // Out of site links, open in another tab window.opener = null; window.open(url, '_blank'); }); } else { // Out of site links, open in another tab window.opener = null; window.open(url, '_blank'); } } render() { const moveViewerLink = this.state.moveViewerLink; // Dropdown menu (for mobile) default highlighted option var optionValue = ''; if (window.location.hash.startsWith('#/help')) optionValue = '#/help'; else if (window.location.hash.startsWith('#/about')) optionValue = '#/about'; else optionValue = moveViewerLink; // TODO: make sure analytics are collected around these page views return ( <div className="menus-container"> <div className="small-menu-container"> <select onChange={this.handleChange} className="Dropdown Main-dropdown" title="Navigate between pages" defaultValue={optionValue}> <option value={moveViewerLink}>Move&nbsp;Viewer</option> <option value="#/help">Help</option> <option value="#/about">About</option> <option value="https://twitter.com/StruzSmash">&#64;StruzSmash</option> </select> </div> <div className="large-menu-container"> <a className="menu" href={moveViewerLink}>Move&nbsp;Viewer</a> <span className="menu-spacer">&#124;</span> <a className="menu" href="#/help">Help</a> <span className="menu-spacer">&#124;</span> <a className="menu" href="#/about">About</a> <span className="menu-spacer">&#124;</span> <ReactGA.OutboundLink className="menu" eventLabel="Twitter" to="https://twitter.com/StruzSmash" target="_blank" rel="noopener noreferrer"> &#64;StruzSmash </ReactGA.OutboundLink> </div> </div> ); } } export default Menu;
styleguide/screens/Patterns/Markdown/Markdown.js
NGMarmaduke/bloom
import React from 'react'; import cx from 'classnames'; import dedent from 'dedent'; import Markdown from '../../../../components/Markdown/Markdown'; import Specimen from '../../../components/Specimen/Specimen'; import { H, T, C } from '../../../components/Scaffold/Scaffold'; import css from './Markdown.css'; import m from '../../../../globals/modifiers.css'; import markdown from './example.md'; const MarkdownDocumentation = () => ( <div> <H level={ 1 }>Markdown</H> <T elm="p" className={ cx(m.mtr, m.largeI, m.demi) }> At Appear Here, we use markdown to markup content for use across our applications. </T> <T elm="p" className={ m.mtLgIi }> To enable us to do this, we have created a <C>Markdown</C> component which provides basic styling of markdown content. </T> <Specimen classNames={ { root: m.mtr, specimenContainer: m.par, } } code={ dedent` <Markdown> # An exhibit of Markdown ... </Markdown> ` } > <Markdown>{ markdown }</Markdown> </Specimen> <T elm="p" className={ m.mtLgIi }> You can add to or make changes to the markdown styles using the <C>className</C> prop. To do this, the class should act as a root selector, and style the any HTML elements you wish using the element selector. </T> <Specimen classNames={ { root: m.mtr, specimenContainer: m.par, } } code={ dedent` // styles.css .markdownExtended h1 { color: var(--color-gold); } // Component.js import Markdown from './components/Markdown'; import css from './styles.css'; <Markdown className={ css.markdownExtended }> # An exhibit of Markdown ... </Markdown> ` } > <Markdown className={ css.markdownExtended }>{ markdown }</Markdown> </Specimen> <T elm="p" className={ m.mtLgIi }> If you wish to write your own styles from scratch, set overrideClassname to true. </T> <Specimen classNames={ { root: m.mtr, specimenContainer: m.par, } } code={ dedent` // styles.css .markdownOverride * { font-family: georgia, serif; } .markdownOverride * + * { margin-top: var(--size-regular); } .markdownOverride h1 { text-decoration: underline; } .markdownOverride p { color: var(--color-grey); } // Component.js import Markdown from './components/Markdown'; import css from './styles.css'; <Markdown className={ css.markdownOverride } overrideClassname> # An exhibit of Markdown ... </Markdown> ` } > <Markdown className={ css.markdownOverride } overrideClassname> { markdown } </Markdown> </Specimen> </div> ); export default MarkdownDocumentation;
examples/star-wars/js/app.js
gabelevi/relay
/** * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import React from 'react'; import ReactDOM from 'react-dom'; import Relay from 'react-relay'; import StarWarsApp from './components/StarWarsApp'; import StarWarsAppHomeRoute from './routes/StarWarsAppHomeRoute'; ReactDOM.render( <Relay.RootContainer Component={StarWarsApp} route={new StarWarsAppHomeRoute({ factionNames: ['empire', 'rebels'], })} />, document.getElementById('root') );
src/App.js
anthonydelgado/codehero-react
import React from 'react'; import './App.css'; import firebase from 'firebase' import { connect } from 'react-firebase' import AceEditor from 'react-ace'; import 'brace/mode/javascript'; import 'brace/theme/ambiance'; import firebase_config_url from './config'; firebase.initializeApp({ databaseURL: firebase_config_url }); class Counter extends React.Component { constructor(props) { super(props); this.state = { numBackspaces: 0, wordsPerMin: 0, numTypedChars: 0, wordCount: 0, timer: 0 }; this.handleChange = this.handleChange.bind(this); } componentDidMount() { setTimeout(this.setRoom(), 7000); this.setTimer(); this.interval_timer = ''; } componentWillUnmount() { clearInterval(this.interval_timer); } // start the timer setTimer() { var that = this; var timer = 0; this.interval_timer = setInterval(function(){ timer++; console.log('timer: ', timer); var wordCount = (that.state.numTypedChars / 5); var wpm = Math.round(wordCount / (timer / 60)); that.setState({wordsPerMin: wpm}); console.log('this.state.wordsPerMin: ', that.state.wordsPerMin); }, 1000); } // add a new room to firebase if one does not currently exist setRoom() { if (this.props.match.params.room) { var mainRef = firebase.database().ref(); var newRef = mainRef.child(this.props.match.params.room); // only set the child ref to blank if it is a new room without any text in it if (newRef.child(this.props.match.params.room) === '') { newRef.set(''); } } } handleChange(event) { console.log(event.keyCode); var keycode = event.keyCode; var valid = (keycode > 47 && keycode < 58) || // number keys keycode === 32 || keycode === 13 || // spacebar & return key(s) (keycode > 64 && keycode < 91) || // letter keys (keycode > 95 && keycode < 112) || // numpad keys // (keycode > 185 && keycode < 193) || // ;=,-./` (in order) (keycode > 218 && keycode < 223); // [\]' (in order) if (valid) { this.setState({numTypedChars: this.state.numTypedChars + 1}); console.log('this.numTypedChars : ', this.state.numTypedChars); } if (event.keyCode === 8) { this.setState({numBackspaces: this.state.numBackspaces + 1}); } console.log('this.numBackspaces: ', this.state.numBackspaces); } render() { return ( <div onKeyUp={this.handleChange}> <AceEditor mode="javascript" theme="ambiance" onChange={this.props.setValue} name="hackerid" height='100vw' width='100vw' value={this.props.value} editorProps={{$blockScrolling: true}} /> </div> ) } } export default connect((props, ref) => ({ value: props.match.params.room, setValue: value => ref(props.match.params.room).set(value) }))(Counter)
src/js/components/icons/base/DocumentVideo.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}-document-video`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'document-video'); 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="M4.99787498,6.99999999 L4.99787498,0.999999992 L19.4999998,0.999999992 L22.9999998,4.50000005 L22.9999998,23 L4,23 M18,1 L18,6 L23,6 M3,10 L12,10 L12,19 L3,19 L3,10 Z M12,13 L17,10.5 L17,18.5 L12,16 L12,13 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'DocumentVideo'; 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/Icon.js
joshforisha/fred-talks
import PropTypes from 'prop-types'; import React from 'react'; import feather from 'feather-icons'; import styled from 'styled-components'; const Icon_ = styled.span` display: inline-block; height: 1.5em; line-height: 1; width: 1.5em; > svg { height: 1.5em; padding: 0.25rem; width: 1.5em; } `; export default function Icon(props) { if (!feather.icons.hasOwnProperty(props.name)) return null; return ( <Icon_ className={props.className} inline={props.inline} dangerouslySetInnerHTML={{ __html: feather.icons[props.name].toSvg() }} /> ); } Icon.defaultProps = { inline: false }; Icon.propTypes = { className: PropTypes.string, inline: PropTypes.bool, name: PropTypes.string.isRequired };
src/icons/AndroidLock.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class AndroidLock extends React.Component { render() { if(this.props.bare) { return <g> <g> <g> <path d="M376,186h-20v-40c0-55-45-100-100-100S156,91,156,146v40h-20c-22.002,0-40,17.998-40,40v200c0,22.002,17.998,40,40,40h240 c22.002,0,40-17.998,40-40V226C416,203.998,398.002,186,376,186z M256,368c-22.002,0-40-17.998-40-40s17.998-40,40-40 s40,17.998,40,40S278.002,368,256,368z M318.002,186H193.998v-40c0-34.004,28.003-62.002,62.002-62.002 c34.004,0,62.002,27.998,62.002,62.002V186z"></path> </g> </g> </g>; } return <IconBase> <g> <g> <path d="M376,186h-20v-40c0-55-45-100-100-100S156,91,156,146v40h-20c-22.002,0-40,17.998-40,40v200c0,22.002,17.998,40,40,40h240 c22.002,0,40-17.998,40-40V226C416,203.998,398.002,186,376,186z M256,368c-22.002,0-40-17.998-40-40s17.998-40,40-40 s40,17.998,40,40S278.002,368,256,368z M318.002,186H193.998v-40c0-34.004,28.003-62.002,62.002-62.002 c34.004,0,62.002,27.998,62.002,62.002V186z"></path> </g> </g> </IconBase>; } };AndroidLock.defaultProps = {bare: false}
tests/flow/react/createElementRequiredProp_string.js
Pajn/prettier
// @flow import React from 'react'; class Bar extends React.Component { props: { test: number, }; render() { return ( <div> {this.props.test} </div> ) } } class Foo extends React.Component { render() { const Cmp = Math.random() < 0.5 ? 'div' : Bar; return (<Cmp/>); } }