path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
examples/forms-material-ui/src/components/forms-update-overlay/Hook.js | lore/lore-forms | import React from 'react';
import createReactClass from 'create-react-class';
import PropTypes from 'prop-types';
export default createReactClass({
displayName: 'Hook',
propTypes: {
model: PropTypes.object.isRequired
},
render: function() {
const { model } = this.props;
return (
<div key={model.id}>
{lore.forms.tweet.update(model, {
blueprint: 'overlay'
})}
</div>
);
}
});
|
cross-player.js | mathbruyen/u-tic-tac-toe | /* jshint node: true, esnext: true */
import React from 'react';
export default class CrossPlayer extends React.Component {
render() {
return React.DOM.div(null, 'X');
}
}
|
app/containers/NotFoundPage/index.js | BrewPi/brewpi-ui | /**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
export default class NotFound extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
src/js/components/IndexDoc.js | grommet/grommet-index-docs | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import DocsArticle from './DocsArticle';
import Example from './Example';
import Index from 'grommet-index/components/Index';
import Query from 'grommet-index/utils/Query';
import attributes from '../attributes';
import result from '../result';
Index.displayName = 'Index';
let annotatedAttributes = attributes.map(attribute => {
let attr = { ...attribute };
if (attr.name === 'state') {
attr.secondary = true;
} else if (attr.name === 'modified') {
attr.hidden = true;
}
return attr;
});
export default class IndexDoc extends Component {
constructor (props) {
super(props);
this._onQuery = this._onQuery.bind(this);
this._onFilter = this._onFilter.bind(this);
this._onSort = this._onSort.bind(this);
this.state = { query: new Query(''), filter: {}, sort: 'name:asc' };
}
_onQuery (query) {
this.setState({ query: query });
}
_onFilter (filter) {
this.setState({ filter: filter });
}
_onSort (sort) {
this.setState({ sort: sort });
}
render () {
let example = (
<Index label="Items" attributes={annotatedAttributes} result={result}
query={this.state.query} onQuery={this._onQuery}
filter={this.state.filter} onFilter={this._onFilter}
sort={this.state.sort} onSort={this._onSort}
fixed={false} />
);
return (
<DocsArticle title="Index" colorIndex="neutral-3">
<p>Combines index header and one of the result formats.</p>
<section>
<h2>Options</h2>
TBD
</section>
<section>
<h2>Example</h2>
<Example code={example} />
</section>
</DocsArticle>
);
}
}
|
webpack/components/TypeAhead/pf3Search/TypeAheadItems.js | snagoor/katello | import React from 'react';
import { Dropdown, MenuItem } from 'patternfly-react';
import { commonItemPropTypes } from '../helpers/commonPropTypes';
const TypeAheadItems = ({
items, activeItems, getItemProps, highlightedIndex,
}) => (
<Dropdown.Menu className="typeahead-dropdown">
{items.map(({ text, type, disabled = false }, index) => {
if (type === 'header') {
return (
<MenuItem key={text} header>
{text}
</MenuItem>
);
}
if (type === 'divider') {
// eslint-disable-next-line react/no-array-index-key
return <MenuItem key={`divider-${index}`} divider />;
}
if (disabled) {
return (
<MenuItem key={text} disabled>
{text}
</MenuItem>
);
}
const itemProps = getItemProps({
index: activeItems.indexOf(text),
item: text,
active: activeItems[highlightedIndex] === text,
onClick: (e) => {
// At this point the event.defaultPrevented
// is already set to true by react-bootstrap
// MenuItem. We need to set it back to false
// So downshift will execute it's own handler
e.defaultPrevented = false;
},
});
return (
<MenuItem {...itemProps} key={text}>
{text}
</MenuItem>
);
})}
</Dropdown.Menu>
);
TypeAheadItems.propTypes = commonItemPropTypes;
export default TypeAheadItems;
|
node_modules/react-router-dom/node_modules/react-router/es/Switch.js | 937aaron/reduxblog | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import React from 'react';
import PropTypes from 'prop-types';
import warning from 'warning';
import invariant from 'invariant';
import matchPath from './matchPath';
/**
* The public API for rendering the first <Route> that matches.
*/
var Switch = function (_React$Component) {
_inherits(Switch, _React$Component);
function Switch() {
_classCallCheck(this, Switch);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Switch.prototype.componentWillMount = function componentWillMount() {
invariant(this.context.router, 'You should not use <Switch> outside a <Router>');
};
Switch.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
warning(!(nextProps.location && !this.props.location), '<Switch> elements should not change from uncontrolled to controlled (or vice versa). You initially used no "location" prop and then provided one on a subsequent render.');
warning(!(!nextProps.location && this.props.location), '<Switch> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.');
};
Switch.prototype.render = function render() {
var route = this.context.router.route;
var children = this.props.children;
var location = this.props.location || route.location;
var match = void 0,
child = void 0;
React.Children.forEach(children, function (element) {
if (!React.isValidElement(element)) return;
var _element$props = element.props,
pathProp = _element$props.path,
exact = _element$props.exact,
strict = _element$props.strict,
sensitive = _element$props.sensitive,
from = _element$props.from;
var path = pathProp || from;
if (match == null) {
child = element;
match = path ? matchPath(location.pathname, { path: path, exact: exact, strict: strict, sensitive: sensitive }) : route.match;
}
});
return match ? React.cloneElement(child, { location: location, computedMatch: match }) : null;
};
return Switch;
}(React.Component);
Switch.contextTypes = {
router: PropTypes.shape({
route: PropTypes.object.isRequired
}).isRequired
};
Switch.propTypes = {
children: PropTypes.node,
location: PropTypes.object
};
export default Switch; |
docs/src/app/components/pages/components/Checkbox/Page.js | ichiohta/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import checkboxReadmeText from './README';
import checkboxCode from '!raw!material-ui/Checkbox/Checkbox';
import CheckboxExampleSimple from './ExampleSimple';
import checkboxExampleSimpleCode from '!raw!./ExampleSimple';
const description = 'The second example is selected by default using the `defaultChecked` property. The third ' +
'example is disabled using the `disabled` property. The fourth example uses custom icons through the ' +
'`checkedIcon` and `uncheckedIcon` properties. The final example uses the `labelPosition` property to position the ' +
'label on the left. ';
const CheckboxPage = () => (
<div>
<Title render={(previousTitle) => `Checkbox - ${previousTitle}`} />
<MarkdownElement text={checkboxReadmeText} />
<CodeExample
title="Examples"
description={description}
code={checkboxExampleSimpleCode}
>
<CheckboxExampleSimple />
</CodeExample>
<PropTypeDescription code={checkboxCode} />
</div>
);
export default CheckboxPage;
|
demo/src/components/App/App.js | moroshko/giant-piano | import styles from './App.less';
import React, { Component } from 'react';
import createPagination from 'createPagination';
export default class App extends Component {
constructor() {
super();
const itemsPerPage = 10;
const maxPages = 5;
const currentPage = 4;
const totalItems = 127;
const paginationData =
createPagination({ itemsPerPage, maxPages })({ currentPage, totalItems });
this.state = {
itemsPerPage,
maxPages,
currentPage,
totalItems,
...paginationData
};
this.updateItemsPerPage = ::this.updateItemsPerPage;
this.updateMaxPages = ::this.updateMaxPages;
this.updateCurrentPage = ::this.updateCurrentPage;
this.updateTotalItems = ::this.updateTotalItems;
this.setCurrentPage = ::this.setCurrentPage;
}
updateState(newState) {
const nextState = {
...this.state,
...newState
};
const { itemsPerPage, maxPages, currentPage, totalItems } = nextState;
try {
const newPaginationData =
createPagination({ itemsPerPage, maxPages })({ currentPage, totalItems });
this.setState({
...nextState,
...newPaginationData
});
} catch (error) {
console.info(error); // eslint-disable-line no-console
}
}
updateItemsPerPage(event) {
this.updateState({
itemsPerPage: parseInt(event.target.value, 10)
});
}
updateMaxPages(event) {
this.updateState({
maxPages: parseInt(event.target.value, 10)
});
}
updateCurrentPage(event) {
this.updateState({
currentPage: parseInt(event.target.value, 10)
});
}
updateTotalItems(event) {
this.updateState({
totalItems: parseInt(event.target.value, 10)
});
}
setCurrentPage(page) {
this.updateState({
currentPage: page
});
}
render() {
const { itemsPerPage, maxPages, currentPage, totalItems,
showFirst, showPrev, pages, showNext, showLast, lastPage } = this.state;
const maxItemsPerPage = Math.floor((totalItems - 1) / (currentPage - 1));
const minTotalItems = itemsPerPage * (currentPage - 1) + 1;
return (
<div className={styles.container}>
<div className={styles.header}>
<img src="https://github.com/moroshko/giant-piano/raw/master/giant-piano.gif" />
<a href="https://github.com/moroshko/giant-piano" target="_blank">
<img src="https://img.shields.io/github/stars/moroshko/giant-piano.svg?style=social&label=Star" />
</a>
</div>
<div className={styles.fieldsContainer}>
<div className={styles.field}>
<label className={styles.label} htmlFor="items-per-page">
Items per page:
</label>
<input id="items-per-page" className={styles.input}
type="number" min="1" max={maxItemsPerPage}
value={itemsPerPage} onChange={this.updateItemsPerPage} />
</div>
<div className={styles.field}>
<label className={styles.label} htmlFor="max-pages">
Max pages:
</label>
<input id="max-pages" className={styles.input}
type="number" min="1"
value={maxPages} onChange={this.updateMaxPages} />
</div>
<div className={styles.field}>
<label className={styles.label} htmlFor="current-page">
Current page:
</label>
<input id="current-page" className={styles.input}
type="number" min="1" max={lastPage}
value={currentPage} onChange={this.updateCurrentPage} />
</div>
<div className={styles.field}>
<label className={styles.label} htmlFor="total-items">
Total items:
</label>
<input id="total-items" className={styles.input}
type="number" min={minTotalItems}
value={totalItems} onChange={this.updateTotalItems} />
</div>
</div>
<div className={styles.pagination}>
{
<button className={`${styles.button} ${showFirst ? '' : styles.hidden}`}
onClick={this.setCurrentPage.bind(null, 1)}>
First
</button>
}
{
<button className={`${styles.button} ${showPrev ? '' : styles.hidden}`}
onClick={this.setCurrentPage.bind(null, currentPage - 1)}>
Prev
</button>
}
{
pages.map(page =>
<button className={`${styles.button} ${styles.page} ${page === currentPage ? styles.currentPage : ''}`}
onClick={this.setCurrentPage.bind(null, page)}
key={page}>
{page}
</button>
)
}
{
<button className={`${styles.button} ${showNext ? '' : styles.hidden}`}
onClick={this.setCurrentPage.bind(null, currentPage + 1)}>
Next
</button>
}
{
<button className={`${styles.button} ${showLast ? '' : styles.hidden}`}
onClick={this.setCurrentPage.bind(null, lastPage)}>
Last
</button>
}
</div>
<div className={styles.footer}>
<img src="https://gravatar.com/avatar/e56de06f4b56f6f06e4a9a271ed57e26?s=32"
alt="Misha Moroshko" />
<span>
Crafted with <span className={styles.love}>love</span> by
{' '}<a href="https://twitter.com/moroshko"
target="_blank">@moroshko</a>
</span>
</div>
</div>
);
}
};
|
src/Assignments/StudyGuideModal.js | SwimmingFishSeniorDesign/SwimmingFishWeb | import React from 'react';
import Modal from 'react-modal';
import StudyGuideForm from './StudyGuideForm';
import FlatButton from 'material-ui/FlatButton';
const styles = {
content: {
top: '50%',
left: '50%',
right: 'auto',
marginRight: '-50%',
transform: 'translate(-50%, -50%)',
backgroundColor: '#E3F2FD'
}
};
const closeButton = {
position: 'absolute',
top: '5px',
right: '5px',
minWidth: '50px'
};
class FormModal extends React.Component {
constructor(props) {
super(props);
this.state = {
modalIsOpen: true
};
}
render() {
return (
<Modal
isOpen={this.state.modalIsOpen}
contentLabel="Example Modal"
style={styles}
>
<FlatButton
label="X"
primary={true}
onClick={this.props.closeFormModal}
style={closeButton}
/>
<StudyGuideForm parentState={this.props.parentState} sendData={this.props.sendData} closeFormModal={this.props.closeFormModal} />
</Modal>
);
}
}
export default FormModal;
|
modules/RouterContextMixin.js | stanleycyang/react-router | import React from 'react';
import invariant from 'invariant';
import { stripLeadingSlashes, stringifyQuery } from './URLUtils';
var { func, object } = React.PropTypes;
function pathnameIsActive(pathname, activePathname) {
if (stripLeadingSlashes(activePathname).indexOf(stripLeadingSlashes(pathname)) === 0)
return true; // This quick comparison satisfies most use cases.
// TODO: Implement a more stringent comparison that checks
// to see if the pathname matches any routes (and params)
// in the currently active branch.
return false;
}
function queryIsActive(query, activeQuery) {
if (activeQuery == null)
return query == null;
if (query == null)
return true;
for (var p in query)
if (query.hasOwnProperty(p) && String(query[p]) !== String(activeQuery[p]))
return false;
return true;
}
var RouterContextMixin = {
propTypes: {
stringifyQuery: func.isRequired
},
getDefaultProps() {
return {
stringifyQuery
};
},
childContextTypes: {
router: object.isRequired
},
getChildContext() {
return {
router: this
};
},
/**
* Returns a full URL path from the given pathname and query.
*/
makePath(pathname, query) {
if (query) {
if (typeof query !== 'string')
query = this.props.stringifyQuery(query);
if (query !== '')
return pathname + '?' + query;
}
return pathname;
},
/**
* Returns a string that may safely be used to link to the given
* pathname and query.
*/
makeHref(pathname, query) {
var path = this.makePath(pathname, query);
var { history } = this.props;
if (history && history.makeHref)
return history.makeHref(path);
return path;
},
/**
* Pushes a new Location onto the history stack.
*/
transitionTo(pathname, query, state=null) {
var { history } = this.props;
invariant(
history,
'Router#transitionTo is client-side only (needs history)'
);
history.pushState(state, this.makePath(pathname, query));
},
/**
* Replaces the current Location on the history stack.
*/
replaceWith(pathname, query, state=null) {
var { history } = this.props;
invariant(
history,
'Router#replaceWith is client-side only (needs history)'
);
history.replaceState(state, this.makePath(pathname, query));
},
/**
* Navigates forward/backward n entries in the history stack.
*/
go(n) {
var { history } = this.props;
invariant(
history,
'Router#go is client-side only (needs history)'
);
history.go(n);
},
/**
* Navigates back one entry in the history stack. This is identical to
* the user clicking the browser's back button.
*/
goBack() {
this.go(-1);
},
/**
* Navigates forward one entry in the history stack. This is identical to
* the user clicking the browser's forward button.
*/
goForward() {
this.go(1);
},
/**
* Returns true if a <Link> to the given pathname/query combination is
* currently active.
*/
isActive(pathname, query) {
var { location } = this.state;
if (location == null)
return false;
return pathnameIsActive(pathname, location.pathname) &&
queryIsActive(query, location.query);
}
};
export default RouterContextMixin;
|
tests/react/createElementRequiredProp_string.js | ylu1317/flow | // @flow
import React from 'react';
class Bar extends React.Component<{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/>);
}
}
|
src/routes/adminToolResponseItem/AdminToolResponseItem.js | goldylucks/adamgoldman.me | // @flow
import React from 'react'
import axios from 'axios'
import Link from '../../components/Link'
import Markdown from '../../components/Markdown'
import { replaceVarsUtil } from '../../components/MultiStepForm/multiStepFormUtils'
type Props = {
id: string,
}
class AdminToolResponseItem extends React.Component<Props> {
state = {
toolResponse: null,
isFetchingToolResponse: true,
}
componentDidMount() {
this.fetchToolResponses()
}
render() {
return (
<div>
<div className='container'>
<div className='mainheading'>
<Link to='/adminToolResponses'>Tools history list</Link>
<h1 className='sitetitle'>Tool History</h1>
</div>
{this.renderResponseItem()}
<hr />
</div>
</div>
)
}
renderResponseItem() {
const { isFetchingToolResponse, toolResponse } = this.state
if (isFetchingToolResponse) {
return <div>Loading Responses</div>
}
if (!toolResponse) {
return <div>No response found</div>
}
return (
<div>
<h2>{toolResponse.title}</h2>
<p>Created at: {`${new Date(toolResponse.createdAt)}`}</p>
{/* TODO remove checking for user after https://github.com/goldylucks/adamgoldman.me/issues/99 */}
<p>User: {toolResponse.user && toolResponse.user.name}</p>
<p>Current Step: {toolResponse.currentStepNum}</p>
<p>Status: {toolResponse.status}</p>
{this.renderStepsWithAnswers(toolResponse)}
</div>
)
}
// eslint-disable-next-line class-methods-use-this
renderStepsWithAnswers({
steps,
answerByStep,
currentStepNum,
hiddenFields,
}) {
return steps.slice(0, currentStepNum).map((step, sIdx) => (
<div>
<div
style={{
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-around',
}}
>
<div style={{ width: '60%' }}>
<Markdown
source={
'## ' +
replaceVarsUtil({
// eslint-disable-line prefer-template
str: step.title,
hiddenFields,
answerByStep,
currentStepNum: sIdx,
})
}
/>
<Markdown
dontEmbedd
source={replaceVarsUtil({
str: step.description,
hiddenFields,
answerByStep,
currentStepNum: sIdx,
})}
/>
<Markdown
dontEmbedd
className='text-muted tool-note'
source={replaceVarsUtil({
str: step.notes,
hiddenFields,
answerByStep,
currentStepNum: sIdx,
})}
/>
</div>
<div style={{ width: '30%' }}>
<Markdown
source={replaceVarsUtil({
str: answerByStep[sIdx],
hiddenFields,
answerByStep,
currentStepNum: sIdx,
})}
/>
</div>
</div>
<hr />
</div>
))
}
fetchToolResponses() {
axios
.get(`/api/toolResponses/${this.props.id}`)
.then(({ data }) =>
this.setState({ toolResponse: data, isFetchingToolResponse: false }),
)
.catch(err => {
global.console.log(err)
this.setState({ isFetchingToolResponse: false })
})
}
}
export default AdminToolResponseItem
|
src/parser/shared/modules/resources/mana/ManaUsageGraph.js | anom0ly/WoWAnalyzer | import BaseChart, { formatTime } from 'parser/ui/BaseChart';
import PropTypes from 'prop-types';
import React from 'react';
import { AutoSizer } from 'react-virtualized';
const COLORS = {
MANA: {
background: 'rgba(2, 109, 215, 0.25)',
border: 'rgba(2, 109, 215, 0.6)',
},
HEALING: {
background: 'rgba(2, 217, 110, 0.2)',
border: 'rgba(2, 217, 110, 0.6)',
},
MANA_USED: {
background: 'rgba(215, 2, 6, 0.4)',
border: 'rgba(215, 2, 6, 0.6)',
},
};
class ManaUsageGraph extends React.Component {
static propTypes = {
mana: PropTypes.arrayOf(
PropTypes.shape({
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
}),
).isRequired,
healing: PropTypes.arrayOf(
PropTypes.shape({
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
}),
).isRequired,
manaUsed: PropTypes.arrayOf(
PropTypes.shape({
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
}),
).isRequired,
};
render() {
const { mana, healing, manaUsed } = this.props;
const baseEncoding = {
x: {
field: 'x',
type: 'quantitative',
axis: {
labelExpr: formatTime('datum.value * 1000'),
grid: false,
},
title: null,
scale: { zero: true, nice: false },
},
y: {
field: 'y',
type: 'quantitative',
title: null,
},
};
const spec = {
data: {
name: 'combined',
},
mark: {
type: 'area',
line: {
strokeWidth: 1,
},
},
encoding: {
...baseEncoding,
color: {
field: 'kind',
scale: {
scheme: [COLORS.HEALING.border, COLORS.MANA.border, COLORS.MANA_USED.border],
},
title: null,
legend: {
orient: 'top',
},
},
},
};
const data = {
combined: [
...mana.map((e) => ({ ...e, kind: 'Mana' })),
...healing.map((e) => ({ ...e, kind: 'HPS' })),
...manaUsed.map((e) => ({ ...e, kind: 'Mana Used' })),
],
};
return (
<AutoSizer disableHeight>
{({ width }) => <BaseChart height={400} width={width} spec={spec} data={data} />}
</AutoSizer>
);
}
}
export default ManaUsageGraph;
|
docs/app/Examples/modules/Dropdown/Types/DropdownExampleSelection.js | ben174/Semantic-UI-React | import React from 'react'
import { Dropdown } from 'semantic-ui-react'
import { friendOptions } from '../common'
const DropdownExampleSelection = () => (
<Dropdown placeholder='Select Friend' fluid selection options={friendOptions} />
)
export default DropdownExampleSelection
|
node-siebel-rest/siebel-claims-native/components/Avatar.js | Pravici/node-siebel | import { ColorPropType, StyleSheet, Text, View } from 'react-native';
import PropTypes from 'prop-types';
import React from 'react';
export default function Avatar({ size, backgroundColor, initials }) {
const style = {
width: size,
height: size,
borderRadius: size / 2,
backgroundColor,
};
return (
<View style={[styles.container, style]}>
<Text style={styles.text}>{initials}</Text>
</View>
);
}
Avatar.propTypes = {
initials: PropTypes.string.isRequired,
size: PropTypes.number.isRequired,
backgroundColor: ColorPropType.isRequired,
};
const styles = StyleSheet.create({
container: {
alignItems: 'center',
justifyContent: 'center',
},
text: {
color: 'white',
},
});
|
src/components/MediaList/Actions/MoveToFirst.js | welovekpop/uwave-web-welovekpop.club | import React from 'react';
import PropTypes from 'prop-types';
import MoveToFirstIcon from '@material-ui/icons/KeyboardArrowUp';
import Action from './Action';
const MoveToFirst = ({ onFirst, ...props }) => (
<Action {...props} onAction={onFirst}>
<MoveToFirstIcon />
</Action>
);
MoveToFirst.propTypes = {
onFirst: PropTypes.func.isRequired,
};
export default MoveToFirst;
|
src/routes.js | k2truong/webapp-starterkit | import React from 'react';
import { IndexRoute, Route } from 'react-router';
import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth';
import {
App,
Chat,
Home,
Widgets,
About,
Login,
Signup,
Survey,
NotFound,
} from 'containers';
export default (store) => {
const requireLogin = (nextState, replace, cb) => {
function checkAuth() {
const { auth: { user }} = store.getState();
if (!user) {
// oops, not logged in, so can't be here!
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
});
}
cb();
}
if (!isAuthLoaded(store.getState())) {
store.dispatch(loadAuth()).then(checkAuth);
} else {
checkAuth();
}
};
/**
* Please keep routes in alphabetical order
*/
return (
<Route path="/" component={App}>
{ /* Home (main) route */ }
<IndexRoute component={Home}/>
{ /* Routes requiring login */ }
<Route onEnter={requireLogin}>
<Route path="chat" component={Chat}/>
</Route>
{ /* Routes */ }
<Route path="about" component={About}/>
<Route path="login" component={Login}/>
<Route path="signup" component={Signup}/>
<Route path="survey" component={Survey}/>
<Route path="widgets" component={Widgets}/>
{ /* Catch all route */ }
<Route path="*" component={NotFound} status={404} />
</Route>
);
};
|
src/widgets/PriorityPicker.android.js | anysome/objective | /**
* Created by Layman(http://github.com/anysome) on 16/3/6.
*/
import React from 'react';
import Picker from 'react-native-wheel-picker';
import Objective from '../logic/Objective';
import {colors} from '../views/styles';
export default class PriorityPicker extends React.Component {
constructor(props) {
super(props);
let {small, ...others} = props;
this.others = others;
this.small = small;
}
_renderOptions() {
let children = [];
for (let [key, value] of Objective.priority) {
if (this.small && (key < 1 || key > 3)) continue;
children.push(<Picker.Item key={key} label={value} value={key} />);
}
return children;
}
render() {
let picker = null;
if (this.props.visible) {
picker = (
<Picker {...this.others}
style={{height: this.small ? 120 : 150}}
itemStyle={{color: colors.dark2, fontSize: 26}}
selectedValue={this.props.selectedValue}>
{this._renderOptions()}
</Picker>
);
}
return picker;
}
};
|
components/animals/takinIndicky.child.js | marxsk/zobro | import React, { Component } from 'react';
import { Text } from 'react-native';
import styles from '../../styles/styles';
import InPageImage from '../inPageImage';
import AnimalText from '../animalText';
import AnimalTemplate from '../animalTemplate';
const IMAGES = [
require('../../images/animals/takinIndicky/01.jpg'),
require('../../images/animals/takinIndicky/02.jpg'),
require('../../images/animals/takinIndicky/03.jpg'),
];
const THUMBNAILS = [
require('../../images/animals/takinIndicky/01-thumb.jpg'),
require('../../images/animals/takinIndicky/02-thumb.jpg'),
require('../../images/animals/takinIndicky/03-thumb.jpg'),
];
var AnimalDetail = React.createClass({
render() {
return (
<AnimalTemplate firstIndex={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}>
<AnimalText>
Takin indický je velmi pozoruhodné zvíře. Podobá se totiž hned několika zvířatům najednou. Jeho hlava připomíná ovci, naopak jeho široké, zavalité tělo se podobá bizonovi, avšak nenechme se zmást. Svojí hbitostí a obratností se vyrovná i kamzíkovi. Klenuté, tlusté a špičaté rohy se podobají rohům pakoně a na vrcholku hlavy srůstají. Mají je jak samci, tak samice. Takin má krátké, podsadité nohy, které zakončují široká kopyta. Ta mu pomáhají pohybovat se po nerovném terénu. Jeho tělo produkuje maz, který je pro něj velmi užitečný, protože ho chrání proti vlhkosti, mlhám a dešti. Takin vidí lépe do stran než rovně a je spíše dalekozraký. Má také dosti krátký ocas – je dokonce kratší než jeho rohy.
</AnimalText>
<InPageImage indexes={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
<AnimalText>
Takin je býložravec, což znamená, že spásá různé listy, větvičky a trávu. Má ve zvyku pást se brzy ráno a později odpoledne. Někdy se postaví i na zadní, aby dosáhl pro ty nejšťavnatější lístečky stromu.
</AnimalText>
<AnimalText>
Samici takina indického se obvykle rodí jen jedno mládě. Je ze začátku tmavší než jeho rodiče, avšak jeho srst po jednom měsíci začne světlat. Mládě je do tří dnů od narození schopné chodit a následovat svoji matku. Do půl roku mu začnou růst rohy.
</AnimalText>
<InPageImage indexes={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
<AnimalText>
I když takin může působit těžce a nemotorně, dokáže se velmi obratně pohybovat po skalách a jiných nerovnostech. Zvládne dokonce utíkat až překvapivě vysokou rychlostí – ovšem jen na krátké vzdálenosti.
</AnimalText>
<AnimalText>
Takin obvykle žije v menších stádech a nejinak je tomu i v brněnské zoo.
</AnimalText>
</AnimalTemplate>
);
}
});
module.exports = AnimalDetail;
|
src/routes/Chapter/components/ChapterView.js | bingomanatee/wonderworld | import React from 'react';
import './chapter.scss';
import _ from 'lodash';
import ArticleListItem from '../../../components/ArticleListItem/ArticleListItem';
export class chapter extends React.Component {
constructor (props) {
super(props);
console.log('loading articles');
}
static contextTypes = {
router: React.PropTypes.object
};
componentDidMount () {
this.props.setBreadcrumb([{label: 'Home', path: '/homepage'}]);
this.props.loadArticles(this.props.params.chapterPath);
}
folderLabel (article) {
if (!article.folder) {
return '';
}
return <b>{article.folder.replace('_', ' ')}:</b>;
}
visitArticle (article) {
this.context.router.push(`/article/${encodeURIComponent(article.path.replace(/\.md$/, ''))}`);
}
articlesList () {
if (!this.props.articles.length) {
return (<div className='chapter-container'>
<div className='chapter-container__inner'>
<p>Loading...</p>
</div>
</div>);
}
const visitArticle = (article) => {
this.visitArticle(article);
};
const key = (article) => `article-key-${article.path}`;
return _(this.props.articles)
.sortBy((article) => article.revisedMoment ? -article.revisedMoment.unix() : -100000)
.map((article) => (
<ArticleListItem key={key(article)} article={article} visitArticle={visitArticle} />)).value();
}
render () {
const list = this.articlesList();
return (
<div className='content-frame__scrolling'>
<h1 className='content-frame__title'>{this.props.params.chapterPath}</h1>
{ list }
</div>
);
}
}
chapter.propTypes = {
articles: React.PropTypes.array,
params: React.PropTypes.object,
loadArticles: React.PropTypes.func.isRequired,
getArticles: React.PropTypes.func.isRequired,
setBreadcrumb: React.PropTypes.func
};
export default chapter;
|
src/index.js | Jiivee/react-test | import React from 'react';
import { render } from 'react-dom'
import App from './App';
import Matches from './components/Matches'
import Rules from './components/Rules'
import Tournaments from './components/Tournaments'
import Tournament from './components/Tournament'
import NewTournament from './components/NewTournament'
import MatchBet from './components/MatchBet'
import PlayoffBet from './components/PlayoffBet'
import SetPlayoffResult from './components/SetPlayoffResult'
import TopScorerBet from './components/TopScorerBet'
import SetTopScorerResult from './components/SetTopScorerResult'
import SetMatchResult from './components/SetMatchResult'
import ResultPage from './components/ResultPage'
import NewUser from './components/NewUser'
import Login from './components/Login'
import Signup from './components/Signup'
import LoginStore from './stores/LoginStore'
import LoginActions from './actions/LoginActions';
import { browserHistory, Router, Route, Link } from 'react-router'
function requireAuth(nextState, replace) {
let jwt = localStorage.getItem('jwt');
if (jwt) {
LoginActions.loginUser(jwt);
}
const authStatus = LoginStore.isLoggedIn();
if (!authStatus) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
function requireAdmin(nextState, replace) {
let jwt = localStorage.getItem('jwt');
if (jwt) {
LoginActions.loginUser(jwt);
}
const user = LoginStore.getUser();
if (user.email !== 'joni.vayrynen@gmail.com') {
replace({
pathname: '/',
state: { nextPathname: nextState.location.pathname }
})
}
}
render((
<Router history={browserHistory}>
<Route component={App}>
<Route path="/" component={Matches}/>
<Route path="/rules" component={Rules}/>
<Route path="matches/:matchId/setresult" component={SetMatchResult} onEnter={requireAdmin}/>
<Route path="playoffs/setresults" component={SetPlayoffResult} onEnter={requireAdmin}/>
<Route path="topscorer/setresults" component={SetTopScorerResult} onEnter={requireAdmin}/>
<Route path="tournaments" component={Tournaments} onEnter={requireAuth}/>
<Route path="tournaments/:tournamentId" component={Tournament} onEnter={requireAuth}/>
<Route path="tournaments/:tournamentId/makebets/match" component={MatchBet} onEnter={requireAuth}/>
<Route path="tournaments/:tournamentId/makebets/playoff" component={PlayoffBet} onEnter={requireAuth}/>
<Route path="tournaments/:tournamentId/makebets/topscorer" component={TopScorerBet} onEnter={requireAuth}/>
<Route path="tournaments/:tournamentId/results/:userId" component={ResultPage} onEnter={requireAuth}/>
<Route path="newtournament" component={NewTournament} onEnter={requireAuth}/>
<Route path="newuser/:jwt" component={NewUser}/>
<Route path="login" component={Login} />
<Route path="signup" component={Signup} />
</Route>
</Router>
), document.getElementById('root'))
|
docs/src/sections/ButtonSection.js | jesenko/react-bootstrap | import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function ButtonSection() {
return (
<div className="bs-docs-section">
<h1 className="page-header">
<Anchor id="buttons">Buttons</Anchor> <small>Button</small>
</h1>
<h3><Anchor id="buttons-options">Options</Anchor></h3>
<p>Use any of the available button style types to quickly create a styled button. Just modify the <code>bsStyle</code> prop.</p>
<ReactPlayground codeText={Samples.ButtonTypes} />
<div className="bs-callout bs-callout-warning">
<h4>Button spacing</h4>
<p>Because React doesn't output newlines between elements, buttons on the same line are displayed
flush against each other. To preserve the spacing between multiple inline buttons, wrap your
button group in <code>{"<ButtonToolbar />"}</code>.</p>
</div>
<h3><Anchor id="buttons-sizes">Sizes</Anchor></h3>
<p>Fancy larger or smaller buttons? Add <code>bsSize="large"</code>, <code>bsSize="small"</code>, or <code>bsSize="xsmall"</code> for additional sizes.</p>
<ReactPlayground codeText={Samples.ButtonSizes} />
<p>Create block level buttons—those that span the full width of a parent— by adding the <code>block</code> prop.</p>
<ReactPlayground codeText={Samples.ButtonBlock} />
<h3><Anchor id="buttons-active">Active state</Anchor></h3>
<p>To set a buttons active state simply set the components <code>active</code> prop.</p>
<ReactPlayground codeText={Samples.ButtonActive} />
<h3><Anchor id="buttons-disabled">Disabled state</Anchor></h3>
<p>Make buttons look unclickable by fading them back 50%. To do this add the <code>disabled</code> attribute to buttons.</p>
<ReactPlayground codeText={Samples.ButtonDisabled} />
<div className="bs-callout bs-callout-warning">
<h4>Event handler functionality not impacted</h4>
<p>This prop will only change the <code>{"<Button />"}</code>’s appearance, not its
functionality. Use custom logic to disable the effect of the <code>onClick</code> handlers.</p>
</div>
<h3><Anchor id="buttons-tags">Button tags</Anchor></h3>
<p>The DOM element tag is choosen automatically for you based on the props you supply. Passing
a <code>href</code> will result in the button using a <code>{"<a />"}</code> element otherwise
a <code>{"<button />"}</code> element will be used.</p>
<ReactPlayground codeText={Samples.ButtonTagTypes} />
<h3><Anchor id="buttons-loading">Button loading state</Anchor></h3>
<p>When activating an asynchronous action from a button it is a good UX pattern to give the user
feedback as to the loading state, this can easily be done by updating
your <code>{"<Button />"}</code>’s props from a state change like below.</p>
<ReactPlayground codeText={Samples.ButtonLoading} />
<h3><Anchor id="buttons-props">Props</Anchor></h3>
<PropTable component="Button"/>
</div>
);
}
|
test/regressions/tests/LinearProgress/DeterminateLinearProgress.js | dsslimshaddy/material-ui | // @flow
import React from 'react';
import LinearProgress from 'material-ui/Progress/LinearProgress';
export default function DeterminateLinearProgress() {
return (
<LinearProgress
mode="determinate"
value={60}
style={{
width: 150,
}}
/>
);
}
|
src/client/auth/logout.react.js | Tzitzian/Oppex | import Component from '../components/component.react';
import React from 'react';
export default class Logout extends Component {
static propTypes = {
actions: React.PropTypes.object.isRequired,
msg: React.PropTypes.object.isRequired
}
render() {
const {actions, msg} = this.props;
return (
<div className="logout">
<button
children={msg.auth.logout.button}
onClick={actions.auth.logout}
/>
</div>
);
}
}
|
src/svg-icons/hardware/devices-other.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareDevicesOther = (props) => (
<SvgIcon {...props}>
<path d="M3 6h18V4H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4v-2H3V6zm10 6H9v1.78c-.61.55-1 1.33-1 2.22s.39 1.67 1 2.22V20h4v-1.78c.61-.55 1-1.34 1-2.22s-.39-1.67-1-2.22V12zm-2 5.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM22 8h-6c-.5 0-1 .5-1 1v10c0 .5.5 1 1 1h6c.5 0 1-.5 1-1V9c0-.5-.5-1-1-1zm-1 10h-4v-8h4v8z"/>
</SvgIcon>
);
HardwareDevicesOther = pure(HardwareDevicesOther);
HardwareDevicesOther.displayName = 'HardwareDevicesOther';
HardwareDevicesOther.muiName = 'SvgIcon';
export default HardwareDevicesOther;
|
src/svg-icons/image/filter-3.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFilter3 = (props) => (
<SvgIcon {...props}>
<path d="M21 1H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zM3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm14 8v-1.5c0-.83-.67-1.5-1.5-1.5.83 0 1.5-.67 1.5-1.5V7c0-1.11-.9-2-2-2h-4v2h4v2h-2v2h2v2h-4v2h4c1.1 0 2-.89 2-2z"/>
</SvgIcon>
);
ImageFilter3 = pure(ImageFilter3);
ImageFilter3.displayName = 'ImageFilter3';
ImageFilter3.muiName = 'SvgIcon';
export default ImageFilter3;
|
ui/src/main/js/components/Breadcrumb.js | medallia/aurora | import React from 'react';
import { Link } from 'react-router-dom';
function url(...args) {
return args.join('/');
}
export default function Breadcrumb({ cluster, role, env, name, instance, taskId, update }) {
const crumbs = [<Link key='cluster' to='/scheduler'>{cluster}</Link>];
if (role) {
crumbs.push(<span key='role-divider'>/</span>);
crumbs.push(<Link key='role' to={`/scheduler/${url(role)}`}>{role}</Link>);
}
if (env) {
crumbs.push(<span key='env-divider'>/</span>);
crumbs.push(<Link key='env' to={`/scheduler/${url(role, env)}`}>{env}</Link>);
}
if (name) {
crumbs.push(<span key='name-divider'>/</span>);
crumbs.push(<Link key='name' to={`/scheduler/${url(role, env, name)}`}>{name}</Link>);
}
if (instance) {
crumbs.push(<span key='instance-divider'>/</span>);
crumbs.push(<Link key='instance' to={`/scheduler/${url(role, env, name, instance)}`}>
{instance}
</Link>);
}
if (update) {
crumbs.push(<span key='update-divider'>/</span>);
crumbs.push(<Link key='update' to={`/scheduler/${url(role, env, name, 'update', update)}`}>
{update}
</Link>);
}
if (taskId) {
crumbs.push(<span key='update-divider'>/</span>);
crumbs.push(<Link key='task' to={`/scheduler/${url(role, env, name, 'task', taskId)}`}>
{taskId}
</Link>);
}
return (<div className='aurora-breadcrumb'>
<div className='container'>
<h2>{crumbs}</h2>
</div>
</div>);
}
|
src/components/ProjectActivityCard/component.js | Hylozoic/hylo-redux | import React from 'react'
import Post from '../Post'
import A from '../A'
import { imageUrl } from '../../models/post'
import { humanDate } from '../../util/text'
const spacer = <span> • </span>
const ProjectActivityCard = ({ expanded, onExpand, post, parentPost }, { isMobile }) => {
const backgroundImage = `url(${imageUrl(parentPost)})`
const url = `/p/${parentPost.id}`
return <div className='project-activity-card'>
<div className='project-banner'>
<A className='image' to={url} style={{backgroundImage}} />
<span className='name'>{parentPost.name}</span>
<span className='spacer'>{spacer}</span>
<span className='date'>{humanDate(parentPost.created_at)}</span>
{!isMobile && <A className='orange-button' to={url}>See all requests</A>}
</div>
<Post {...{post, parentPost, onExpand, expanded}} inActivityCard />
</div>
}
ProjectActivityCard.contextTypes = {isMobile: React.PropTypes.bool}
export default ProjectActivityCard
|
app/containers/App/index.js | audoralc/pyxis | /**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
*/
import React from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
static propTypes = { children: React.PropTypes.node,};
static childContextTypes = { muiTheme: React.PropTypes.object };
getChildContext()
{
var theme = getMuiTheme();
return { muiTheme: theme }
};
render() {
return (
<div>
{React.Children.toArray(this.props.children)}
</div>
);
}
}
|
src/components/01-atoms/Calendar/Day/index.js | buildit/bookit-web | import React from 'react'
import PropTypes from 'prop-types'
import momentPropTypes from 'react-moment-proptypes'
import { connect } from 'react-redux'
import { selectDate } from '../../../../actions'
import styles from './styles.scss'
import { day as dayConfig, dot as dotConfig } from '../config'
export const Day = ({ day, handleClick }) => {
const dayStyle = {
width: `${dayConfig.size}rem`,
height: `${dayConfig.size}rem`,
padding: `${dayConfig.padding}rem`,
fontSize: `${dayConfig.fontSize}rem`,
}
const numberStyle = {}
const dotStyle = {
width: `${dotConfig.size}px`,
height: `${dotConfig.size}px`,
}
if (day.isSelectedDate) {
dayStyle.background = '#2b3947' // grey-blue
}
if (!day.isInCurrentMonth) {
dayStyle.opacity = '0'
}
if (day.isToday) {
numberStyle.borderBottom = '2px solid white'
}
if (day.hasUserOwnedMeeting) {
dotStyle.background = '#fbfe34' // brand yellow
}
return (
<span
className={styles.day}
style={dayStyle}
onClick={() => handleClick(day.date)}
>
<span
className={styles.number}
style={numberStyle}
>
{ day.date.format('D') }
<span
className={styles.dot}
style={dotStyle}
/>
</span>
</span>
)
}
Day.propTypes = {
day: PropTypes.shape({
date: momentPropTypes.momentObj,
}),
handleClick: PropTypes.func.isRequired,
}
const mapDispatchToProps = dispatch => ({
handleClick: date => dispatch(selectDate(date)),
})
const connected = connect(null, mapDispatchToProps)(Day)
export default connected
|
react-flux-mui/js/material-ui/src/svg-icons/social/person-add.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialPersonAdd = (props) => (
<SvgIcon {...props}>
<path d="M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm-9-2V7H4v3H1v2h3v3h2v-3h3v-2H6zm9 4c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
</SvgIcon>
);
SocialPersonAdd = pure(SocialPersonAdd);
SocialPersonAdd.displayName = 'SocialPersonAdd';
SocialPersonAdd.muiName = 'SvgIcon';
export default SocialPersonAdd;
|
react/features/base/react/components/web/SectionList.js | gpolitis/jitsi-meet | // @flow
import React, { Component } from 'react';
import type { Section } from '../../Types';
import Container from './Container';
type Props = {
/**
* Rendered when the list is empty. Should be a rendered element.
*/
ListEmptyComponent: Object,
/**
* Used to extract a unique key for a given item at the specified index.
* Key is used for caching and as the react key to track item re-ordering.
*/
keyExtractor: Function,
/**
* Returns a React component that renders each Item in the list.
*/
renderItem: Function,
/**
* Returns a React component that renders the header for every section.
*/
renderSectionHeader: Function,
/**
* An array of sections.
*/
sections: Array<Section>,
/**
* Defines what happens when an item in the section list is clicked.
*/
onItemClick: Function
};
/**
* Implements a React/Web {@link Component} for displaying a list with
* sections similar to React Native's {@code SectionList} in order to
* facilitate cross-platform source code.
*
* @augments Component
*/
export default class SectionList extends Component<Props> {
/**
* Renders the content of this component.
*
* @returns {React.ReactNode}
*/
render() {
const {
ListEmptyComponent,
renderSectionHeader,
renderItem,
sections,
keyExtractor
} = this.props;
/**
* If there are no recent items we don't want to display anything.
*/
if (sections) {
return (
<Container
className = 'navigate-section-list'>
{
sections.length === 0
? ListEmptyComponent
: sections.map((section, sectionIndex) => (
<Container
key = { sectionIndex }>
{ renderSectionHeader(section) }
{ section.data
.map((item, listIndex) => {
const listItem = {
item
};
return renderItem(listItem,
keyExtractor(section,
listIndex));
}) }
</Container>
)
)
}
</Container>
);
}
return null;
}
}
|
examples/search-form/modules/index.js | alexeyraspopov/react-coroutine | import React from 'react';
import ReactDOM from 'react-dom';
import SearchForm from './SearchForm';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { query: '' };
this.handleEvent = this.handleEvent.bind(this);
}
handleEvent(event) {
let query = event.target.value;
this.setState(() => ({ query }));
}
render() {
return (
<article>
<h1>NPM Search</h1>
<input
value={this.state.query}
placeholder="Search for Node packages..."
onChange={this.handleEvent} />
<SearchForm query={this.state.query} />
</article>
);
}
}
ReactDOM.render(<App />, document.querySelector('main'));
|
redux/src/main/renderer/components/TweetBody.js | wozaki/twitter-js-apps | import React from 'react';
import Time from './Time';
import twitterText from 'twitter-text';
import TweetAnchorText from '../../domain/models/TweetAnchorText';
const Anchor = ({ onAnchorClicked, url, text, title }) => {
return (
<a className="Tweet-anchor"
dangerouslySetInnerHTML={{ __html: text }}
href={url}
onClick={onAnchorClicked}
tabIndex="-1"
title={title}
/>
)
};
const Image = ({ imageUrl, tweetUrl }) => {
const onClicked = (event) => {
event.preventDefault();
};
return (
<div className="Tweet-image-container">
<a href={tweetUrl} onClick={onClicked} tabIndex="-1">
<img className="Tweet-image" src={imageUrl}/>
</a>
</div>
);
};
const Text = ({ text }) => {
const escapedText = twitterText.htmlEscape(text);
return <span dangerouslySetInnerHTML={{ __html: escapedText }}/>;
};
const TweetBody = ({ onAnchorClicked, tweet }) => {
const getComponents = () => {
const components = [];
// const { onAnchorClicked, tweet } = this.props;
const { text, id_str } = tweet;
let index = 0;
const entities = new TweetAnchorText(tweet).entities;
entities.forEach((entity) => {
components.push(<Text text={text.substring(index, entity.startIndex)}/>);
if (getImageUrls().indexOf(entity.url) === -1) {
components.push(
<Anchor
text={entity.text}
title={entity.title}
url={entity.url}
onAnchorClicked={onAnchorClicked}
/>
);
}
index = entity.endIndex;
});
components.push(<Text text={text.substring(index, text.length)}/>);
components.push(...getImages());
return components;
};
const getImages = () => {
if (tweet.extended_entities && tweet.extended_entities.media) {
return tweet.extended_entities.media.filter((media) => {
return media.type === 'photo';
}).map((media) => {
return <Image imageUrl={media.media_url_https} tweetUrl={media.url}/>;
});
} else {
return [];
}
};
const getImageUrls = () => {
if (tweet.extended_entities && tweet.extended_entities.media) {
return tweet.extended_entities.media.filter((media) => {
return media.type === 'photo';
}).map((media) => {
return media.url;
});
} else {
return [];
}
};
return (
<div className="Tweet-body">
{getComponents()}
</div>
);
};
export default TweetBody
|
packages/react/.storybook/addon-theme/register.js | carbon-design-system/carbon-components | /**
* Copyright IBM Corp. 2021, 2021
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { addons } from '@storybook/addons';
import { CarbonThemePanel, CarbonTypePanel } from './components/Panel';
import {
CARBON_THEMES_ADDON_ID,
CARBON_THEME_PANEL_ID,
CARBON_TYPE_ADDON_ID,
CARBON_TYPE_PANEL_ID,
} from './shared';
if (process.env.CARBON_REACT_STORYBOOK_USE_CUSTOM_PROPERTIES === 'true') {
// Disabling because storybook addons doesn't provide proptypes or display names for these panels
/* eslint-disable react/display-name, react/prop-types */
addons.register(CARBON_THEMES_ADDON_ID, (api) => {
addons.addPanel(CARBON_THEME_PANEL_ID, {
title: 'Carbon Theme',
render: ({ active, key }) => (
<CarbonThemePanel api={api} key={key} active={active} />
),
});
});
addons.register(CARBON_TYPE_ADDON_ID, (api) => {
addons.addPanel(CARBON_TYPE_PANEL_ID, {
title: 'Carbon Type',
render: ({ active, key }) => (
<CarbonTypePanel api={api} key={key} active={active} />
),
});
});
}
|
components/Trendline.js | cofacts/rumors-site | import React from 'react';
/**
* @param {string} props.id - String ID of article
*/
function Trendline({ id }) {
return (
<a
className="root"
href={`https://datastudio.google.com/u/0/reporting/18J8jZYumsoaCPBk9bdRd97GKvi_W5v-r/page/NrUQ?config=%7B%22df7%22:%22include%25EE%2580%25800%25EE%2580%2580IN%25EE%2580%2580${id}%22%7D`}
target="_blank"
rel="noopener noreferrer"
>
<iframe
width="200"
height="50"
src={`https://datastudio.google.com/embed/reporting/1t6Qx0P_3lsQilD1PPNf0jIfXsJ1Id7uC/page/q0iq?config=%7B%22df1%22:%22include%25EE%2580%25800%25EE%2580%2580IN%25EE%2580%2580${id}%22%7D`}
style={{ border: 0 }}
/>
<style jsx>{`
.root {
display: block;
position: relative;
}
.root::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
`}</style>
</a>
);
}
export default Trendline;
|
src/index.js | nilvisa/LEK_react-with-redux | import _ from 'lodash';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';
const API_KEY = 'AIzaSyDfxJ-hiHH9PRKCH08NXFt9i3l4IZDwa2g';
class App extends Component {
constructor(props) {
super(props);
this.state = {
videos: [],
selectedVideo: null
};
this.videoSearch('surfboards');
}
videoSearch(term) {
YTSearch({ key: API_KEY, term: term }, videos => {
this.setState({
videos: videos,
selectedVideo: videos[0]
});
});
}
render() {
const videoSearch = _.debounce((term) => { this.videoSearch(term)}, 300);
return (
<div>
<SearchBar onSearchTermChange={videoSearch} />
<VideoDetail video={this.state.selectedVideo} />
<VideoList
onVideoSelect={selectedVideo => this.setState({ selectedVideo })}
videos={this.state.videos} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container')); |
src/index.js | ayonghosh/circle-chart-demo | import React from 'react';
import ReactDOM from 'react-dom';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import CircularMeter from './CircularMeter';
let el = document.getElementById('app');
const App = React.createClass({
render() {
return (
<div>
<CircularMeter val={ this.props.revenue }
title="Revenue Estimated vs Actual"
color="#c0392b"/>
<CircularMeter val={ this.props.hours }
title="Hours Estimated vs Actual"
color="#3498db"/>
<CircularMeter val={ this.props.jobs }
title="Jobs Estimated vs Actual"
color="#27ae60"/>
</div>
);
}
});
ReactDOM.render(<App revenue={ 23 } hours={ 54 } jobs={ 38 } />, el);
// Keep randomly changing meter values to demonstrate animations work even
// after first mount
setInterval( () => {
const revenue = Math.round(Math.random() * 100);
const hours = Math.round(Math.random() * 100);
const jobs = Math.round(Math.random() * 100);
ReactDOM.render(<App
revenue={ revenue }
hours={ hours }
jobs={ jobs } />, el);
}, 5000);
|
src/native/todos/Checkbox.js | skallet/este | // @flow
import type { ButtonProps } from '../../common/components/Button';
import React from 'react';
import { Box, Button } from '../../common/components';
import { Image } from 'react-native';
type CheckboxProps = ButtonProps & {
checked?: boolean,
};
const images = {
checked: require('./img/CheckboxChecked.png'),
unchecked: require('./img/Checkbox.png'),
};
const Checkbox = ({
checked,
onPress,
...props
}: CheckboxProps) => (
<Button
onPress={onPress}
{...props}
>
<Box
as={Image}
source={checked ? images.checked : images.unchecked}
style={theme => ({
height: theme.typography.fontSize(0),
width: theme.typography.fontSize(0),
})}
/>
</Button>
);
export default Checkbox;
|
src/CarouselItem.js | PeterDaveHello/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import TransitionEvents from './utils/TransitionEvents';
const CarouselItem = React.createClass({
propTypes: {
direction: React.PropTypes.oneOf(['prev', 'next']),
onAnimateOutEnd: React.PropTypes.func,
active: React.PropTypes.bool,
animateIn: React.PropTypes.bool,
animateOut: React.PropTypes.bool,
caption: React.PropTypes.node,
index: React.PropTypes.number
},
getInitialState() {
return {
direction: null
};
},
getDefaultProps() {
return {
animation: true
};
},
handleAnimateOutEnd() {
if (this.props.onAnimateOutEnd && this.isMounted()) {
this.props.onAnimateOutEnd(this.props.index);
}
},
componentWillReceiveProps(nextProps) {
if (this.props.active !== nextProps.active) {
this.setState({
direction: null
});
}
},
componentDidUpdate(prevProps) {
if (!this.props.active && prevProps.active) {
TransitionEvents.addEndEventListener(
React.findDOMNode(this),
this.handleAnimateOutEnd
);
}
if (this.props.active !== prevProps.active) {
setTimeout(this.startAnimation, 20);
}
},
startAnimation() {
if (!this.isMounted()) {
return;
}
this.setState({
direction: this.props.direction === 'prev' ?
'right' : 'left'
});
},
render() {
let classes = {
item: true,
active: (this.props.active && !this.props.animateIn) || this.props.animateOut,
next: this.props.active && this.props.animateIn && this.props.direction === 'next',
prev: this.props.active && this.props.animateIn && this.props.direction === 'prev'
};
if (this.state.direction && (this.props.animateIn || this.props.animateOut)) {
classes[this.state.direction] = true;
}
return (
<div {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
{this.props.caption ? this.renderCaption() : null}
</div>
);
},
renderCaption() {
return (
<div className="carousel-caption">
{this.props.caption}
</div>
);
}
});
export default CarouselItem;
|
admin/client/components/ListControl.js | efernandesng/keystone | import React from 'react';
import classnames from 'classnames';
var ListControl = React.createClass({
propTypes: {
onClick: React.PropTypes.func,
type: React.PropTypes.oneOf(['check', 'delete', 'sortable']).isRequired
},
renderControl () {
var icon = 'octicon octicon-';
var className = classnames('ItemList__control ItemList__control--' + this.props.type, {
'is-active': this.props.active
});
var tabindex = this.props.type === 'sortable' ? -1 : null;
var title;
if (this.props.type === 'check') {
icon += 'check';
title = 'Check';
}
if (this.props.type === 'delete') {
icon += 'trashcan';
title = 'Delete';
}
if (this.props.type === 'sortable') {
icon += 'three-bars';
title = 'Change sortorder of';
}
return (
<button type="button" title={title + ' item'} onClick={this.props.onClick} className={className} tabIndex={tabindex}>
<span className={icon} />
</button>
);
},
render () {
var className = 'ItemList__col--control ItemList__col--' + this.props.type;
return (
<td className={className}>
{this.renderControl()}
</td>
);
}
});
module.exports = ListControl;
|
src/svg-icons/device/signal-cellular-3-bar.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellular3Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M2 22h20V2z"/><path d="M17 7L2 22h15z"/>
</SvgIcon>
);
DeviceSignalCellular3Bar = pure(DeviceSignalCellular3Bar);
DeviceSignalCellular3Bar.displayName = 'DeviceSignalCellular3Bar';
DeviceSignalCellular3Bar.muiName = 'SvgIcon';
export default DeviceSignalCellular3Bar;
|
src/PageHeader.js | mxc/react-bootstrap | import React from 'react';
import classNames from 'classnames';
const PageHeader = React.createClass({
render() {
return (
<div {...this.props} className={classNames(this.props.className, 'page-header')}>
<h1>{this.props.children}</h1>
</div>
);
}
});
export default PageHeader;
|
examples/sidebar/app.js | gdi2290/react-router | import React from 'react';
import HashHistory from 'react-router/lib/HashHistory';
import { Router, Route, Link } from 'react-router';
import data from './data';
var Category = React.createClass({
render() {
var category = data.lookupCategory(this.props.params.category);
return (
<div>
<h1>{category.name}</h1>
{this.props.children || (
<p>{category.description}</p>
)}
</div>
);
}
});
var CategorySidebar = React.createClass({
render() {
var category = data.lookupCategory(this.props.params.category);
return (
<div>
<Link to="/">◀︎ Back</Link>
<h2>{category.name} Items</h2>
<ul>
{category.items.map(item => (
<li><Link to={`/category/${category.name}/${item.name}`}>{item.name}</Link></li>
))}
</ul>
</div>
);
}
});
var Item = React.createClass({
render() {
var { category, item } = this.props.params;
var menuItem = data.lookupItem(category, item);
return (
<div>
<h1>{menuItem.name}</h1>
<p>${menuItem.price}</p>
</div>
);
}
});
var Index = React.createClass({
render() {
return (
<div>
<h1>Sidebar</h1>
<p>
Routes can have multiple components, so that all portions of your UI
can participate in the routing.
</p>
</div>
);
}
});
var IndexSidebar = React.createClass({
render() {
return (
<div>
<h2>Categories</h2>
<ul>
{data.getAll().map(category => (
<li><Link to={`/category/${category.name}`}>{category.name}</Link></li>
))}
</ul>
</div>
);
}
});
var App = React.createClass({
render() {
return (
<div>
<div className="Sidebar">
{this.props.sidebar || <IndexSidebar/>}
</div>
<div className="Content">
{this.props.content || <Index/>}
</div>
</div>
);
}
});
React.render((
<Router history={new HashHistory}>
<Route path="/" component={App}>
<Route path="category/:category" components={{content: Category, sidebar: CategorySidebar}}>
<Route path=":item" component={Item}/>
</Route>
</Route>
</Router>
), document.getElementById('example'));
|
src/client/components/message/chatMessage.js | uuchat/uuchat | import React, { Component } from 'react';
import { Modal } from 'antd';
import ChatMessageItem from './chatMessageItem';
let onlineListModal = null;
let historyChatFetch = false;
class ChatMessage extends Component{
constructor(){
super();
this.state = {
markVisible: false,
visible: false,
onlineCustomerList: {},
onlineShow: null,
markedLists: {}
};
}
componentDidMount(){
let {socket, chat} = this.props;
let {markedLists} = this.state;
if (!markedLists[chat.cid]) {
markedLists[chat.cid] = chat.marked;
}
this.setState({
markedLists: markedLists
});
socket && socket.on('cs.online.info', this.csOnlineInfo);
}
componentWillUnmount(){
this.props.socket && this.props.socket.off('cs.online.info');
}
componentDidUpdate(){
if (historyChatFetch) {
historyChatFetch = false;
} else {
let msgList = this.refs.list;
msgList.scrollTop = msgList.scrollHeight;
}
}
marked = () => {
let markVisible = this.state.markVisible;
this.setState({
markVisible: !markVisible
});
};
optionSelect = (e) => {
e.stopPropagation();
let type = e.target.getAttribute('data-type');
if (type === 'm') {
this.setState({
visible: true
});
} else if (type === 't') {
this.customerTransfer();
}
};
customerTransfer = () => {
let _self = this;
let onlineLists = [];
let onlines = _self.state.onlineCustomerList;
for (let i in onlines) {
if (i !== _self.props.csid){
onlineLists.push({
name: i,
info: onlines[i]
});
}
}
onlineListModal = Modal.info({
title: 'Online customer success lists',
okText: 'Ok',
content: (
<div>
{onlineLists.length > 0 ? onlineLists.map((cs, i) =>
<div key={i} className="online-item">
<span className="online-avatar fl"> {cs.info[1] !=='' ? <img width="100%" src={cs.info[1]} alt="" /> : <img width="100%" src={require('../../static/images/contact.png')} alt="" /> }</span>
<span className="online-name fl"> {cs.info[0]}</span>
<span className="online-btn fr" data-csid={cs.name} onClick={this.transfer}>Transfer</span>
</div>
) :
<h2>There has no another online customerSuccess!</h2>
}
</div>
),
onOk(){
_self.setState({
markVisible: false
});
}
});
};
markHide = () => {
this.setState({
visible: false,
markVisible: false
});
};
markColorSelect = (e) => {
let {chat, csid, socket} = this.props;
let {markedLists} = this.state;
let t = e.target;
let _self = this;
if (t.tagName.toLowerCase() === 'span') {
socket.emit('cs.marked', chat.cid, csid, parseInt(t.innerHTML, 10), function (type) {
if (type) {
markedLists[chat.cid]=parseInt(t.innerHTML, 10);
_self.setState({
markedLists: markedLists
});
}
});
}
};
csOnlineInfo = (data) =>{
if (Object.keys(this.state.onlineCustomerList).length !== Object.keys(data).length) {
this.setState({
onlineCustomerList: data
});
}
};
transfer = (e) => {
let {socket, chat, transferChat} = this.props;
let _self = this;
let t = e.target;
let csid = t.getAttribute('data-csid');
socket.emit('cs.dispatch', csid, chat.cid, function(success){
if (success) {
transferChat(chat.cid);
_self.setState({
markVisible: false
});
}
onlineListModal.destroy();
});
};
scrollHandle = (e) => {
let msgList = this.refs.list;
let {csid, chat, customerSuccess} = this.props;
let {chatLists, avatar} = customerSuccess.state;
if ((e.deltaY < 0) && (msgList.scrollTop <= 0) && chatLists[chat.cid].hasMoreHistoryChat && !chatLists[chat.cid].isLoading) {
chatLists[chat.cid].isLoading = true;
msgList.className += ' loading';
requestAnimationFrame(function () {
getChatHistory();
});
}
function getChatHistory(){
historyChatFetch = true;
fetch('/messages/customer/' + chat.cid + '/cs/' + csid+'?pageNum='+chatLists[chat.cid].pageNum+'&pageSize=10')
.then((data) => data.json())
.then(d =>{
if (d.code === 200) {
if (d.msg.length === 0 || d.msg.length < 10) {
chatLists[chat.cid].hasMoreHistoryChat = false;
}
chatLists[chat.cid].pageNum++;
chatLists[chat.cid].isLoading = false;
if (d.msg.length > 0) {
d.msg.reverse().map(chat => chatLists[chat.cid].messageLists.unshift({
msgAvatar: (chat.type === 1 || chat.type === 2) ? avatar : '',
msgText: chat.msg,
msgType: chat.type,
msgTime: chat.createdAt
}));
}
customerSuccess.setState({
chatLists: chatLists
});
}
msgList.className = 'message-lists';
})
.catch(e => {
chatLists[chat.cid].isLoading = false;
msgList.className = 'message-lists';
customerSuccess.setState({
chatLists: chatLists
});
});
}
};
render(){
let {visible, markVisible, markedLists} = this.state;
let {chat} = this.props;
let markArr = ['grey', 'red', 'orange', 'yellow', 'green', 'blue', 'purple'];
!markedLists[chat.cid] && (markedLists[chat.cid] = chat.marked);
return (
<div className="chat-message">
<div className="message-title">U-{chat.name.toUpperCase()}
<div className="chat-tags fr" onClick={this.marked}>...
<ul className="more-options" style={{display: !markVisible ? 'none' : 'block'}} onClick={this.optionSelect}>
<span className="caret"></span>
<h3>List Actions <span className="fr options-close" onClick={this.markHide}>╳</span></h3>
<li data-type="m"><i className="action-icon mark"></i>Mark</li>
<li data-type="t"><i className="action-icon transfer"></i>Transfer</li>
</ul>
</div>
<Modal
title="Mark customer for favorite color"
okText="Ok"
cancelText="Cancel"
visible={visible}
onOk={this.markHide}
onCancel={this.markHide}
>
<div className="mark-color-list" onClick={this.markColorSelect}>
{markArr.map((m ,i)=>
<span key={m} className={"mark-tag tag-"+m+(markedLists[chat.cid] === i ? " selected" : "")} title={"mark "+m}>{i}</span>
)}
</div>
</Modal>
</div>
<div className="message-lists" ref="list" onWheel={this.scrollHandle}>
{chat.messageLists.map((msg) =>
<ChatMessageItem
key={msg.msgTime}
ownerType={msg.msgType}
ownerAvatar={msg.msgAvatar}
ownerText={msg.msgText}
time={msg.msgTime}
shortSetting={true}
cid={chat.cid}
/>
)}
</div>
</div>
);
}
}
export default ChatMessage; |
Project 03 - TopMovies/src/components/ListCardItem.js | DCKT/30DaysofReactNative | // @flow
import React from 'react'
import { Image } from 'react-native'
import { Card, CardItem, Left, Body, Text, Button, Icon } from 'native-base'
import type { TMovieListDetail } from '../utils/types'
type Props = {
movie: TMovieListDetail,
onPress: Function
}
export default (props: Props) => {
const { movie, onPress } = props
return (
<Card>
<CardItem button onPress={onPress}>
<Left>
<Body>
<Text>{ movie.title }</Text>
<Text note>{ movie.original_title }</Text>
</Body>
</Left>
</CardItem>
<CardItem cardBody button onPress={onPress}>
<Image source={{ uri: `https://image.tmdb.org/t/p/w500${movie.backdrop_path}` }} style={{ flex: 1, height: 200 }} />
</CardItem>
<CardItem content>
<Text>{ movie.overview }</Text>
</CardItem>
<CardItem style={{ justifyContent: 'space-around' }}>
<Button transparent>
<Text>{ movie.vote_count} votes</Text>
</Button>
<Button transparent>
<Icon ios='ios-star' android='md-star' />
<Text>{ movie.vote_average }/10</Text>
</Button>
<Text>{ movie.release_date }</Text>
</CardItem>
</Card>
)
}
|
src/svg-icons/image/crop-portrait.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCropPortrait = (props) => (
<SvgIcon {...props}>
<path d="M17 3H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H7V5h10v14z"/>
</SvgIcon>
);
ImageCropPortrait = pure(ImageCropPortrait);
ImageCropPortrait.displayName = 'ImageCropPortrait';
ImageCropPortrait.muiName = 'SvgIcon';
export default ImageCropPortrait;
|
src/components/Layout/Header.js | yining1023/thesisBook | import React from 'react'
import {Link} from 'react-router-dom'
import s from './Header.css'
import FilterMenu from '../FilterMenu/FilterMenu'
import logo from '../../img/itp-logo-tisch.svg'
import {Drawer, IconButton} from 'material-ui'
import MenuIcon from 'material-ui/svg-icons/navigation/menu'
class Header extends React.Component {
constructor(props) {
super(props)
this.state = {
showDrawer: false,
}
}
componentDidMount() {
window.componentHandler.upgradeElement(this.root)
window.onresize = () => this.setState({ showDrawer: false })
}
componentWillUnmount() {
window.componentHandler.downgradeElements(this.root)
}
toggleDrawer() {
this.setState({
showDrawer: !this.state.showDrawer,
})
}
render() {
return (
<header className={`mdl-layout__header ${s.header}`} ref={node => (this.root = node)}>
<div className={`mdl-layout__header-row ${s.row}`}>
<Link className={`mdl-layout-title`} to="/">
<img className={s.title} src={logo} alt={"ITP Thesis 2017"} />
</Link>
<div className="mdl-layout-spacer" />
<div className={s.desktop}>
<FilterMenu />
</div>
<div className={s.mobile}>
<IconButton onTouchTap={this.toggleDrawer.bind(this)}><MenuIcon color="#ffffff" /></IconButton>
</div>
<Drawer
docked={false}
width={300}
openSecondary={true}
open={this.state.showDrawer}
onRequestChange={(showDrawer) => this.setState({showDrawer})}
containerStyle={{ backgroundColor: 'rgba(30, 30, 30, 0.6)' }}
>
<FilterMenu />
</Drawer>
</div>
</header>
)
}
}
export default Header
|
node-red/ui/src/components/joystick/main.js | dennisdunn/botlab | import React from 'react';
import ReactDOM from 'react-dom';
import Style from './style.css'
class Joystick extends React.Component {
constructor(props) {
super(props);
};
render() {
(
<div id={this.props.id || "joystick1"}>
<canvas></canvas>
</div>
)
};
}; |
frontend/src/lib/mui-components/ComboboxDialog/components/_ListVirtualized.js | jf248/scrape-the-plate | import React from 'react';
import classnames from 'classnames';
import * as Mui from '@material-ui/core';
import * as Virtualized from 'react-virtualized';
import ListItem from './ListItem';
const styles = theme => ({
root: {
backgroundColor: theme.palette.background.paper,
flex: '1 0 auto',
height: '100%',
paddingTop: 0,
},
noMatch: {
padding: '8px 16px 8px 24px',
fontStyle: 'italic',
color: theme.palette.text.disabled,
},
listSection: {
backgroundColor: 'inherit',
},
ul: {
backgroundColor: 'inherit',
padding: 0,
},
backgroundColor: {
backgroundColor: theme.palette.background.paper,
},
});
class List extends React.Component {
render() {
const {
ListProps: { className: ListClassName, ...ListPropsProp },
SubheaderProps,
classes,
comparator,
downshift,
noMatchProps: { className: noMatchClassName, ...noMatchPropsProp },
noMatchText,
selectedItems,
submenuItems,
items,
groupIndicies,
onMoreClick,
clickedIndex,
} = this.props;
const { isOpen, itemToString } = downshift;
const rowRenderer = ({ index, key, style }) => {
return groupIndicies.includes(index) ? (
<Mui.ListSubheader
style={style}
class={classes.subheader}
key={items[index]}
{...SubheaderProps}
>
{`${items[index]}`}
</Mui.ListSubheader>
) : (
<ListItem
{...{
index,
key: itemToString(items[index]),
item: items[index],
selected: selectedItems.some(selectedItem =>
comparator(items[index], selectedItem)
),
downshift,
style,
clickedIndex,
onMoreClick,
submenuItems,
}}
/>
);
};
const { ref, ...otherListProps } = downshift.getMenuProps();
const NoMatch = () => (
<div
className={classnames(classes.noMatch, noMatchClassName)}
{...noMatchPropsProp}
>
<Mui.Typography color={'inherit'}>{noMatchText}</Mui.Typography>
</div>
);
const StickySubheader = ({ scrollTop }) => {
const stepFunc = (beg, end) => x => {
if (x < beg) {
return 0;
}
if (x > end) {
return 1;
}
return (x - beg) / (end - beg);
};
const newScrollTop =
groupIndicies
.slice(1)
.map(index => stepFunc(index, index + 1))
.reduce((acc, f) => acc + f(scrollTop / 48 + 1), 0) * 48;
return (
<div style={{ position: 'relative', height: 0, width: '100%' }}>
<Virtualized.AutoSizer
style={{ height: 48, position: 'absolute', top: 0, zIndex: 10 }}
>
{({ width }) => (
<Virtualized.List
{...{
style: { overflow: 'hidden' },
scrollTop: newScrollTop,
height: 48,
width: width - 17,
rowCount: groupIndicies.length,
rowHeight: 48,
rowRenderer: ({ index, style }) => (
<Mui.ListSubheader
key={items[groupIndicies[index]]}
style={style}
className={classes.backgroundColor}
{...SubheaderProps}
>
{`${items[groupIndicies[index]]}`}
</Mui.ListSubheader>
),
selectedItems,
}}
/>
)}
</Virtualized.AutoSizer>
</div>
);
};
if (isOpen) {
return (
<Virtualized.ScrollSync>
{({ onScroll, scrollTop }) => (
<React.Fragment>
<StickySubheader {...{ scrollTop }} />
<Mui.RootRef rootRef={ref}>
<Mui.List
{...otherListProps}
className={classnames(classes.root, ListClassName)}
{...ListPropsProp}
>
{items.length === 0 ? (
<NoMatch />
) : (
<Virtualized.AutoSizer>
{({ width, height }) => (
<Virtualized.List
{...{
height,
width,
rowCount: items.length,
rowHeight: 48,
rowRenderer,
selectedItems,
onScroll,
}}
/>
)}
</Virtualized.AutoSizer>
)}
</Mui.List>
</Mui.RootRef>
</React.Fragment>
)}
</Virtualized.ScrollSync>
);
} else {
return null;
}
}
}
List.defaultProps = {
noMatchProps: {},
noMatchText: 'No matches...',
menuBottomFixed: true,
ListProps: {},
selectedItems: [],
};
export default Mui.withStyles(styles)(List);
|
src/components/Spinner/Spinner.js | ismaelgt/english-accents-map | import React from 'react'
class Spinner extends React.Component {
componentDidMount () {
componentHandler.upgradeDom()
}
render () {
return (
<div className='loading-indicator'>
<div ref='spinner' className='mdl-spinner mdl-spinner--single-color mdl-js-spinner is-active' />
</div>
)
}
}
export default Spinner
|
components/Footer/Footer.js | elliotec/LnL | import React from 'react';
import FaFacebookSquare from 'react-icons/lib/fa/facebook-square';
import './Footer.css';
import { Link } from 'react-router';
import inthegullyLogo from 'images/inthegullylogoblack.png';
export default class Footer extends React.Component {
render () {
return (
<div className="footer">
<div className="footer-nav">
<div className="fb-container">
<a href="https://www.facebook.com/groups/1830648883849106/" target="_blank">
<FaFacebookSquare className='fb-button footer-fb' />
</a>
</div>
<div className="footer-flex">
<Link className="footer-link" to='/products/'>Products</Link>
{/* <Link className="footer-link" to='/about/'>About</Link> */}
<Link className="footer-link" to='/howtouse/'>How to Use</Link>
</div>
<div className="gully-flex">
<a className="gully-link" href="http://www.inthegully.com/" target="_blank">
<p className="website-by">website by</p>
<img src={inthegullyLogo} className="gully-logo" alt="inthegully logo"/>
</a>
</div>
</div>
</div>
)
}
}
|
app/components/View/index.js | wanbinkimoon/parmigiana | /**
*
* View
*
*/
import React from 'react';
import ReactDOM from 'react-dom';
import { ViewWrap } from './styles'
import Scene from './scene'
class View extends React.Component { // eslint-disable-line react/prefer-stateless-function
componentDidMount() {
const { screen } = this.props
const ViewDOM = ReactDOM.findDOMNode(this)
const div = document.createElement("div");
div.id = `sceneDOM_${screen}`;
const h = ViewDOM.clientHeight
const w = ViewDOM.clientWidth
ViewDOM.appendChild(div);
Scene(div.id, w, h, this.props.models);
}
render() {
return (
<ViewWrap ref={(ViewWrap) => { this.viewDOM = ViewWrap; }} />
);
}
}
View.propTypes = {
};
export default View;
|
src/routes/ServiceUnavailable/components/ServiceUnavailableView.js | TorinoMeteo/tm-realtime-map | import React from 'react'
export const ServiceUnavailableView = () => (
<div className='page-error'>
<h1 className='text-center'>
<i className='ion-alert-circled' /><br />
Servizio non disponibile 503
</h1>
<p className='lead text-center'>Il server è al momento incapace di risovere le richieste.</p>
</div>
)
export default ServiceUnavailableView
|
app/jsx/gradebook/SISGradePassback/PostGradesDialogSummaryPage.js | djbender/canvas-lms | /*
* Copyright (C) 2014 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import I18n from 'i18n!modules'
import React from 'react'
export default function PostGradesDialogSummaryPage(props) {
return (
<div className="post-summary text-center">
<h1 className="lead">
<span className="assignments-to-post-count">
{I18n.t(
{
one: 'You are ready to sync 1 assignment.',
other: 'You are ready to sync %{count} assignments.'
},
{count: props.postCount}
)}
</span>
</h1>
<h4 style={{color: '#AAAAAA'}}>
{props.needsGradingCount > 0 ? (
<button className="btn btn-link" onClick={props.advanceToNeedsGradingPage}>
{I18n.t(
'assignments_to_grade',
{
one: '1 assignment has ungraded submissions',
other: '%{count} assignments have ungraded submissions'
},
{count: props.needsGradingCount}
)}
</button>
) : null}
</h4>
<form className="form-horizontal form-dialog form-inline">
<div className="form-controls">
<button type="button" className="btn btn-primary" onClick={props.postGrades}>
{I18n.t('Sync Grades')}
</button>
</div>
</form>
</div>
)
}
|
react-semi-theme/src/greetings/Hola.js | tsupol/semi-starter | import React from 'react';
// Since this component is simple and static, there's no parent container for it.
const Hola = () => {
return (
<div>
<h2>Hola from semi theme!</h2>
</div>
);
};
export default Hola;
|
src/components/Github/LoadMoreButton.js | jseminck/react-native-github-feed | import React from 'react';
import { View, TouchableHighlight, Text } from 'react-native';
export default class LoadMoreButton extends React.Component {
static propTypes = {
onLoadMore: React.PropTypes.func.isRequired
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight
underlayColor='white'
activeOpacity={1}
onPress={::this.props.onLoadMore}
>
<Text style={styles.text}>
PLZ MORE
</Text>
</TouchableHighlight>
</View>
);
}
}
const styles = {
container: {
marginTop: 10,
marginBottom: 10,
justifyContent: 'flex-start',
alignItems: 'center'
},
text: {
width: 100,
height: 100,
borderWidth: 2,
borderColor: '#45698F',
borderRadius: 50,
paddingTop: 40,
paddingLeft: 13,
color: '#45698F',
fontWeight: 'bold'
}
} |
packages/material-ui-icons/src/SignalWifi2BarLock.js | lgollut/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z" /><path d="M15.5 14.5c0-2.8 2.2-5 5-5 .4 0 .7 0 1 .1L23.6 7c-.4-.3-4.9-4-11.6-4C5.3 3 .8 6.7.4 7L12 21.5l3.5-4.3v-2.7z" opacity=".3" /><path d="M4.8 12.5l7.2 9 3.5-4.4v-2.6c0-1.3.5-2.5 1.4-3.4C15.6 10.5 14 10 12 10c-4.1 0-6.8 2.2-7.2 2.5z" /></React.Fragment>
, 'SignalWifi2BarLock');
|
src/components/common/svg-icons/editor/format-bold.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatBold = (props) => (
<SvgIcon {...props}>
<path d="M15.6 10.79c.97-.67 1.65-1.77 1.65-2.79 0-2.26-1.75-4-4-4H7v14h7.04c2.09 0 3.71-1.7 3.71-3.79 0-1.52-.86-2.82-2.15-3.42zM10 6.5h3c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5h-3v-3zm3.5 9H10v-3h3.5c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5z"/>
</SvgIcon>
);
EditorFormatBold = pure(EditorFormatBold);
EditorFormatBold.displayName = 'EditorFormatBold';
EditorFormatBold.muiName = 'SvgIcon';
export default EditorFormatBold;
|
packages/frontend/src/components/adminPage/MonitoringService/index.js | ks888/LambStatus | import React from 'react'
// MonitoringService is an interface the all monitoring service classes should implement.
export class MonitoringService {
// getMetricsSelector returns a React component to select monitoring service's metrics.
// The component must handle the `props` object and the `onChange` function properly.
// The `props` object represents a set of values to identify the metric of the monitoring service.
// Its value may be null at first in the process of creating a new metric.
// The component is expected to update the `props` object by interacting with a user.
// When the value is changed, call `onChange` function.
getMetricsSelector () {
throw new Error('not implemented')
}
// getServiceName returns the name of this monitoring service.
getServiceName () {
throw new Error('not implemented')
}
// getMessageInPreviewDialog returns a React component shown in the preview dialog.
// Do not need to override this unless the monitoring service has the different data
// collection mechanism.
getMessageInPreviewDialog () {
return (props) => {
return (
<div>
Note: if the metric added just now, try again in 1 minute. Data will be backfilled up to 30 days in the past.
</div>
)
}
}
}
// MonitoringServiceManager is a manager class to create the new instance of some monitoring service.
class MonitoringServiceManager {
constructor () {
this.services = {}
}
register (serviceName, classObj) {
this.services[serviceName] = classObj
}
create (serviceName) {
const ClassObj = this.services[serviceName]
if (ClassObj === undefined) {
throw new Error(`unknown service: ${serviceName}`)
}
return new ClassObj()
}
listServices () {
return Object.keys(this.services)
}
}
// singleton
export const monitoringServiceManager = new MonitoringServiceManager()
|
src/components/FreelancerInfo/FreelancerInfo.js | ortonomy/flingapp-frontend | import React, { Component } from 'react';
import InfoTable from '../InfoTable/InfoTable';
import info from './FreelancerInfo.module.css';
class FreelancerInfo extends Component {
render() {
const personalInfo = {
'first name': this.props.freelancer.flFirstName,
'last name': this.props.freelancer.flLastName,
'location': this.props.freelancer.flLocation,
'timezone': this.props.freelancer.flTimezone,
'native speaker': this.props.freelancer.flIsNativeSpeaker ? 'Yes' : 'No',
'primary language': this.props.freelancer.flPrimaryLanguage
}
const proInfo = {
'capable roles': 'Chief editor, Editor, Content developer',
'employment status': this.props.freelancer.flEmploymentStatus,
'tags': ['expertise:ESP','works fast'],
'documents': ['freelancer_assessment.doc']
}
const experience = {}
return (
<div className={info.FreelancerInfo}>
<InfoTable title='Personal Information' info={personalInfo}/>
<InfoTable title='Professional Information' info={proInfo}/>
<InfoTable title='Experience' info={experience}/>
</div>
)
}
}
export default FreelancerInfo;
|
src/routes.js | Bucko13/kinects-it | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import { App } from './components/App';
import { Home } from './components/Home';
import Demo from './containers/Demo';
import LoginPage from './containers/LoginPage';
import { SignupPage } from './components/SignupPage';
import DashboardPage from './containers/DashboardPage';
import UsageStatsPage from './containers/UsageStatsPage';
import AddDevicePage from './containers/AddDevicePage';
import SetupDevicePage from './containers/SetupDevicePage';
import DeviceProfilePage from './containers/DeviceProfilePage';
import HomeUsage from './components/HomeUsage';
import JoinRentalPage from './containers/JoinRentalPage';
import ChooseRolePage from './containers/ChooseRolePage';
import DevicePage from './containers/DevicePage';
import Logout from './components/Logout';
import { requireAuthentication } from './containers/requireAuthentication';
export default (
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="/demo" component={Demo} />
<Route path="/login" component={LoginPage} />
<Route path="/signup" component={SignupPage} />
<Route path="/dashboard" component={requireAuthentication(DashboardPage)} />
<Route path="/add-device" component={requireAuthentication(AddDevicePage)} />
<Route path="/usage-stats" component={requireAuthentication(UsageStatsPage)} />
<Route path="/setup-device" component={requireAuthentication(SetupDevicePage)} />
<Route path="/device-profile" component={requireAuthentication(DeviceProfilePage)} />
<Route path="/home-usage" component={requireAuthentication(HomeUsage)} />
<Route path="/join-rental" component={requireAuthentication(JoinRentalPage)} />
<Route path="/device" component={requireAuthentication(DevicePage)} />
<Route path="/choose-role" component={requireAuthentication(ChooseRolePage)} />
<Route path="/logout" component={requireAuthentication(Logout)} />
<Route path="*" component={requireAuthentication(DashboardPage)} />
</Route>
);
|
blueocean-material-icons/src/js/components/svg-icons/hardware/smartphone.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const HardwareSmartphone = (props) => (
<SvgIcon {...props}>
<path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/>
</SvgIcon>
);
HardwareSmartphone.displayName = 'HardwareSmartphone';
HardwareSmartphone.muiName = 'SvgIcon';
export default HardwareSmartphone;
|
13. ReactJS Fundamentals - Feb 2019/03. Events and Forms/Fog-App/src/DynamicForm/RegisterForm.js | zrusev/SoftUni_2016 | import React from 'react';
import './register.css';
class RegisterForm extends React.Component {
constructor(props) {
super(props);
this.state = {
usernameReg: '',
emailReg: '',
passwordReg: ''
}
}
handleChange = event => {
this.setState({
[event.target.id]: event.target.value
});
}
render() {
return (
<div className="Register">
<h1>Sign Up</h1>
<form onSubmit={(event) => {
event.preventDefault();
this.props.registerUser(this.state);
}}>
<label>Username</label>
<input type="text" id="usernameReg" onChange={this.handleChange} />
<label>Email</label>
<input type="text" id="emailReg" onChange={this.handleChange} />
<label>Password</label>
<input type="password" id="passwordReg" onChange={this.handleChange} />
<input type="submit" value="Sign Up"/>
</form>
</div>
)
}
}
export default RegisterForm; |
src/compoments/PurpleCard.js | purple-net/react-native-purple | import React from 'react'
import { View, StyleSheet, Platform, Image } from 'react-native'
import fonts from '../config/fonts'
import colors from '../config/colors'
import Text from './PurpleText'
import Divider from './PurpleDivider'
import normalize from '../util/normalizeText'
let styles = {}
const PurpleCard = ({
children,
flexDirection,
containerStyle,
wrapperStyle,
title,
titleStyle,
dividerStyle,
image,
imageStyle,
fontFamily}) => (
<View style={[
styles.container,
image && {padding: 0},
containerStyle && containerStyle]}>
<View style={[styles.wrapper, wrapperStyle && wrapperStyle, flexDirection && {flexDirection}]}>
{
title && !image && (
<View>
<Text style={[
styles.cardTitle,
titleStyle && titleStyle,
fontFamily && {fontFamily}
]}>{title}</Text>
<Divider style={[styles.divider, dividerStyle && dividerStyle]} />
</View>
)
}
{
image && (
<View style={{flex: 1}}>
<Image
resizeMode='cover'
style={[{flex:1, width: null, height: 150}, imageStyle && imageStyle]}
source={image} />
<View
style={[{padding: 10}, wrapperStyle && wrapperStyle]}>
{title && <Text style={[styles.imageTitle, titleStyle && titleStyle]}>{title}</Text>}
{children}
</View>
</View>
)
}
{ !image && children}
</View>
</View>
)
styles = StyleSheet.create({
container: {
backgroundColor: 'white',
borderColor: colors.grey5,
borderWidth: 1,
padding: 15,
margin: 15,
marginBottom: 0,
...Platform.select({
ios: {
shadowColor: 'rgba(0,0,0, .2)',
shadowOffset: {height: 0, width: 0},
shadowOpacity: 1,
shadowRadius: 1
},
android: {
elevation: 1
}
})
},
imageTitle: {
fontSize: normalize(14),
marginBottom: 8,
color: colors.grey1,
...Platform.select({
ios: {
fontWeight: '500'
},
android: {
fontFamily: fonts.android.black
}
})
},
wrapper: {
backgroundColor: 'transparent'
},
divider: {
marginBottom: 15
},
cardTitle: {
fontSize: normalize(14),
...Platform.select({
ios: {
fontWeight: 'bold'
},
android: {
fontFamily: fonts.android.black
}
}),
textAlign: 'center',
marginBottom: 15,
color: colors.grey1
}
})
export default PurpleCard
|
src/applications/edu-benefits/0994/pages/bankInformation.js | department-of-veterans-affairs/vets-website | import _ from 'lodash';
import React from 'react';
import fullSchema from 'vets-json-schema/dist/22-0994-schema.json';
import ReviewCardField from 'platform/forms-system/src/js/components/ReviewCardField';
import { isValidRoutingNumber } from 'platform/forms/validations';
import { hasNewBankInformation, hasPrefillBankInformation } from '../utils';
import PaymentView from '../components/PaymentView';
import PaymentReviewView from '../components/PaymentReviewView';
import { bankInfoNote, bankInfoHelpText } from '../content/bankInformation';
const { bankAccount } = fullSchema.properties;
const hasNewBankInfo = formData => {
const bankAccountObj = _.get(formData['view:bankAccount'], 'bankAccount', {});
return hasNewBankInformation(bankAccountObj);
};
const hasPrefillBankInfo = formData => {
const bankAccountObj = _.get(formData, 'prefillBankAccount', {});
return hasPrefillBankInformation(bankAccountObj);
};
const startInEdit = data =>
!_.get(data, 'view:hasBankInformation', false) &&
!hasNewBankInformation(data.bankAccount);
const newItemName = 'account information';
const directDepositDescription = formData => {
return (
<div className="vads-u-margin-top--2 vads-u-margin-bottom--2">
<p>
We make payments only through direct deposit, also called electronic
funds transfer (EFT). Please provide your direct deposit information
below. We’ll send your housing payment to this account.
</p>
<img
src="/img/direct-deposit-check-guide.svg"
alt="On a personal check, find your bank’s 9-digit routing number listed along the bottom-left edge, and your account number listed beside that."
/>
{hasPrefillBankInfo(formData) && (
<p>
This is the bank account information we have on file for you. We’ll
send your housing payment to this account.
</p>
)}
</div>
);
};
function validateRoutingNumber(
errors,
routingNumber,
formData,
schema,
errorMessages,
) {
if (!isValidRoutingNumber(routingNumber)) {
errors.addError(errorMessages.pattern);
}
}
const bankAccountUI = {
'ui:order': ['accountType', 'routingNumber', 'accountNumber'],
'ui:description': data => directDepositDescription(data),
accountType: {
'ui:title': 'Account type',
'ui:widget': 'radio',
'ui:options': {
labels: {
checking: 'Checking',
savings: 'Savings',
},
},
},
accountNumber: {
'ui:title': 'Bank account number',
'ui:errorMessages': {
pattern: 'Please enter a valid account number',
required: 'Please enter a bank account number',
},
},
routingNumber: {
'ui:title': 'Bank’s 9-digit routing number',
'ui:validations': [validateRoutingNumber],
'ui:errorMessages': {
pattern: 'Please enter a valid 9 digit routing number',
required: 'Please enter a routing number',
},
},
};
export const uiSchema = {
'ui:title': 'Direct deposit information',
'view:descriptionWithInfo': {
'ui:options': {
hideIf: data => !hasPrefillBankInfo(data) && !hasNewBankInfo(data),
},
},
'view:descriptionWithoutInfo': {
'ui:options': {
hideIf: data => hasPrefillBankInfo(data) || hasNewBankInfo(data),
},
},
'view:bankAccount': {
'ui:field': ReviewCardField,
'ui:options': {
viewComponent: PaymentView,
reviewTitle: 'Payment information',
editTitle: 'Update bank account',
itemName: newItemName,
itemNameAction: 'Update',
startInEdit,
volatileData: true,
},
saveClickTrackEvent: { event: 'edu-0994-bank-account-saved' },
bankAccount: {
...bankAccountUI,
accountType: {
...bankAccountUI.accountType,
'ui:reviewWidget': PaymentReviewView,
'ui:errorMessages': {
required: 'Please choose an account type',
},
},
accountNumber: {
...bankAccountUI.accountNumber,
'ui:reviewWidget': PaymentReviewView,
'ui:errorMessages': {
required: 'Please provide a bank account number',
pattern: 'Please enter a valid account number',
},
},
routingNumber: {
...bankAccountUI.routingNumber,
'ui:reviewWidget': PaymentReviewView,
'ui:errorMessages': {
required: 'Please provide a bank routing number',
pattern: 'Please enter a valid routing number',
},
},
},
},
'view:bankInfoNote': {
'ui:description': bankInfoNote,
},
'view:bankInfoHelpText': {
'ui:description': bankInfoHelpText,
},
};
export const schema = {
type: 'object',
properties: {
'view:descriptionWithInfo': {
type: 'object',
properties: {},
},
'view:descriptionWithoutInfo': {
type: 'object',
properties: {},
},
'view:bankAccount': {
type: 'object',
properties: { bankAccount },
},
'view:bankInfoNote': {
type: 'object',
properties: {},
},
'view:bankInfoHelpText': {
type: 'object',
properties: {},
},
},
};
|
src/js/components/HeaderWeekDaysRow.js | Pearson-Higher-Ed/o-calendar | import React from 'react'
const HeaderWeekDaysRow = (props) => {
return(
<tr>
{props.daysOfWeek.map( (dayOfWeek,i) =>
<th id ={`weekdayHeaderRowCell${i}`} className ='weekdayHeaderRowCell' key ={`weekdayHeaderRowCell${i}`}>
{dayOfWeek}
</th>
)}
</tr>
)
}
export default HeaderWeekDaysRow
|
src/components/MainPage/AboutPattern.js | coolshare/ReactReduxPattern | import React from 'react';
import {connect} from 'react-redux'
import cs from '../../services/CommunicationService'
import RemoteService from '../../services/RemoteService'
import Footer from './Footer';
/**
*
*/
class _AboutPattern extends React.Component{
componentDidMount(tabId) {
let self = this;
RemoteService.fatchThroughProxy("https://raw.githubusercontent.com/coolshare/ReactReduxPattern/master/README.md", {"callback":function(data) {
self.refs.aboutPattern.innerHTML = data;
}})
}
/**
* render
* @return {ReactElement} markup
*/
render(){
return (
<div style={{"height":"500px", "overflow":"auto"}}>
<pre ref="aboutPattern">
{this.props.aboutPattern===undefined?"":this.props.aboutPattern}
</pre>
</div>
)
}
}
const AboutPattern = connect(
store => {
return {
aboutPattern: store.MainContainerReducer.aboutPattern
};
}
)(_AboutPattern);
export default AboutPattern |
src/uic/RightDrawer.js | ajaycheenath/abs | import React, { Component } from 'react';
import drawerStyle from "../css/drawer.css";
import Icon from "./Icon";
class Card extends Component {
componentWillMount() {
this.setState({show: true});
}
onClose = () =>{
this.props.showDrawer(false);
}
render() {
return (
<div>
<div className={drawerStyle.grayOut}>
</div>
<div className={drawerStyle.drawer}>
<Icon styleClass={drawerStyle.close} name="circle-x" onClick={this.onClose}/>
{this.props.children}
</div>
</div>
);
}
}
export default Card;
|
src/carousel.js | jaketrent/react-drift | import PropTypes from 'prop-types'
import React from 'react'
import styleable from 'react-styleable'
import css from './carousel.css'
function renderSlides(props) {
return React.Children.map(props.children, (slide, i) => {
return React.cloneElement(slide, {
style: {
...slide.props.style,
width: props.width,
left: props.width * (i - props.showIndex)
}
})
})
}
function Carousel(props) {
return (
<div className={props.css.root}>
{renderSlides(props)}
{props.nav}
</div>
)
}
Carousel.propTypes = {
nav: PropTypes.node.isRequired,
showIndex: PropTypes.number,
width: PropTypes.number
}
export default styleable(css)(Carousel)
|
src/routes/about/index.js | balmbees/overwatch | import React from 'react';
import About from './About';
export default {
path: '/about',
action() {
return (
<About />
);
},
};
|
techCurriculum/ui/solutions/2.6/src/components/Title.js | tadas412/EngineeringEssentials | /**
* Copyright 2017 Goldman Sachs.
* 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.
**/
import React from 'react';
function Title() {
return (
<div>
<h1>Cards</h1>
<h2>Share your ideas</h2>
</div>
);
}
export default Title;
|
scripts/Input.js | rachardking/react-lofty | import React from 'react';
import classNames from 'classnames';
import validator from 'validator';
import validationMessage './validationMessage';
import Base from './Base';
import addons from 'react/addons';
class Input extends Base {
constructor(props) {
super(props);
this.state = {
value: this.props.value,
validationMessage: this.props.validationMessage,
isValid: true
};
}
//shadow compare
shouldComponentUpdate(nextProps, nextState) {
return addons.addons.PureRenderMixin.shouldComponentUpdate.apply(this, arguments);
}
componentWillReceiveProps(nextProps) {
this.setState({
value: this.props.value
});
}
getValue() {
return this.parseOutputValue(this.getRawValue());
}
getRawValue() {
return this.state.value;
}
parseInputValue(value) {
return value;
}
parseOutputValue(value) {
return value;
}
validationResult() {
let component = this;
if (!component.props.validations) {
return true;
}
let validResult = {
isValid: true,
rule: null,
args: null,
name: this.props.name || '',
value: null,
message: null,
};
//validations="isNumeric,isLength:4:12"
//validationError="This is not a valid email"
//isLength(str, min [, max])
// <div className={className}>
// <input type="text" onChange={this.changeValue} value={this.getValue()}/>
// <span>{errorMessage}</span>
// </div>
component.props.validations.split(',').forEach((validation) => {
let args = validation.split(':');
let rule = args.shift();
let value = component.getValue();
args = args.map((arg) => { return JSON.parse(arg); });
args = [value].concat(args);
validResult.value = value;
validResult.args = args.slice(1);
validResult.rule = rule;
validResult.message = component.props.validationMessage || validationMessage[rule];
if (!validator[rule].apply(validator, args)) {
validResult.isValid = false;
return validResult;
}
});
return validResult;
}
handleChange(e) {
var value = e.target ? e.target.value : e;
this.props.handleInputChange(this, value);
}
validate() {
let validationResult = this.validationResult();
let isValid = validationResult.isValid;
this.props.onValidateToForm(validationResult);
this.props.onValidate(validationResult);
this.setState({
isValid: isValid,
validationMessage: validationResult.validationMessage
});
return validationResult;
}
}
Input.defaultProps = {
onValidate() {},
onChange() {},
onValidateToForm() {}
};
Input.propTypes = {
onValidate: React.PropTypes.Func,
onChange: React.PropTypes.Func
};
export default Input; |
app/jsx/assignments_2/student/components/LatePolicyStatusDisplay/index.js | djbender/canvas-lms | /*
* Copyright (C) 2018 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import I18n from 'i18n!a2LatePolicyStatusDisplay'
import PropTypes from 'prop-types'
import React from 'react'
import {Tooltip} from '@instructure/ui-overlays'
import {Button} from '@instructure/ui-buttons'
import {Flex} from '@instructure/ui-layout'
import {Text} from '@instructure/ui-elements'
import LatePolicyToolTipContent from './LatePolicyToolTipContent'
import {ScreenReaderContent} from '@instructure/ui-a11y'
export default function LatePolicyStatusDisplay(props) {
// TODO: actually pass the assignment and submission in here instead of all these
// separate props
const {attempt, gradingType, grade, originalGrade, pointsDeducted, pointsPossible} = props
return (
<div data-testid="late-policy-container">
<Flex justifyItems="end">
<Flex.Item padding="none xxx-small none none">
<Text size="medium">{I18n.t('Late Policy:')}</Text>
</Flex.Item>
<Flex.Item>
<Tooltip
tip={
<LatePolicyToolTipContent
attempt={attempt}
grade={grade}
gradingType={gradingType}
originalGrade={originalGrade}
pointsDeducted={pointsDeducted}
pointsPossible={pointsPossible}
/>
}
on={['hover', 'focus']}
placement="start"
>
<Button href="#" variant="link" theme={{mediumPadding: '0', mediumHeight: 'normal'}}>
<ScreenReaderContent>
{I18n.t(
{one: 'Late Policy: minus 1 Point', other: 'Late Policy: minus %{count} Points'},
{count: props.pointsDeducted}
)}
</ScreenReaderContent>
<Text aria-hidden="true" size="medium">
{I18n.t(
{one: '-1 Point', other: '-%{count} Points'},
{count: props.pointsDeducted}
)}
</Text>
</Button>
</Tooltip>
</Flex.Item>
</Flex>
</div>
)
}
LatePolicyStatusDisplay.propTypes = {
attempt: PropTypes.number.isRequired,
grade: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
gradingType: PropTypes.string.isRequired,
originalGrade: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
pointsDeducted: PropTypes.number.isRequired,
pointsPossible: PropTypes.number.isRequired
}
|
newclient/scripts/components/admin/admin.js | kuali/research-coi | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import React from 'react'; // eslint-disable-line no-unused-vars
import ReactDOM from 'react-dom';
import {Router, Route, browserHistory} from 'react-router';
import {DetailView} from './detail-view/detail-view';
import {ListView} from './list-view/list-view';
import {SizeAwareComponent} from '../size-aware-component';
import UserInfoStore from '../../stores/user-info-store';
import ConfigStore from '../../stores/config-store';
import ColorStore from '../../stores/color-store'; // eslint-disable-line no-unused-vars
const router = (
<Router history={browserHistory}>
<Route path="/coi/new/admin/detailview" component={DetailView}>
<Route
path="/coi/new/admin/detailview/:id/:statusCd"
component={DetailView}
/>
</Route>
<Route path="/coi/new/admin/listview" component={ListView} />
<Route path="/coi/new/admin*" component={ListView} />
</Router>
);
function latestState() {
return {
configState: ConfigStore.getState(),
userInfoState: UserInfoStore.getState()
};
}
class App extends SizeAwareComponent {
constructor() {
super();
this.state = latestState();
this.onChange = this.onChange.bind(this);
}
getChildContext() {
return {
configState: this.state.configState,
userInfo: this.state.userInfoState.userInfo
};
}
componentDidMount() {
UserInfoStore.listen(this.onChange);
ConfigStore.listen(this.onChange);
}
componentWillUnmount() {
UserInfoStore.unlisten(this.onChange);
ConfigStore.unlisten(this.onChange);
}
onChange() {
this.setState(latestState());
this.forceUpdate();
}
render() {
if (this.state.userInfoState.userInfo.coiRole === undefined) {
return (
<div>
Loading...
</div>
);
}
return router;
}
}
App.childContextTypes = {
configState: React.PropTypes.object,
userInfo: React.PropTypes.object
};
function renderApp() {
ReactDOM.render(<App />, document.querySelector('#theApp'));
ConfigStore.unlisten(renderApp);
}
ConfigStore.listen(renderApp);
window.colorBlindModeOn = false;
if (window.localStorage.getItem('colorBlindModeOn') === 'true') {
document.body.classList.add('color-blind');
window.colorBlindModeOn = true;
}
|
app/projectList/ProjectList.js | stefanKuijers/aw-fullstack-app | // @flow
import React, { Component } from 'react';
import { remote } from 'electron';
import { getStoredState } from '../app/stateStorage';
import {Card, CardTitle, CardText} from 'material-ui/Card';
import Subheader from 'material-ui/Subheader';
import {List, ListItem} from 'material-ui/List';
import Avatar from 'material-ui/Avatar';
import AddIcon from 'material-ui/svg-icons/content/add';
import InfoIcon from 'material-ui/svg-icons/action/info';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import IconButton from 'material-ui/IconButton';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import Popover from 'material-ui/Popover/Popover';
import styles from './ProjectList.css';
import Project from './Project';
// import OnlineProjectsPage from '../onlineProjects/OnlineProjectsPage';
import { projectsExplenation, helpStyles } from '../helpCenter/HelpCenter';
const fileSystem = require('fs');
const Path = require('path');
const dialog = remote.dialog;
const removeLoader = function () {
const element = document.getElementById('app-container');
element.className = 'app-loaded';
}
const initialState = {
createProjectModal: false,
addExistingProjectModal: false,
createFromTemplate: false,
path: undefined
};
export default class ProjectList extends Component {
componentWillMount() {
removeLoader();
this.props.checkActivation({redirect: false});
};
state = {
createProjectModal: false,
addExistingProjectModal: false,
createFromTemplate: false,
path: undefined,
projectPopoverOpen: false,
popoverAnchor: undefined
};
toggleModalBoxState = (modalName = null, path) => {
if (modalName === null) {
this.state.createProjectModal = false;
this.state.addExistingProjectModal = false;
this.state.createFromTemplate = false;
} else {
this.state[modalName] = !this.state[modalName];
}
this.state.path = path;
this.setState(this.state);
};
toggleProjectPopover = (e) => {
this.state.globPopoverOpen = !this.state.globPopoverOpen;
this.state.popoverAnchor = e.currentTarget;
this.setState(this.state);
}
getTemplates(actions) {
const templates = getStoredState('templates');
return templates.map((template, index) => {
return (
<ListItem
key={index}
onTouchTap={() => {actions.createProjectFromTemplate(this.state.path, template.data)}}
primaryText={`${template.name} - ${template.author}`}
secondaryText={template.desc}
className={styles.listItem}
secondaryTextLines={2}
/>
);
});
}
createListItems(actions) {
if (this.props.projects && this.props.projects.length) {
return this.props.projects.map((project, index) => {
const config = this.props.configs[project.configId];
return (<Project key={index} data={{project, config, projects: this.props.projects}} actions={actions}/>);
});
} else {
return (
<div className={styles.noProjectsMessage}>
<p>Add your first project by clicking on the button below</p>
<p>Tip: use a template for your first project</p>
</div>
);
}
}
promptForFolder(action, actions) {
dialog.showOpenDialog({
properties: ['openDirectory']
}, (paths) => {
if (paths && paths.length) {
let path = paths[0] + Path.sep;
fileSystem.exists(
`${path}.workflowconfig`,
(exists) => {this.handleProjectCreation(action, actions, exists, path)});
}
});
}
handleProjectCreation(action, actions, workflowconfigExists, path) {
if ((action === 'createNew' || action === 'createFromTemplate') && workflowconfigExists) {
this.toggleModalBoxState('addExistingProjectModal', path);
}
// we want to create a new project and add its config. Lets do it.
if (action === 'createNew' && !workflowconfigExists) {
actions.createProject(path);
}
// we want to add an existing project and there is a file to import. lets do it
if (action === 'addExistingProject' && workflowconfigExists) {
actions.addExistingProject(path);
}
// we want to import a project but there is not file to import.
if (action === 'addExistingProject' && !workflowconfigExists) {
this.toggleModalBoxState('createProjectModal', path);
}
if (action === 'createFromTemplate' && !workflowconfigExists) {
this.toggleModalBoxState(action, path);
}
}
render() {
removeLoader();
const actions = {
toggleProject: this.props.toggleProject,
startBuild: this.props.startBuild,
deleteProject: this.props.deleteProject,
createProject: this.props.createProject,
addExistingProject: this.props.addExistingProject,
createProjectFromTemplate: this.props.createProjectFromTemplate
};
const modalCancelButton = <FlatButton label="Cancel" onTouchTap={() => {this.toggleModalBoxState()}} />;
const createProjectModalButton = <FlatButton label="Create new project" primary={true} onTouchTap={() => {actions.createProject(this.state.path); this.toggleModalBoxState()}}/>;
const addExistingProjectModalButton = <FlatButton label="Add existing project" primary={true} onTouchTap={() => {actions.addExistingProject(this.state.path); this.toggleModalBoxState()}}/>;
return (
<article className="page">
<Card className="section">
<CardTitle
title={"My Projects"}
className={helpStyles.header}
onTouchTap={this.toggleProjectPopover}
><InfoIcon/></CardTitle>
<Popover
open={this.state.globPopoverOpen}
anchorEl={this.state.popoverAnchor}
onRequestClose={this.toggleProjectPopover}
className={helpStyles.popover}
zDepth={4}
>{projectsExplenation}</Popover>
<CardText>
<List>
{this.createListItems(actions)}
<IconMenu
className={styles.iconMenu}
anchorOrigin={{horizontal: 'middle', vertical: 'top'}}
targetOrigin={{horizontal: 'middle', vertical: 'top'}}
iconButtonElement={
<IconButton className={styles.buttonListItem}>
<ListItem
key="addNew"
leftAvatar={<Avatar icon={<AddIcon/>} />}
primaryText="Add new project"
className={styles.listItem}
/>
</IconButton>
}
>
<MenuItem primaryText="Create New" onTouchTap={() => {this.promptForFolder('createNew', actions)}} />
<MenuItem primaryText="Add Existing Project" onTouchTap={() => {this.promptForFolder('addExistingProject', actions)}} />
<MenuItem primaryText="Create From Template" onTouchTap={() => {this.promptForFolder('createFromTemplate', actions);}}/>
</IconMenu>
</List>
</CardText>
<Dialog
title="Add Existing Project"
actions={[modalCancelButton, addExistingProjectModalButton]}
modal={false}
open={this.state.addExistingProjectModal}
>
The folder you selected already contains a .workflowconfg file. Do you want to add this existing project to your project list?
</Dialog>
<Dialog
title="Create New Project"
actions={[modalCancelButton, createProjectModalButton]}
modal={false}
open={this.state.createProjectModal}
>
The folder you selected does not contain a .workflowconfg file. Do you want to create a new workflow project in this folder?
</Dialog>
<Dialog
title="Create From Template"
actions={[modalCancelButton]}
modal={false}
open={this.state.createFromTemplate}
>
<header>Select a template</header>
<List>{this.getTemplates(actions)}</List>
</Dialog>
</Card>
</article>
);
}
/* <OnlineProjectsPage /> */
}
|
src/components/shop/OrderItem.js | mangal49/HORECA | import React from 'react';
class OrderItem extends React.Component {
render() {
return (
<div>Order Item</div>
);
}
}
export default OrderItem;
|
src/components/controls/input-file.js | kishorevarma/formsy-bulma-components | import React, { Component } from 'react';
import ControlCommon from './control-common';
// A file control can only be set to an empty string.
// I think we need to keep this as an uncontrolled component, so we override the
// value.prop.
class FileControl extends Component {
initElementRef = (element) => {
this.element = element;
}
render() {
let props = [...this.props];
delete props.label;
delete props.value;
return (
<input
{...props}
type="file"
ref={this.initElementRef}
/>
);
}
}
FileControl.propTypes = {
...ControlCommon.propTypes
};
export default FileControl;
|
src/svg-icons/image/camera-alt.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCameraAlt = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="12" r="3.2"/><path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/>
</SvgIcon>
);
ImageCameraAlt = pure(ImageCameraAlt);
ImageCameraAlt.displayName = 'ImageCameraAlt';
ImageCameraAlt.muiName = 'SvgIcon';
export default ImageCameraAlt;
|
app/javascript/mastodon/features/compose/components/autosuggest_account.js | PlantsNetwork/mastodon | import React from 'react';
import Avatar from '../../../components/avatar';
import DisplayName from '../../../components/display_name';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
export default class AutosuggestAccount extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
};
render () {
const { account } = this.props;
return (
<div className='autosuggest-account'>
<div className='autosuggest-account-icon'><Avatar account={account} size={18} /></div>
<DisplayName account={account} />
</div>
);
}
}
|
examples/js/others/expose-api-table.js | powerhome/react-bootstrap-table | /* eslint max-len: 0 */
/* eslint no-alert: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(100);
export default class ExposeApiTable extends React.Component {
constructor(props) {
super(props);
this.state = {
text: ''
};
}
handleClick = (rowKey) => {
alert(this.refs.table.getPageByRowKey(rowKey));
}
render() {
return (
<div>
<div className='form-inline'>
{ `typing your row key -> ` }
<input
className='form-control'
ref='rowKeyInput'
onChange={ (e) => {
this.setState( {
text: e.target.value
} );
} }
value={ this.state.text } />
{ ' ' }
<button
className='btn btn-success'
onClick={ () => {
this.handleClick(parseInt(this.refs.rowKeyInput.value, 10));
} }>
get the page
</button>
</div>
<BootstrapTable
ref='table'
data={ products }
pagination={ true }
search={ true }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
</div>
);
}
}
|
src/svg-icons/image/grain.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageGrain = (props) => (
<SvgIcon {...props}>
<path d="M10 12c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zM6 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12-8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-4 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/>
</SvgIcon>
);
ImageGrain = pure(ImageGrain);
ImageGrain.displayName = 'ImageGrain';
ImageGrain.muiName = 'SvgIcon';
export default ImageGrain;
|
src/rendering/fields.js | MGrin/mgr-form-react | import React from 'react';
import PropTypes from 'prop-types';
import { FIELD_RENDERER_PROPS } from '../props';
export const input = ({ value, className, fieldNameAsCss, validate, disabled, onValueChange, ...otherProps }) => (
<input
value={value}
className={`${className} ${className}-renderer ${className}-${fieldNameAsCss}-renderer`}
onChange={({ target: { value }}) => {
onValueChange(value);
validate(value);
}}
disabled={disabled}
{...otherProps}
/>
);
input.propTypes = FIELD_RENDERER_PROPS;
export const select = ({ value, className, fieldNameAsCss, validate, disabled, onValueChange, options, ...otherProps }) => (
<select
value={value}
className={`${className} ${className}-renderer ${className}-${fieldNameAsCss}-renderer`}
onChange={({ target: { value }}) => {
onValueChange(value);
validate(value);
}}
disabled={disabled}
{...otherProps}>
{options.map((option, idx) => (
<option
value={option.value}
key={`option-${fieldNameAsCss}-${idx}`}>{option.label}</option>
))}
</select>
);
select.propTypes = {
...FIELD_RENDERER_PROPS,
options: PropTypes.arrayOf(
PropTypes.shape({
label: PropTypes.string.isRequired,
value: PropTypes.any.isRequired,
}),
).isRequired,
};
|
blueocean-material-icons/src/js/components/svg-icons/action/picture-in-picture-alt.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionPictureInPictureAlt = (props) => (
<SvgIcon {...props}>
<path d="M19 11h-8v6h8v-6zm4 8V4.98C23 3.88 22.1 3 21 3H3c-1.1 0-2 .88-2 1.98V19c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2zm-2 .02H3V4.97h18v14.05z"/>
</SvgIcon>
);
ActionPictureInPictureAlt.displayName = 'ActionPictureInPictureAlt';
ActionPictureInPictureAlt.muiName = 'SvgIcon';
export default ActionPictureInPictureAlt;
|
test/integration/client-navigation/pages/dynamic/[slug]/route.js | zeit/next.js | import React from 'react'
export default class DynamicRoute extends React.Component {
static async getInitialProps({ query = { slug: 'default' } }) {
return {
query,
}
}
render() {
return <p id="dynamic-page">{this.props.query.slug}</p>
}
}
|
actor-apps/app-web/src/app/components/dialog/TypingSection.react.js | hardikamal/actor-platform | import React from 'react';
import { PureRenderMixin } from 'react/addons';
import classNames from 'classnames';
import DialogStore from 'stores/DialogStore';
export default React.createClass({
mixins: [PureRenderMixin],
getInitialState() {
return {
typing: null,
show: false
};
},
componentDidMount() {
DialogStore.addTypingListener(this.onTypingChange);
},
componentWillUnmount() {
DialogStore.removeTypingListener(this.onTypingChange);
},
onTypingChange() {
const typing = DialogStore.getSelectedDialogTyping();
if (typing === null) {
this.setState({show: false});
} else {
this.setState({typing: typing, show: true});
}
},
render() {
const typing = this.state.typing;
const show = this.state.show;
const typingClassName = classNames('typing', {
'typing--hidden': show === false
});
return (
<div className={typingClassName}>
<div className="typing-indicator"><i></i><i></i><i></i></div>
<span>{typing}</span>
</div>
);
}
});
|
src/shared/components/donate/donate.js | sethbergman/operationcode_frontend | import React from 'react';
import Section from 'shared/components/section/section';
import LinkButton from 'shared/components/linkButton/linkButton';
import commonUrl from 'shared/constants/commonLinks';
import styles from './donate.css';
const Donate = () => (
<Section
title="Donate"
headingLines={false}
className={styles.donateSection}
headingTheme="white"
>
<div className={styles.donate}>
<p>
As a 501(c)(3) veteran-led nonprofit organization, our programs and
services are maintained through the efforts of our volunteer staff. Your
financial support allows us to continue helping the military community
learn software development, enter the tech industry, and code the
future.
</p>
<p>Thank you for supporting our mission!</p>
<LinkButton text="Donate Now" link={commonUrl.donateLink} isExternal />
</div>
</Section>
);
export default Donate;
|
assets/js/pages/LogoutPage.js | trappar/you-should | import React, { Component } from 'react';
import Redirect from 'react-router/Redirect';
import { observer } from 'mobx-react';
import { observable } from 'mobx';
@observer(['alerts', 'user', 'decisions'])
export default class LogoutPage extends Component {
@observable redirect = false;
constructor(props) {
super(props);
fetch('/logout', { credentials: 'include' })
.then(response => {
if (response.ok) {
this.props.user.logout();
this.props.decisions.logout();
this.redirect = true;
} else {
this.props.alerts.setError('There was a problem logging you out.');
this.redirect = true;
}
});
}
render() {
return (
<div className="centerOfScreen">
<div>
{this.redirect && <Redirect to="/"/>}
<h1>Logging you out...</h1>
</div>
</div>
);
}
} |
src/components/TaskInspector/ExpandingMetadataListItem.js | Charlie9830/pounder | import React, { Component } from 'react';
import { Typography, ListItem, List, ListSubheader, Divider, ListItemIcon, ListItemText } from '@material-ui/core';
import Expander from '../Expander';
import PersonIcon from '@material-ui/icons/Person';
import ClockIcon from '@material-ui/icons/AccessTime';
const MetadataItem = (props) => {
return (
<React.Fragment>
<ListSubheader> {props.title} </ListSubheader>
<Divider />
<ListItem>
<ListItemIcon>
<PersonIcon />
</ListItemIcon>
<ListItemText primary={props.by} />
</ListItem>
<ListItem>
<ListItemIcon>
<ClockIcon />
</ListItemIcon>
<ListItemText primary={props.on} />
</ListItem>
</React.Fragment>
)
}
class ExpandingMetadataListItem extends Component {
constructor(props) {
super(props);
// State.
this.state = {
isOpen: false,
}
}
render() {
let { metadata } = this.props;
let closedComponent = (
<div>
<Typography color="textSecondary"> Created {metadata.createdOn} </Typography>
<Typography color="textSecondary"> by {metadata.createdBy} </Typography>
</div>
)
let openComponent = (
<List>
<MetadataItem title="Created" on={metadata.createdOn} by={metadata.createdBy} />
<MetadataItem title="Updated" on={metadata.updatedOn} by={metadata.updatedBy} />
<MetadataItem title="Completed" on={metadata.completedOn} by={metadata.completedBy} />
</List>
)
return (
<ListItem
onClick={() => { this.setState({ isOpen: true })}}>
<Expander
open={this.state.isOpen}
onClose={() => { this.setState({ isOpen: false }) }}
closedComponent={closedComponent}
openComponent={openComponent}/>
</ListItem>
);
}
}
export default ExpandingMetadataListItem; |
example.js | u-wave/react-list-lazy-load | import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
// LazyList wraps around ReactList--so we need both!
import LazyList from 'react-list-lazy-load'
import ReactList from 'react-list'
const randBetween = (min, max) =>
Math.floor(min + (Math.random() * (max - min)))
// Utility to create arrays with test data
const array = (len, val = () => null) => {
const arr = []
for (let i = 0; i < len; i++) {
arr.push(val(i))
}
return arr
}
function mergePage (items, newItems, offset) {
const merged = items.slice()
newItems.forEach((item, idx) => {
merged[idx + offset] = item
})
return merged
}
class App extends React.Component {
constructor (props) {
super(props)
this.state = {
items: array(25, (i) => `item #${i}`)
}
this.handleRequestPage = this.handleRequestPage.bind(this)
}
// Simulate a network request for `limit` items
fetch (page, cb) {
const { minLoadTime, maxLoadTime, pageSize } = this.props
setTimeout(() => {
// Generate a new page of items
const data = array(pageSize, (i) => `item #${(page * pageSize) + i}`)
cb(data)
}, randBetween(minLoadTime, maxLoadTime))
}
handleRequestPage (page, cb) {
const { pageSize } = this.props
// Simulate a network request or other async operation
this.fetch(page, (data) => {
// Merge the new page into the current `items` collection and rerender
this.setState({
items: mergePage(this.state.items, data, page * pageSize)
})
// Tell LazyList that the page was loaded
cb()
})
}
render () {
const { totalItems } = this.props
const { items } = this.state
return (
<LazyList
pageSize={this.props.pageSize}
items={items}
length={totalItems}
onRequestPage={this.handleRequestPage}
>
<ReactList
type='uniform'
length={totalItems}
itemRenderer={(index, key) => (
// If `items[index] == null`, the page is still being loaded.
items[index] != null ? (
<div key={key}>
#{index}
<strong>{items[index]}</strong>
</div>
) : (
<div key={key}>Loading …</div>
)
)}
/>
</LazyList>
)
}
}
App.propTypes = {
pageSize: PropTypes.number.isRequired,
totalItems: PropTypes.number.isRequired,
minLoadTime: PropTypes.number.isRequired,
maxLoadTime: PropTypes.number.isRequired
}
ReactDOM.render(
<App
pageSize={10}
totalItems={1000}
minLoadTime={250}
maxLoadTime={1250}
/>,
document.getElementById('example')
)
|
src/js/components/icons/base/BrandCodepenTry.js | kylebyerly-hp/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-brand-codepen-try`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'brand-codepen-try');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 312 137" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fillRule="evenodd" d="M312,125 C312,131.627 306.627,137 300,137 L12,137 C5.373,137 0,131.627 0,125 L0,12 C0,5.373 5.373,0 12,0 L300,0 C306.627,0 312,5.373 312,12 L312,125 L312,125 Z M51.011,76.064 C53.707,76.064 56.179,77.039 58.097,78.65 L60.707,75.539 C58.083,73.333 54.7,72.001 51.011,72.001 C42.689,72.001 35.918,78.772 35.918,87.094 C35.918,95.416 42.689,102.188 51.011,102.188 C54.7,102.188 58.083,100.856 60.707,98.649 L58.097,95.539 C56.179,97.151 53.707,98.124 51.011,98.124 C44.93,98.124 39.982,93.176 39.982,87.095 C39.982,81.014 44.93,76.064 51.011,76.064 L51.011,76.064 Z M134.562,72.873 L126.435,72.873 C125.313,72.873 124.403,73.783 124.403,74.904 L124.403,99.285 C124.403,100.408 125.313,101.316 126.435,101.316 L134.562,101.316 C142.404,101.316 148.784,94.937 148.784,87.093 C148.784,79.251 142.404,72.873 134.562,72.873 L134.562,72.873 Z M134.562,97.254 L128.466,97.254 L128.466,76.938 L134.562,76.938 C140.164,76.938 144.721,81.495 144.721,87.096 C144.722,92.697 140.164,97.254 134.562,97.254 L134.562,97.254 Z M159.786,74.904 L159.786,99.285 C159.786,100.408 160.695,101.316 161.818,101.316 L178.75,101.316 L178.75,97.253 L163.852,97.253 L163.852,89.126 L173.332,89.126 L173.332,85.063 L163.852,85.063 L163.852,76.936 L178.75,76.936 L178.75,72.874 L161.818,72.874 C160.695,72.873 159.786,73.783 159.786,74.904 L159.786,74.904 Z M221.289,74.904 L221.289,99.285 C221.289,100.408 222.198,101.316 223.32,101.316 L240.252,101.316 L240.252,97.253 L225.354,97.253 L225.354,89.126 L234.834,89.126 L234.834,85.063 L225.354,85.063 L225.354,76.936 L240.252,76.936 L240.252,72.874 L223.32,72.874 C222.198,72.873 221.289,73.783 221.289,74.904 L221.289,74.904 Z M201.952,72.873 L193.148,72.873 C192.025,72.873 191.116,73.783 191.116,74.904 L191.116,101.318 L195.179,101.318 L195.179,89.127 L201.95,89.127 C206.43,89.127 210.077,85.481 210.077,81 C210.077,76.519 206.434,72.873 201.952,72.873 L201.952,72.873 Z M201.952,85.062 L195.18,85.062 L195.18,76.935 L201.952,76.935 C204.193,76.935 206.015,78.757 206.015,80.998 C206.016,83.241 204.193,85.062 201.952,85.062 L201.952,85.062 Z M272.018,72.873 L272.018,93.674 L255.293,73.604 C254.745,72.946 253.846,72.703 253.04,72.995 C252.234,73.287 251.699,74.05 251.699,74.905 L251.699,101.319 L255.763,101.319 L255.763,80.518 L272.488,100.587 C272.883,101.061 273.458,101.318 274.05,101.318 C274.281,101.318 274.516,101.277 274.741,101.195 C275.546,100.904 276.082,100.14 276.082,99.285 L276.082,72.873 L272.018,72.873 L272.018,72.873 Z M112.861,80.168 C112.851,80.115 112.841,80.063 112.828,80.012 C112.82,79.981 112.808,79.952 112.799,79.921 C112.784,79.875 112.77,79.83 112.752,79.785 C112.738,79.754 112.725,79.724 112.71,79.695 C112.689,79.652 112.669,79.611 112.647,79.57 C112.629,79.542 112.612,79.513 112.593,79.484 C112.569,79.445 112.542,79.409 112.515,79.372 C112.494,79.346 112.473,79.318 112.451,79.292 C112.422,79.257 112.39,79.225 112.359,79.191 C112.334,79.166 112.31,79.142 112.284,79.118 C112.251,79.087 112.215,79.058 112.179,79.029 C112.152,79.008 112.124,78.986 112.095,78.966 C112.085,78.958 112.075,78.949 112.064,78.944 L92.254,65.736 C91.628,65.319 90.814,65.319 90.189,65.736 L70.377,78.941 C70.366,78.949 70.357,78.958 70.347,78.964 C70.318,78.984 70.29,79.006 70.262,79.028 C70.226,79.055 70.191,79.085 70.157,79.116 C70.132,79.139 70.107,79.163 70.083,79.188 C70.051,79.221 70.021,79.254 69.99,79.29 C69.968,79.315 69.947,79.343 69.927,79.37 C69.899,79.407 69.873,79.444 69.848,79.483 C69.83,79.512 69.812,79.54 69.795,79.569 C69.772,79.61 69.751,79.651 69.732,79.692 C69.717,79.723 69.704,79.753 69.69,79.783 C69.672,79.827 69.657,79.873 69.642,79.919 C69.632,79.95 69.621,79.98 69.614,80.01 C69.6,80.062 69.591,80.114 69.581,80.166 C69.576,80.192 69.57,80.22 69.566,80.246 C69.555,80.327 69.549,80.407 69.549,80.49 L69.549,93.697 C69.549,93.778 69.555,93.86 69.566,93.94 C69.57,93.966 69.576,93.994 69.581,94.02 C69.591,94.073 69.601,94.124 69.614,94.175 C69.622,94.206 69.633,94.235 69.642,94.266 C69.657,94.313 69.672,94.358 69.69,94.403 C69.704,94.434 69.717,94.464 69.732,94.494 C69.752,94.536 69.772,94.577 69.795,94.618 C69.812,94.647 69.83,94.676 69.848,94.704 C69.873,94.743 69.899,94.78 69.927,94.817 C69.948,94.844 69.968,94.871 69.99,94.897 C70.02,94.932 70.051,94.964 70.083,94.999 C70.107,95.024 70.132,95.048 70.157,95.071 C70.191,95.102 70.226,95.131 70.262,95.159 C70.29,95.18 70.318,95.203 70.347,95.223 C70.358,95.231 70.367,95.24 70.377,95.245 L90.188,108.452 C90.5,108.661 90.86,108.765 91.22,108.765 C91.58,108.765 91.941,108.661 92.253,108.452 L112.063,95.245 C112.075,95.238 112.084,95.228 112.094,95.223 C112.123,95.202 112.151,95.18 112.178,95.159 C112.214,95.131 112.25,95.102 112.283,95.071 C112.309,95.048 112.333,95.024 112.358,94.999 C112.389,94.966 112.42,94.933 112.45,94.897 C112.472,94.871 112.494,94.844 112.514,94.817 C112.541,94.78 112.568,94.743 112.592,94.704 C112.611,94.676 112.628,94.647 112.646,94.618 C112.668,94.577 112.689,94.536 112.709,94.494 C112.724,94.464 112.737,94.434 112.751,94.403 C112.769,94.358 112.783,94.313 112.798,94.266 C112.808,94.235 112.819,94.206 112.827,94.175 C112.841,94.124 112.85,94.072 112.86,94.02 C112.864,93.994 112.871,93.966 112.875,93.94 C112.885,93.86 112.892,93.778 112.892,93.697 L112.892,80.492 C112.892,80.409 112.885,80.329 112.875,80.248 C112.872,80.223 112.865,80.195 112.861,80.168 L112.861,80.168 Z M91.22,91.501 L84.633,87.096 L91.22,82.69 L97.808,87.096 L91.22,91.501 L91.22,91.501 Z M89.357,79.454 L81.282,84.855 L74.764,80.495 L89.357,70.766 L89.357,79.454 L89.357,79.454 L89.357,79.454 Z M77.933,87.096 L73.273,90.212 L73.273,83.979 L77.933,87.096 L77.933,87.096 Z M81.282,89.336 L89.357,94.736 L89.357,103.424 L74.764,93.695 L81.282,89.336 L81.282,89.336 Z M93.082,94.736 L101.157,89.336 L107.676,93.695 L93.082,103.424 L93.082,94.736 L93.082,94.736 Z M104.508,87.096 L109.168,83.979 L109.168,90.211 L104.508,87.096 L104.508,87.096 Z M101.157,84.854 L93.082,79.454 L93.082,70.766 L107.676,80.495 L101.157,84.854 L101.157,84.854 Z M81.272,51.355 L79.064,51.355 L79.064,34.048 L72.577,34.048 L72.577,32.033 L87.759,32.033 L87.759,34.048 L81.272,34.048 L81.272,51.355 L81.272,51.355 Z M107.915,51.355 L102.311,43.847 L96.79,43.847 L96.79,51.355 L94.61,51.355 L94.61,32.033 L102.918,32.033 C107.169,32.033 109.902,34.324 109.902,37.802 C109.902,41.031 107.694,42.908 104.657,43.461 L110.592,51.356 L107.915,51.355 L107.915,51.355 L107.915,51.355 Z M102.752,34.048 L96.79,34.048 L96.79,41.887 L102.725,41.887 C105.623,41.887 107.693,40.396 107.693,37.885 C107.693,35.483 105.872,34.048 102.752,34.048 L102.752,34.048 Z M124.897,51.355 L122.689,51.355 L122.689,43.709 L114.656,32.033 L117.306,32.033 L123.821,41.694 L130.39,32.033 L132.93,32.033 L124.897,43.681 L124.897,51.355 L124.897,51.355 Z M152.59,32.033 L152.59,51.355 L150.409,51.355 L150.409,32.033 L152.59,32.033 L152.59,32.033 Z M168.326,51.355 L166.118,51.355 L166.118,34.048 L159.631,34.048 L159.631,32.033 L174.813,32.033 L174.813,34.048 L168.327,34.048 L168.327,51.355 L168.326,51.355 L168.326,51.355 Z M201.677,51.686 C195.798,51.686 191.85,47.077 191.85,41.722 C191.85,36.367 195.852,31.702 201.733,31.702 C207.612,31.702 211.559,36.311 211.559,41.667 C211.559,47.021 207.557,51.686 201.677,51.686 L201.677,51.686 Z M201.677,33.717 C197.26,33.717 194.114,37.25 194.114,41.667 C194.114,46.084 197.317,49.672 201.733,49.672 C206.149,49.672 209.295,46.139 209.295,41.722 C209.295,37.305 206.094,33.717 201.677,33.717 L201.677,33.717 Z M233.15,32.033 L235.275,32.033 L235.275,51.355 L233.537,51.355 L221.06,35.511 L221.06,51.355 L218.935,51.355 L218.935,32.033 L220.976,32.033 L233.15,47.518 L233.15,32.033 L233.15,32.033 L233.15,32.033 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'BrandCodepenTry';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
client/src/containers/ErrorContainer.js | redcom/pinstery | // @flow
import type { State, ErrorsType } from '../store/CommonStoreTypes';
import React from 'react';
import { connect } from 'react-redux';
import { Errors } from '../components';
const ErrorContainer = ({ error }: ErrorsType) => {
if (!error.error) return null;
return (
<Errors>
{error.error.message}
</Errors>
);
};
export default connect((state: State) => ({ error: state.error }))(
ErrorContainer,
);
|
packages/reactor-kitchensink/src/examples/Grid/GroupedGrid/GroupedGrid.js | markbrocato/extjs-reactor | import React, { Component } from 'react';
import { Container, Grid, Toolbar, SegmentedButton, Button, Column } from '@extjs/ext-react';
import './data';
Ext.require([
'Ext.grid.cell.Number',
'Ext.grid.cell.Widget',
'Ext.grid.SummaryRow',
'Ext.ux.rating.Picker'
]);
export default class GroupedGridExample extends Component {
store = Ext.create('Ext.data.Store', {
autoLoad: true,
proxy: {
type: 'ajax',
url: '/KitchenSink/Restaurants'
},
sorters: ['cuisine', 'name'],
groupField: 'cuisine'
});
state = {
grouped: true
};
onToggleGrouping = on => this.setState({ grouped: on })
render() {
const { grouped } = this.state;
return (
<Container layout="vbox" padding="10">
<Toolbar margin="0 0 20 0" shadow>
<div style={{ marginRight: '10px' }}>Grouping:</div>
<SegmentedButton label="Grouping">
<Button ui="toolbar-default" pressed text="ON" handler={this.onToggleGrouping.bind(this, true)}/>
<Button ui="toolbar-default" text="OFF" handler={this.onToggleGrouping.bind(this, false)}/>
</SegmentedButton>
</Toolbar>
<Grid
flex={1}
title="Restaurants"
shadow
store={this.store}
grouped={grouped}
groupFooter={{
xtype: 'gridsummaryrow'
}}
>
<Column t
text="Name"
dataIndex="name"
flex={1}
groupHeaderTpl='{columnName}: {value:htmlEncode}'
/>
<Column
text="Cuisine"
dataIndex="cuisine"
flex={1}
/>
<Column
text="Rating"
dataIndex="rating"
summaryCell="numbercell"
groupHeaderTpl='{value:repeat("★")} ({value:plural("Star")})'
cell={{
xtype: 'widgetcell',
widget: {
xtype: 'rating',
tip: 'Set to {tracking:plural("Star")}'
}
}}
/>
</Grid>
</Container>
)
}
}
|
src/javascript/shared/components/textfields/TextFieldGroup.js | rahulharinkhede2013/xigro-dashboard |
import React from 'react';
import classnames from 'classnames';
const TextFieldGroup = ({ field, value, label, error, type, onChange, checkUserExists }) => {
return (
<div className={classnames('form-group', { 'has-error': error })}>
<label className="control-label">{label}</label>
<input
onChange={onChange}
onBlur={checkUserExists}
value={value}
type={type}
name={field}
className="form-control"
/>
{error && <span className="help-block">{error}</span>}
</div> );
}
TextFieldGroup.propTypes = {
field: React.PropTypes.string.isRequired,
value: React.PropTypes.string.isRequired,
label: React.PropTypes.string.isRequired,
error: React.PropTypes.string,
type: React.PropTypes.string.isRequired,
onChange: React.PropTypes.func.isRequired,
checkUserExists: React.PropTypes.func
}
TextFieldGroup.defaultProps = {
type: 'text'
}
export default TextFieldGroup; |
src/svg-icons/action/settings-remote.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsRemote = (props) => (
<SvgIcon {...props}>
<path d="M15 9H9c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h6c.55 0 1-.45 1-1V10c0-.55-.45-1-1-1zm-3 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zM7.05 6.05l1.41 1.41C9.37 6.56 10.62 6 12 6s2.63.56 3.54 1.46l1.41-1.41C15.68 4.78 13.93 4 12 4s-3.68.78-4.95 2.05zM12 0C8.96 0 6.21 1.23 4.22 3.22l1.41 1.41C7.26 3.01 9.51 2 12 2s4.74 1.01 6.36 2.64l1.41-1.41C17.79 1.23 15.04 0 12 0z"/>
</SvgIcon>
);
ActionSettingsRemote = pure(ActionSettingsRemote);
ActionSettingsRemote.displayName = 'ActionSettingsRemote';
ActionSettingsRemote.muiName = 'SvgIcon';
export default ActionSettingsRemote;
|
app/templates/blog/Posts.js | twixlyhq/react-site | import React from 'react';
import PostList from './partials/PostList';
const Posts = (props) => {
return (
<PostList {...props} />
);
};
export default Posts; |
modules/snapshots-navigator/icon/index.js | hakonhk/vaerhona | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Container, Label, ImageCompare } from './ui';
import {
Picture,
Statistics,
Thermometer,
Droplets,
Compass,
} from '../../icons';
export default class Icon extends Component {
static propTypes = {
selected: PropTypes.bool.isRequired,
label: PropTypes.string,
onClick: PropTypes.func,
};
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick(e, ...rest) {
e.preventDefault();
if (this.props.onClick) {
this.props.onClick(e, ...rest);
}
}
render() {
let icon;
let fillColor = this.props.selected ? '#00628B' : '#000000';
switch (this.props.type) {
case 'image':
icon = <Picture fill={fillColor} />;
break;
case 'image-compare':
icon = (
<ImageCompare color={fillColor}>
<Picture fill={fillColor} />
</ImageCompare>
);
break;
case 'graph':
icon = <Statistics fill={fillColor} />;
break;
case 'thermometer':
icon = <Thermometer fill={fillColor} />;
break;
case 'droplets':
icon = <Droplets fill={fillColor} />;
break;
case 'compass':
icon = <Compass fill={fillColor} />;
break;
default:
icon = '?';
}
return (
<Container
selected={this.props.selected}
onClick={this.onClick}
onTouchStart={this.onClick}
>
{icon}
{this.props.label ? (
<Label style={{ color: fillColor }}>{this.props.label}</Label>
) : null}
</Container>
);
}
}
|
node_modules/react-bootstrap/es/NavDropdown.js | yeshdev1/Everydays-project | 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 _extends from 'babel-runtime/helpers/extends';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import Dropdown from './Dropdown';
import splitComponentProps from './utils/splitComponentProps';
import ValidComponentChildren from './utils/ValidComponentChildren';
var propTypes = _extends({}, Dropdown.propTypes, {
// Toggle props.
title: PropTypes.node.isRequired,
noCaret: PropTypes.bool,
active: PropTypes.bool,
// Override generated docs from <Dropdown>.
/**
* @private
*/
children: PropTypes.node
});
var NavDropdown = function (_React$Component) {
_inherits(NavDropdown, _React$Component);
function NavDropdown() {
_classCallCheck(this, NavDropdown);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
NavDropdown.prototype.isActive = function isActive(_ref, activeKey, activeHref) {
var props = _ref.props;
var _this2 = this;
if (props.active || activeKey != null && props.eventKey === activeKey || activeHref && props.href === activeHref) {
return true;
}
if (ValidComponentChildren.some(props.children, function (child) {
return _this2.isActive(child, activeKey, activeHref);
})) {
return true;
}
return props.active;
};
NavDropdown.prototype.render = function render() {
var _this3 = this;
var _props = this.props,
title = _props.title,
activeKey = _props.activeKey,
activeHref = _props.activeHref,
className = _props.className,
style = _props.style,
children = _props.children,
props = _objectWithoutProperties(_props, ['title', 'activeKey', 'activeHref', 'className', 'style', 'children']);
var active = this.isActive(this, activeKey, activeHref);
delete props.active; // Accessed via this.isActive().
delete props.eventKey; // Accessed via this.isActive().
var _splitComponentProps = splitComponentProps(props, Dropdown.ControlledComponent),
dropdownProps = _splitComponentProps[0],
toggleProps = _splitComponentProps[1];
// Unlike for the other dropdowns, styling needs to go to the `<Dropdown>`
// rather than the `<Dropdown.Toggle>`.
return React.createElement(
Dropdown,
_extends({}, dropdownProps, {
componentClass: 'li',
className: classNames(className, { active: active }),
style: style
}),
React.createElement(
Dropdown.Toggle,
_extends({}, toggleProps, { useAnchor: true }),
title
),
React.createElement(
Dropdown.Menu,
null,
ValidComponentChildren.map(children, function (child) {
return React.cloneElement(child, {
active: _this3.isActive(child, activeKey, activeHref)
});
})
)
);
};
return NavDropdown;
}(React.Component);
NavDropdown.propTypes = propTypes;
export default NavDropdown; |
actor-apps/app-web/src/app/components/sidebar/HeaderSection.react.js | liruqi/actor-platform-v0.9 | import _ from 'lodash';
import React from 'react';
import mixpanel from 'utils/Mixpanel';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import classNames from 'classnames';
import MyProfileActions from '../../actions/MyProfileActionCreators';
import LoginActionCreators from 'actions/LoginActionCreators';
import HelpActionCreators from 'actions/HelpActionCreators';
import AddContactActionCreators from 'actions/AddContactActionCreators';
import AvatarItem from 'components/common/AvatarItem.react';
import MyProfileModal from 'components/modals/MyProfile.react';
import ActorClient from 'utils/ActorClient';
import AddContactModal from 'components/modals/AddContact.react';
import PreferencesModal from '../modals/Preferences.react';
import PreferencesActionCreators from 'actions/PreferencesActionCreators';
var getStateFromStores = () => {
return {
dialogInfo: null
};
};
@ReactMixin.decorate(IntlMixin)
class HeaderSection extends React.Component {
constructor(props) {
super(props);
this.state = _.assign({
isOpened: false
}, getStateFromStores());
}
componentDidMount() {
ActorClient.bindUser(ActorClient.getUid(), this.setUser);
}
componentWillUnmount() {
ActorClient.unbindUser(ActorClient.getUid(), this.setUser);
}
setUser = (user) => {
this.setState({user: user});
};
setLogout = () => {
LoginActionCreators.setLoggedOut();
};
openMyProfile = () => {
MyProfileActions.show();
mixpanel.track('My profile open');
};
openHelpDialog = () => {
HelpActionCreators.open();
mixpanel.track('Click on HELP');
};
openAddContactModal = () => {
AddContactActionCreators.openModal();
};
onSettingsOpen = () => {
PreferencesActionCreators.show();
};
toggleHeaderMenu = () => {
const { isOpened } = this.state;
if (!isOpened) {
this.setState({isOpened: true});
mixpanel.track('Open sidebar menu');
document.addEventListener('click', this.closeHeaderMenu, false);
} else {
this.closeHeaderMenu();
}
};
closeHeaderMenu = () => {
this.setState({isOpened: false});
document.removeEventListener('click', this.closeHeaderMenu, false);
};
render() {
const { user } = this.state;
if (user) {
let headerClass = classNames('sidebar__header', 'sidebar__header--clickable', {
'sidebar__header--opened': this.state.isOpened
});
let menuClass = classNames('dropdown', {
'dropdown--opened': this.state.isOpened
});
return (
<header className={headerClass}>
<div className="sidebar__header__user row" onClick={this.toggleHeaderMenu}>
<AvatarItem image={user.avatar}
placeholder={user.placeholder}
size="tiny"
title={user.name} />
<span className="sidebar__header__user__name col-xs">{user.name}</span>
<div className={menuClass}>
<span className="dropdown__button">
<i className="material-icons">arrow_drop_down</i>
</span>
<ul className="dropdown__menu dropdown__menu--right">
<li className="dropdown__menu__item hide">
<i className="material-icons">photo_camera</i>
<FormattedMessage message={this.getIntlMessage('setProfilePhoto')}/>
</li>
<li className="dropdown__menu__item" onClick={this.openMyProfile}>
<i className="material-icons">edit</i>
<FormattedMessage message={this.getIntlMessage('editProfile')}/>
</li>
<li className="dropdown__menu__item" onClick={this.openAddContactModal}>
<i className="material-icons">person_add</i>
Add contact
</li>
<li className="dropdown__menu__separator"></li>
<li className="dropdown__menu__item hide">
<svg className="icon icon--dropdown"
dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#integration"/>'}}/>
<FormattedMessage message={this.getIntlMessage('configureIntegrations')}/>
</li>
<li className="dropdown__menu__item" onClick={this.openHelpDialog}>
<i className="material-icons">help</i>
<FormattedMessage message={this.getIntlMessage('helpAndFeedback')}/>
</li>
<li className="dropdown__menu__item" onClick={this.onSettingsOpen}>
<i className="material-icons">settings</i>
<FormattedMessage message={this.getIntlMessage('preferences')}/>
</li>
<li className="dropdown__menu__item dropdown__menu__item--light" onClick={this.setLogout}>
<FormattedMessage message={this.getIntlMessage('signOut')}/>
</li>
</ul>
</div>
</div>
<MyProfileModal/>
<AddContactModal/>
<PreferencesModal/>
</header>
);
} else {
return null;
}
}
}
export default HeaderSection;
|
app/app.js | kondoSoft/react-car-rental | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
// Needed for redux-saga es6 generator support
import 'babel-polyfill';
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import 'sanitize.css/sanitize.css';
// Import root app
import App from 'containers/App';
// Import selector for `syncHistoryWithStore`
import { makeSelectLocationState } from 'containers/App/selectors';
// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';
// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-unresolved, import/extensions */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import CSS reset and Global Styles
import './global-styles';
// Import root routes
import createRoutes from './routes';
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: makeSelectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (messages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={messages}>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</LanguageProvider>
</Provider>,
document.getElementById('app')
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
(new Promise((resolve) => {
resolve(import('intl'));
}))
.then(() => Promise.all([
import('intl/locale-data/jsonp/en.js'),
]))
.then(() => render(translationMessages))
.catch((err) => {
throw err;
});
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.