path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
javascript/src/views/FolderItemImage.js | unclecheese/silverstripe-kickassets | import React from 'react';
import Config from '../stores/Config';
const FolderItemImage = React.createClass({
propTypes: {
type: React.PropTypes.oneOf(['image', 'file', 'folder']),
iconURL: React.PropTypes.string,
title: React.PropTypes.string,
extension: React.PropTypes.string
},
getInitialState () {
return {
src: this.props.iconURL || this.getIconPath(this.props.extension)
}
},
componentWillReceiveProps (nextProps) {
this.setState({
src: nextProps.iconURL || this.getIconPath(nextProps.extension)
});
},
getIconPath () {
const ext = this.props.extension || this.props.title.split('.').pop().toLowerCase(),
iconSize = Config.get('iconSize'),
thumbnailsDir = Config.get('thumbnailsDir');
return `${thumbnailsDir}/${iconSize}px/${ext}.png`;
},
showBlank () {
this.setState({
src: this.getIconPath('_blank')
});
},
render () {
return <img draggable={false} src={this.state.src} onError={this.showBlank} />
}
});
export default FolderItemImage; |
modules/Redirect.js | migolo/react-router | import React from 'react'
import invariant from 'invariant'
import { createRouteFromReactElement } from './RouteUtils'
import { formatPattern } from './PatternUtils'
import { falsy } from './PropTypes'
const { string, object } = React.PropTypes
/**
* A <Redirect> is used to declare another URL path a client should be sent
* to when they request a given URL.
*
* Redirects are placed alongside routes in the route configuration and are
* traversed in the same manner.
*/
const Redirect = React.createClass({
statics: {
createRouteFromReactElement(element) {
const route = createRouteFromReactElement(element)
if (route.from)
route.path = route.from
// TODO: Handle relative pathnames, see #1658
invariant(
route.to.charAt(0) === '/',
'<Redirect to> must be an absolute path. This should be fixed in the future'
)
route.onEnter = function (nextState, replaceState) {
const { location, params } = nextState
const pathname = route.to ? formatPattern(route.to, params) : location.pathname
replaceState(
route.state || location.state,
pathname,
route.query || location.query
)
}
return route
}
},
propTypes: {
path: string,
from: string, // Alias for path
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
render() {
invariant(
false,
'<Redirect> elements are for router configuration only and should not be rendered'
)
}
})
export default Redirect
|
examples/auth/src/components/Profile.js | lore/lore | import React from 'react';
import createReactClass from 'create-react-class';
import PropTypes from 'prop-types';
import { connect } from 'lore-hook-connect';
import { withRouter } from 'react-router';
export default connect(function(getState, props) {
return {
user: getState('user.current'),
userPermissions: getState('permission.forCurrentUser')
};
})(
withRouter(createReactClass({
displayName: 'Profile',
propTypes: {
user: PropTypes.object.isRequired,
userPermissions: PropTypes.object.isRequired
},
getStyles: function() {
return {
card: {
position: 'relative',
display: 'block',
marginBottom: '.75rem',
backgroundColor: '#fff',
borderRadius: '.25rem',
border: '1px solid rgba(0,0,0,.125)',
marginTop: '20px'
},
cardBlock: {
padding: '1.25rem'
},
avatar: {
width: '40px',
// display: 'inline-block',
position: 'absolute',
top: '-20px',
left: '50%'
},
permissions: {
marginLeft: '-12px'
}
}
},
logout: function() {
this.props.router.push('/logout');
},
render: function() {
const { user, userPermissions } = this.props;
const styles = this.getStyles();
const permissions = userPermissions.data.map(function(permission) {
return (
<li key={permission.id}>
{permission.data.description}
</li>
);
});
// if (user.data.nickname === 'admin') {
// permissions = 'You are allowed to create, edit, update and delete todos.'
// } else {
// permissions = 'You are only allowed to view todos.';
// }
return (
<div className="card" style={styles.card}>
<div className="card-block" style={styles.cardBlock}>
<img
className="img-circle"
src={user.data.picture}
style={styles.avatar} />
<h4 className="card-title">
Hi {user.data.nickname}!
</h4>
<div className="card-text">
<p>You have permission to perform the following:</p>
<ul style={styles.permissions}>
{permissions}
</ul>
</div>
<button className="btn btn-primary" onClick={this.logout}>
Logout
</button>
</div>
</div>
);
}
}))
);
|
packages/envision-docs/src/components/Footer/index.js | sitevision/envision | import React from 'react';
import Helmet from 'react-helmet';
import PropTypes from 'prop-types';
import Link from '../Link';
const Footer = ({ menuItems }) => {
return (
<>
<div className="footer-wrapper">
<footer className="footer">
<a href="https://www.sitevision.se/">© Sitevision</a>
<nav className="footer-nav">
<ul className="env-nav env-nav--menubar env-nav--border">
{menuItems.map(({ label, to }) => (
<li className="env-nav__item" key={label}>
<Link to={to} activeClassName="active">
{label}
</Link>
</li>
))}
</ul>
</nav>
</footer>
</div>
<Helmet>
<script>
{`var _paq = _paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(["setDoNotTrack", true]);
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//uistats.sitevision.se/";
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', '8']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();`}
</script>
</Helmet>
</>
);
};
Footer.propTypes = {
menuItems: PropTypes.array,
};
export default Footer;
|
test/helpers.js | rapilabs/react-bootstrap | import React from 'react';
import { cloneElement } from 'react';
export function shouldWarn(about) {
console.warn.called.should.be.true;
console.warn.calledWithMatch(about).should.be.true;
console.warn.reset();
}
/**
* Helper for rendering and updating props for plain class Components
* since `setProps` is deprecated.
* @param {ReactElement} element Root element to render
* @param {HTMLElement?} mountPoint Optional mount node, when empty it uses an unattached div like `renderIntoDocument()`
* @return {ComponentInstance} The instance, with a new method `renderWithProps` which will return a new instance with updated props
*/
export function render(element, mountPoint){
let mount = mountPoint || document.createElement('div');
let instance = React.render(element, mount);
if (!instance.renderWithProps) {
instance.renderWithProps = function(newProps) {
return render(
cloneElement(element, newProps), mount);
};
}
return instance;
}
|
src/ui/molecule/InterfaceForm/Wires.js | jkubos/tickator-ide | import React from 'react'
import {observable} from 'mobx'
import {observer} from 'mobx-react'
import styles from './style.less'
import {UiState} from '~/src/business/UiState'
import {Modals} from '~/src/business/Modals'
import {Tools} from '~/src/util/Tools'
import {WireDefinition} from '~/src/tickator/definition/WireDefinition'
import {DataTypes} from '~/src/tickator/DataTypes'
import {Vector} from '~/src/util/geometry/Vector'
import {Point} from '~/src/util/geometry/Point'
import {LongClickDetector} from '~/src/util/LongClickDetector'
import {Button} from '~/src/ui/quark/Button'
@observer
export class Wires extends React.Component {
_WIDTH = 600
_PIN_BOX_HEIGHT = 70
_ARROW_HALF_LENGTH = 15
static propTypes = {
wires: React.PropTypes.arrayOf(React.PropTypes.instanceOf(WireDefinition)).isRequired
}
static contextTypes = {
uiState: React.PropTypes.instanceOf(UiState).isRequired
}
render() {
return <svg
style={{display: 'inline', userSelect: 'none'}}
width={this._WIDTH}
height={this._PIN_BOX_HEIGHT*this.props.wires.length}
>
{this.props.wires.map((wire, i)=>this._renderWire(wire, i))}
</svg>
}
_renderWire(wire, index) {
const y = (index+1)*this._PIN_BOX_HEIGHT-20
const arrowDirection = new Vector(wire.direction=='in'?-1:1, 0)
let typeLabel = '?'
if (wire.basicType) {
typeLabel = DataTypes[wire.basicType]
} else if (wire.refType) {
typeLabel = wire.refType.name
}
return <g key={wire.businessObject.uuid}>
<text
x={this._WIDTH/2-5}
y={y-25}
textAnchor="end"
alignmentBaseline="baseline"
fill={wire.hasValidType() ? 'white' : 'red' }
onClick={e=>this._editType(wire)}
>{typeLabel}</text>
<text
x={this._WIDTH/2+5}
y={y-25}
textAnchor="start"
alignmentBaseline="baseline"
fill={wire.nameIsValid ? 'white' : 'red'}
onClick={e=>this._editLabel(wire)}
>{wire.name || '???'}</text>
<line
x1={0}
y1={y}
x2={this._WIDTH}
y2={y}
stroke="#333"
strokeWidth={18}
onClick={e=>this._openMenu(wire)}
/>
<line
x1={0}
y1={y}
x2={this._WIDTH}
y2={y}
stroke="white"
strokeWidth={4}
onClick={e=>this._openMenu(wire)}
/>
{this._renderArrow(new Point(50, y), arrowDirection, wire)}
{this._renderArrow(new Point(this._WIDTH-50, y), arrowDirection, wire)}
</g>
}
_renderArrow(point, dir, wire) {
const p1 = point.added(dir.unit().multiplied(this._ARROW_HALF_LENGTH))
const baseEnd = point.added(dir.unit().multiplied(-1*this._ARROW_HALF_LENGTH))
const p2 = baseEnd.added(dir.unit().perpendAntiClockwise().multiplied(this._ARROW_HALF_LENGTH))
const p3 = baseEnd.added(dir.unit().perpendClockwise().multiplied(this._ARROW_HALF_LENGTH))
return <polygon
points={[p1, p2, p3].map(p=>p.toCoord()).join(' ')}
stroke="white"
strokeWidth="1"
fill="white"
onClick={e=>this._changeDirection(wire)}
/>
}
_changeDirection(wire) {
if (wire.direction=='in') {
wire.direction = 'out'
} else {
wire.direction = 'in'
}
}
_editLabel(wire) {
this.context.uiState.openModal(Modals.TEXT_MODAL, {value: wire.name}, e=>{
if (e.confirmed) {
wire.name = e.value
}
})
}
_editType(wire) {
let options = [];
options = options.concat(wire.interfaceDefinition.refsType.map(t=>{
return {
label: t.name,
value: {type: t}
}
}))
if (options.length>0) {
options = options.concat({separator: true})
}
options = options.concat(Object.keys(DataTypes).map(t=>{
return {
label: DataTypes[t],
value: {basicType: t}
}
}))
this.context.uiState.openModal(Modals.CHOICE_MODAL, {options}, e=>{
if (e.confirmed) {
if (e.value.type) {
wire.refType = e.value.type
} else {
wire.basicType = e.value.basicType
}
}
})
}
_openMenu(wire) {
const buttons = {
buttons: [
{glyph: "fa-trash", label: "Delete", command: "delete"},
{glyph: "fa-clone", label: "Clone", command: "clone"}
]
}
this.context.uiState.openModal(Modals.CONTEXT_MENU, buttons, e=>{
if (e.confirmed) {
if (e.command==="delete") {
wire.delete()
} else if (e.command==="clone") {
wire.clone()
}
}
})
}
}
|
packages/lore-tutorial/templates/es6/step15/src/components/CreateDialog.js | lore/lore | import React from 'react';
import ReactDOM from 'react-dom';
export default class CreateDialog extends React.Component {
componentDidMount() {
this.show();
}
show() {
const node = ReactDOM.findDOMNode(this);
$(node).modal('show');
}
render () {
return (
<div className="modal fade" tabIndex="-1" role="dialog">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 className="modal-title">Modal title</h4>
</div>
<div className="modal-body">
<p>One fine body…</p>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" className="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
);
}
}
|
src/client/components/SearchBoxWidget/SearchBoxWidget.js | vidaaudrey/trippian | import log from '../../log'
import React from 'react'
import {
defineMessages, intlShape, injectIntl
}
from 'react-intl'
import Geosuggest from 'react-geosuggest'
import {
AutoSuggestBoxWidget
}
from '../index'
import store from '../../redux/store'
import {
SearchBoxWidget as appConfig
}
from '../../config/appConfig'
const messages = defineMessages({
searchButtonText: {
id: 'search-box-widget.search-button-text',
description: 'text for the search button',
defaultMessage: appConfig.searchButtonText
},
searchInputPlaceHolder: {
id: 'search-box-widget.search-input-place-holder',
description: 'text for the search input placeholder',
defaultMessage: appConfig.placeholderText
}
})
class SearchBoxWidget extends React.Component {
constructor(props) {
super(props)
}
componentDidMount() {
// Elliot is going to do something
}
handleClick() {
const search = store.getState().appState.get('searchText')
const searchText = search.label
log.info('search clicked', search, searchText)
// FIX: pushState will reload the page, it seems to be a problem working in progress: https://github.com/rackt/history/issues/105
store.getState().appState.get('history').pushState({
state: searchText
}, `destination/search/${searchText}`)
// this.props.history.pushState({
// searchText: searchText
// }, `destination/search/${searchText}`)
}
render() {
const {
formatMessage
} = this.props.intl
return (
<form className = {`search-box-widget form-inline ${this.props.className}`} role = "form" onSubmit={this.handleClick.bind(this)}>
<div className = "form-group" >
<label className = "sr-only" > search for destinations < /label>
<AutoSuggestBoxWidget />
</div>
<button type = "submit" onClick={this.handleClick.bind(this)} className = "btn btn-primary" >
{formatMessage(messages.searchButtonText)}
</button>
</form>
)
}
}
SearchBoxWidget.propTypes = {
intl: intlShape.isRequired,
name: React.PropTypes.string
// history: React.PropTypes.object.isRequired
}
SearchBoxWidget.displayName = 'SearchBoxWidget'
export default injectIntl(SearchBoxWidget)
|
src/components/Navigation.js | zebras-filming-videos/streamr-web | import React from 'react'
import ProfilePreviewContainer from './auth/ProfilePreviewContainer'
import { NavLink } from 'react-router-dom'
export default ({
isSignedIn
}) => (
<nav role='main'>
<ul>
<li>
<NavLink exact to='/'>Explore</NavLink>
</li>
{
(isSignedIn) ? (
<li className='record'>
<NavLink to='/record'>Record</NavLink>
</li>
) : (
<li>
<NavLink to='/login'>Log In</NavLink>
</li>
)
}
{showUserOrSignUp(isSignedIn)}
</ul>
</nav>
)
function showUserOrSignUp (isSignedIn) {
if (isSignedIn) {
return <ProfilePreviewContainer />
} else {
return (
<li>
<NavLink to='/signup'>Sign up</NavLink>
</li>
)
}
}
|
template/app/views/Home/Handler.js | thomasboyt/earthling | import React from 'react';
import {connect} from 'react-redux';
import {updateText} from '../../actions/ExampleActions';
const Home = React.createClass({
requestUpdateText() {
this.props.dispatch(updateText('hello redux'));
},
render() {
return (
<div>
<p>{this.props.text}</p>
<button onClick={this.requestUpdateText}>update</button>
<p>press ctrl+h to toggle devtools</p>
</div>
);
}
});
function select(state) {
return {
text: state.example.text
};
}
export default connect(select)(Home);
|
fields/types/color/ColorField.js | giovanniRodighiero/cms | import { SketchPicker } from 'react-color';
import { css } from 'glamor';
import Field from '../Field';
import React from 'react';
import {
Button,
FormInput,
InlineGroup as Group,
InlineGroupSection as Section,
} from '../../../admin/client/App/elemental';
import transparentSwatch from './transparent-swatch';
import theme from '../../../admin/client/theme';
const ColorField = Field.create({
displayName: 'ColorField',
statics: {
type: 'Color',
},
propTypes: {
onChange: React.PropTypes.func,
path: React.PropTypes.string,
value: React.PropTypes.string,
},
getInitialState () {
return {
displayColorPicker: false,
};
},
updateValue (value) {
this.props.onChange({
path: this.props.path,
value: value,
});
},
handleInputChange (event) {
var newValue = event.target.value;
if (/^([0-9A-F]{3}){1,2}$/.test(newValue)) {
newValue = '#' + newValue;
}
if (newValue === this.props.value) return;
this.updateValue(newValue);
},
handleClick () {
this.setState({ displayColorPicker: !this.state.displayColorPicker });
},
handleClose () {
this.setState({ displayColorPicker: false });
},
handlePickerChange (color) {
var newValue = color.hex;
if (newValue === this.props.value) return;
this.updateValue(newValue);
},
renderSwatch () {
const className = `${css(classes.swatch)} e2e-type-color__swatch`;
return (this.props.value) ? (
<span
className={className}
style={{ backgroundColor: this.props.value }}
/>
) : (
<span
className={className}
dangerouslySetInnerHTML={{ __html: transparentSwatch }}
/>
);
},
renderField () {
const { displayColorPicker } = this.state;
return (
<div className="e2e-type-color__wrapper" style={{ position: 'relative' }}>
<Group>
<Section grow>
<FormInput
autoComplete="off"
name={this.getInputName(this.props.path)}
onChange={this.valueChanged}
ref="field"
value={this.props.value}
/>
</Section>
<Section>
<Button onClick={this.handleClick} aphroditeStyles={classes.button} data-e2e-type-color__button>
{this.renderSwatch()}
</Button>
</Section>
</Group>
{displayColorPicker && (
<div>
<div
className={css(classes.blockout)}
data-e2e-type-color__blockout
onClick={this.handleClose}
/>
<div className={css(classes.popover)} onClick={e => e.stopPropagation()} data-e2e-type-color__popover>
<SketchPicker
color={this.props.value}
onChangeComplete={this.handlePickerChange}
onClose={this.handleClose}
/>
</div>
</div>
)}
</div>
);
},
});
/* eslint quote-props: ["error", "as-needed"] */
const classes = {
button: {
background: 'white',
padding: 4,
width: theme.component.height,
':hover': {
background: 'white',
},
},
blockout: {
bottom: 0,
left: 0,
position: 'fixed',
right: 0,
top: 0,
zIndex: 1,
},
popover: {
marginTop: 10,
position: 'absolute',
left: 0,
zIndex: 2,
},
swatch: {
borderRadius: 1,
boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.1)',
display: 'block',
height: '100%',
width: '100%',
},
};
module.exports = ColorField;
|
src/components/Footer.js | jonniebigodes/freecodecampApiChallenges | import React from 'react'
import '../Assets/styleSheets/base.scss'
const Footer = () => (
<footer className="footerstyle">
<div className="footerText">
Made by{' '}
<a
href="https://www.freecodecamp.com/jonniebigodes"
target="_noopener"
rel="nofollow">
Jonniebigodes
</a>
</div>
<div className="footerText">
Github repository:{' '}
<a
href="https://github.com/jonniebigodes/freecodecampApiChallenges"
target="_noopener"
rel="nofollow">
Data Visualization Challenges
</a>
</div>
</footer>
)
export default Footer
|
src/components/togglecheckbox/Togglecheckbox.js | Convicted202/PixelShape | import './togglecheckbox.styl';
import React, { Component } from 'react';
import classNames from 'classnames';
// this is needed to reference input from label
// so we will increase it in constructor to keep unique
let id = 0;
class ToggleCheckbox extends Component {
constructor (...props) {
id++;
super(...props);
this.state = { id };
}
render () {
const classes = classNames(
'togglecheckbox',
this.props.className
);
return (
<div className={classes}>
<input
className="togglecheckbox-checkbox"
type="checkbox"
id={`togglecheckbox-${this.state.id}`}
checked={this.props.value}
onChange={this.props.onChange} />
<label className="togglecheckbox-checkbox__switch" htmlFor={`togglecheckbox-${this.state.id}`} />
<span className="togglecheckbox-checkbox__text">{this.props.children}</span>
</div>
);
}
}
export default ToggleCheckbox;
|
src/index.js | blurbyte/money-fetch | // required for redux-saga generatos
import 'regenerator-runtime/runtime';
/* eslint-disable import/default */
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { persistStore } from 'redux-persist';
import createCompressor from 'redux-persist-transform-compress';
import App from './containers/App';
// styles reset
import 'sanitize.css/sanitize.css';
// redux store
import configureStore from './store';
// es6 promises polyfill
import Promise from 'promise-polyfill';
if (!window.Promise) {
window.Promise = Promise;
}
// load favicon & manifest.json
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json'; // eslint-disable-line import/extensions
// custom global styles
import './styles/globalStyles';
const initialState = {};
const store = configureStore(initialState);
// persisting the store with compression
const compressor = createCompressor({ whitelist: ['currencies'] });
persistStore(store, { transforms: [compressor] });
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
);
// install ServiceWorker
if (process.env.NODE_ENV === 'production') {
require('offline-plugin/runtime').install();
}
|
app/components/Button.js | live106/todo-for-react-native | import React from 'react';
import PropTypes from 'prop-types';
import {
Text,
TouchableHighlight
} from 'react-native';
import { themable } from '../themes';
const Button = (props) => {
const {
style,
underlayColor,
btnTextStyle,
disabledStyle,
disabled,
children,
onPress
} = props;
const btnStyles = [style];
if (disabled) btnStyles.push(disabledStyle);
return (
<TouchableHighlight
onPress={ onPress }
style={ btnStyles }
underlayColor={ underlayColor }
activeOpacity={1}>
<Text style={ btnTextStyle }>{ children }</Text>
</TouchableHighlight>
);
};
const ThemableButton = themable(Button, (theme) => {
const { styles, variables } = theme;
return {
style: styles.button,
btnTextStyle: styles.buttonText,
underlayColor: variables.colorMain,
disabledStyle: styles.buttonDisabled
};
});
ThemableButton.propTypes = {
onPress: PropTypes.func.isRequired
};
export default ThemableButton;
|
src/page/todo/index.js | xincyang/webpack-demo | import 'react-hot-loader/patch';
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import App from './components/App.js'
import configureStore from './store/configureStore.js'
import { AppContainer } from 'react-hot-loader'
let store = configureStore()
const renderDOM = Component => {
render(
<AppContainer>
<Provider store={store}>
<Component />
</Provider>
</AppContainer>,
document.getElementById('root')
)
}
renderDOM(App)
if (module.hot) {
module.hot.accept('./components/App.js', () => {
renderDOM(App)
})
}
|
local-cli/templates/HelloWorld/index.android.js | gilesvangruisen/react-native | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class HelloWorld extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
|
imports/ui/components/home/HomeGetStarted/HomeGetStarted.js | pletcher/cltk_frontend | import React from 'react';
import WorksList from '/imports/ui/components/works/WorksList';
class HomeGetStarted extends React.Component {
render() {
return (
<section id="get-started" className="bg-gray" >
<div className="container text-center">
<div className="row">
<h2 className="section-title">Get Started </h2>
<hr className="section-header-line" />
<h4 className="uppercase" >
Browse the authors, poets, and historians in the archive
</h4>
</div>
</div>
<WorksList
limit={15}
/>
<div className="container text-center">
<div className="row">
<a
className="waves-effect waves-light btn-large"
aria-label="View more"
href="/browse"
>
View more
</a>
</div>
</div>
</section>
);
}
}
export default HomeGetStarted;
|
src/components/Button.js | nitrog7/nl-fluid | import React from 'react';
import Component from './Component';
import Icon from './Icon';
import _ from 'lodash';
export default class Button extends Component {
static propTypes() {
return {
children: React.PropTypes.object,
ghost: React.PropTypes.bool,
loader: React.PropTypes.string,
isLoading: React.PropTypes.bool,
prefix: React.PropTypes.string,
status: React.PropTypes.string,
suffix: React.PropTypes.string,
type: React.PropTypes.string
};
}
static get defaultProps() {
return {
ghost: false,
loader: 'spinner5',
isLoading: false,
prefix: '',
status: '',
suffix: '',
type: 'default'
};
}
constructor(props) {
super(props, 'btn');
// Check if button is loading
let loadObj = this.chkLoading(props);
// Set initial state
this.state = {
isLoading: this.props.isLoading,
prefix: loadObj.prefix || this.props.prefix,
suffix: loadObj.suffix || this.props.suffix,
prefixOrg: this.props.prefix,
suffixOrg: this.props.suffix
};
}
componentWillReceiveProps(props) {
let {prefix, suffix} = this.chkLoading(props);
this.setState({
isLoading: props.isLoading,
prefix,
suffix
});
}
addStyles() {
let cls = [];
switch (this.props.type) {
case 'primary':
cls.push('btn-primary');
break;
case 'secondary':
cls.push('btn-secondary');
break;
case 'link':
cls.push('btn-link');
break;
default:
cls.push('btn-default');
break;
}
switch (this.props.status) {
case 'success':
cls.push('btn-success');
break;
case 'warning':
cls.push('btn-warning');
break;
case 'danger':
cls.push('btn-danger');
break;
}
if(this.props.ghost) {
cls.push('btn-ghost');
}
if(this.props.prefix !== '') {
cls.push('btn-has-prefix');
}
if(this.props.suffix !== '') {
cls.push('btn-has-suffix');
}
if(this.props.isLoading) {
cls.push('btn-is-loading');
}
return cls;
}
getIcon(type) {
let icon;
if(this.state[type] !== '') {
icon = <Icon className={`btn_${type}`} name={this.state[type]} />;
}
return icon;
}
chkLoading(props) {
let prefix = '';
let suffix = '';
if(props.isLoading) {
if(props.prefix !== '') {
prefix = props.loader;
}
if(props.suffix !== '') {
suffix = props.loader;
}
} else {
if(this.state.prefixOrg) {
prefix = this.state.prefixOrg;
}
if(this.state.suffixOrg) {
suffix = this.state.suffixOrg;
}
}
return {prefix, suffix};
}
render() {
let props = _.omit(this.props, ['type', 'status', 'children']);
return (
<button className={this.getStyles()} {...props}>
{this.getIcon('prefix')}
{this.props.children}
{this.getIcon('suffix')}
</button>
);
}
}
|
app/app.js | Luandro-com/repsparta-web-app | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
import 'babel-polyfill';
// TODO constrain eslint import/no-unresolved rule to this block
// Load the manifest.json file and the .htaccess file
import 'file?name=[name].[ext]!./manifest.json'; // eslint-disable-line import/no-unresolved
import 'file?name=[name].[ext]!./.htaccess'; // eslint-disable-line import/no-unresolved
// 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 configureStore from './store';
import { StyleRoot } from 'radium';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
const muiTheme = getMuiTheme({
palette: {
primary1Color: '#EC1D24',
primary2Color: '#24358A',
// primary3Color: grey400,
accent1Color: '#EC1D24',
accent2Color: 'orange',
accent3Color: 'orange',
// textColor: darkBlack,
// alternateTextColor: white,
canvasColor: '#fff',
// borderColor: grey300,
// disabledColor: fade(darkBlack, 0.3),
// pickerHeaderColor: cyan500,
// clockCircleColor: fade(darkBlack, 0.07),
// shadowColor: fullBlack,
},
});
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
import ga from 'react-ga';
ga.initialize('UA-78747741-1');
// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/lib/sanitize.css';
// 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
import { selectLocationState } from 'containers/App/selectors';
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: selectLocationState(),
});
/**
* Inject Lightbox
*/
import { lightboxLoaded } from 'containers/Store/actions'
const script = document.createElement('script');
script.src = 'https://stc.pagseguro.uol.com.br/pagseguro/api/v2/checkout/pagseguro.lightbox.js';
script.onload = function () {
console.log('PagSeguro lightbox is loaded');
store.dispatch(lightboxLoaded())
};
document.head.appendChild(script); //or something of the likes
// Set up the router, wrapping all Routes in the App component
import App from 'containers/App';
import createRoutes from './routes';
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
ReactDOM.render(
<Provider store={store}>
<MuiThemeProvider muiTheme={muiTheme}>
<StyleRoot>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(
useScroll(
(prevProps, props) => {
if (!prevProps || !props) {
return true;
}
if (prevProps.location.pathname !== props.location.pathname) {
return [0, 0];
}
return true;
}
)
)
}
/>
</StyleRoot>
</MuiThemeProvider>
</Provider>,
document.getElementById('app')
);
// 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
import { install } from 'offline-plugin/runtime';
install();
|
client/components/UserStatus/Busy.js | VoiSmart/Rocket.Chat | import React from 'react';
import UserStatus from './UserStatus';
const Busy = (props) => <UserStatus status='busy' {...props} />;
export default Busy;
|
src/svg-icons/hardware/tablet-mac.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareTabletMac = (props) => (
<SvgIcon {...props}>
<path d="M18.5 0h-14C3.12 0 2 1.12 2 2.5v19C2 22.88 3.12 24 4.5 24h14c1.38 0 2.5-1.12 2.5-2.5v-19C21 1.12 19.88 0 18.5 0zm-7 23c-.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.5zm7.5-4H4V3h15v16z"/>
</SvgIcon>
);
HardwareTabletMac = pure(HardwareTabletMac);
HardwareTabletMac.displayName = 'HardwareTabletMac';
HardwareTabletMac.muiName = 'SvgIcon';
export default HardwareTabletMac;
|
frontend/react/pages/IndexPage.js | Dishant15/TechIntrest | import React from 'react';
import {Link} from 'react-router';
import {connect} from 'react-redux';
import {loadPinList} from '../actions/pinActions';
import BlockGrid from '../components/BlockGrid';
@connect((store) => {
return {
fetching: store.pinList.fetching,
fetched : store.pinList.fetched,
pins : store.pinList.pins,
};
})
export default class IndexPage extends React.Component {
componentWillMount(){
this.props.dispatch(loadPinList('/api/pin/all/'))
}
render(){
return(
<div style={{textAlign:'center'}}>
<div class="container" >
<h2 class="heading">Best Tech Pins, All at one place</h2>
{this.props.fetched &&
<BlockGrid data={this.props.pins} />
}
{this.props.fetching &&
<h1 class='text-center'>Loading...</h1>
}
</div>
</div>
)
}
} |
public/javascripts/bower/react-tray/lib/components/Tray.js | HotChalk/canvas-lms | import React from 'react';
import ReactDOM from 'react-dom';
import TrayPortal from './TrayPortal';
import { a11yFunction } from '../helpers/customPropTypes';
const renderSubtreeIntoContainer = ReactDOM.unstable_renderSubtreeIntoContainer;
export default React.createClass({
displayName: 'Tray',
propTypes: {
isOpen: React.PropTypes.bool,
onBlur: React.PropTypes.func,
onOpen: React.PropTypes.func,
closeTimeoutMS: React.PropTypes.number,
closeOnBlur: React.PropTypes.bool,
maintainFocus: React.PropTypes.bool,
getElementToFocus: a11yFunction,
getAriaHideElement: a11yFunction
},
getDefaultProps() {
return {
isOpen: false,
closeTimeoutMS: 0,
closeOnBlur: true,
maintainFocus: true
};
},
componentDidMount() {
this.node = document.createElement('div');
this.node.className = 'ReactTrayPortal';
document.body.appendChild(this.node);
this.renderPortal(this.props);
},
componentWillReceiveProps(props) {
this.renderPortal(props);
},
componentWillUnmount() {
ReactDOM.unmountComponentAtNode(this.node);
document.body.removeChild(this.node);
},
renderPortal(props) {
delete props.ref;
renderSubtreeIntoContainer(this, <TrayPortal {...props}/>, this.node);
},
render() {
return null;
}
});
|
examples/styling/radium/src/components/Profile/index.js | carteb/carte-blanche | import React, { Component } from 'react';
const styles = {};
class Profile extends Component {
static propTypes = {
avatarUrl: React.PropTypes.string.isRequired,
firstName: React.PropTypes.string.isRequired,
lastName: React.PropTypes.string,
username: React.PropTypes.string.isRequired,
bio: React.PropTypes.string,
};
onAddFriend = () => {
alert(`Add @${this.props.username} as a friend`); // eslint-disable-line no-alert
};
render() {
return (
<div style={styles.card}>
<div style={styles.row}>
<img
style={styles.avatar}
src={this.props.avatarUrl}
alt={`${this.props.firstName} ${this.props.lastName}`}
/>
<div style={styles.information}>
<h1 style={styles.name}>
{this.props.firstName}{(this.props.lastName) ? (` ${this.props.lastName}`) : null}
</h1>
<h2 style={styles.username}>@{this.props.username}</h2>
</div>
</div>
<p style={styles.paragraph}>{this.props.bio}</p>
<div style={styles.buttonWrapper}>
</div>
</div>
);
}
}
export default Profile;
|
src/Label.js | JimiHFord/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const Label = React.createClass({
mixins: [BootstrapMixin],
getDefaultProps() {
return {
bsClass: 'label',
bsStyle: 'default'
};
},
render() {
let classes = this.getBsClassSet();
return (
<span {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</span>
);
}
});
export default Label;
|
client/src/Requests/RequestsPage.js | clembou/github-requests | import React from 'react';
import _ from 'lodash';
import { Grid, PageHeader, ListGroup, Panel } from 'react-bootstrap';
import { Route, Switch, Link } from 'react-router-dom';
import Requests from './Requests';
const findProject = (projects, params) => {
return _.find(projects, p => p.organisation === params.organisation && p.repository === params.repo && p.label === params.label) || {};
};
const RequestsPage = ({ match, ...rest }) => rest.projects.length > 0 &&
<div>
<Switch>
<Route
path={`${match.path}/:organisation/:repo/:label`}
render={props => (
<Requests
key={`${match.path}/:organisation/:repo/:label`}
{...props}
isAdmin={rest.isAdmin}
userProfile={rest.userProfile}
project={findProject(rest.projects, props.match.params)}
/>
)}
/>
<Route
render={props => (
<RequestsPageHome
{...props}
isAdmin={rest.isAdmin}
userProfile={rest.userProfile}
projects={rest.projects}
groups={rest.groups}
/>
)}
/>
</Switch>
</div>;
export default RequestsPage;
const RequestsPageHome = props => (
<Grid>
<PageHeader>Please select a project: </PageHeader>
{props.groups.length > 0 &&
props.groups.map(pg => (
<ProjectGroup
key={pg.name}
name={pg.name}
description={pg.description}
projects={props.projects.filter(p => _.includes(p.groups, pg.key))}
/>
))}
</Grid>
);
const ProjectGroup = props => (
<Panel collapsible defaultExpanded header={props.name}>
{props.description && props.description}
<ListGroup fill>
{props.projects.map(p => (
<Link key={p.label} to={`/requests/${p.organisation}/${p.repository}/${p.label}`} className="list-group-item">
{p.name}
</Link>
))}
</ListGroup>
</Panel>
);
|
src/interface/icons/Mastery.js | sMteX/WoWAnalyzer | import React from 'react';
const icon = props => (
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="16 16 32 32" className="icon" {...props}>
<path d="M46.934,26.287c-1.107,0-2.004,0.885-2.004,1.976c0,0.31,0.079,0.599,0.208,0.861l-6.74,4.691 l-0.387-8.422c1.064-0.048,1.914-0.906,1.914-1.967c0-1.091-0.898-1.976-2.005-1.976c-1.107,0-2.004,0.885-2.004,1.976 c0,0.732,0.408,1.364,1.008,1.705l-4.812,8.237l-4.812-8.237c0.6-0.341,1.008-0.973,1.008-1.705c0-1.091-0.897-1.976-2.004-1.976 c-1.107,0-2.004,0.885-2.004,1.976c0,1.061,0.85,1.919,1.914,1.967l-0.387,8.422l-6.74-4.691c0.129-0.261,0.208-0.551,0.208-0.861 c0-1.092-0.897-1.976-2.005-1.976c-1.107,0-2.004,0.885-2.004,1.976c0,1.091,0.897,1.976,2.004,1.976 c0.298,0,0.578-0.068,0.832-0.183l5.048,13.236c2.178-0.849,5.377-1.385,8.943-1.385c3.566,0,6.764,0.536,8.942,1.385l5.048-13.236 c0.254,0.115,0.534,0.183,0.832,0.183c1.107,0,2.005-0.885,2.005-1.976C48.939,27.172,48.041,26.287,46.934,26.287z" />
</svg>
);
export default icon;
|
examples/async/index.js | arusakov/redux | import 'babel-core/polyfill';
import React from 'react';
import { Provider } from 'react-redux';
import App from './containers/App';
import configureStore from './store/configureStore';
const store = configureStore();
React.render(
<Provider store={store}>
{() => <App />}
</Provider>,
document.getElementById('root')
);
|
demo/components/ButtonToolbar.js | redux-autoform/redux-autoform | import React from 'react';
import { bool, array } from 'prop-types';
export default class ButtonToolbar extends React.Component {
static propTypes = {
pristine: bool.isRequired,
submitting: bool.isRequired,
errors: array.isRequired
};
render() {
const { pristine, submitting, errors } = this.props;
const disabled = !!(pristine || errors.length > 0 || submitting);
return (
<div>
<button type="submit" disabled={disabled}>Submit</button>
</div>
);
}
} |
demo/index.js | thoqbk/recharts | import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import App from './container/App';
ReactDOM.render((
<Router history={browserHistory}>
<Route path="/" component={App} />
</Router>
), document.getElementById('root'));
|
fields/types/text/TextFilter.js | brianjd/keystone | import React from 'react';
import { findDOMNode } from 'react-dom';
import {
FormField,
FormInput,
FormSelect,
SegmentedControl,
} from '../../../admin/client/App/elemental';
const INVERTED_OPTIONS = [
{ label: 'Matches', value: false },
{ label: 'Does NOT Match', value: true },
];
const MODE_OPTIONS = [
{ label: 'Contains', value: 'contains' },
{ label: 'Exactly', value: 'exactly' },
{ label: 'Begins with', value: 'beginsWith' },
{ label: 'Ends with', value: 'endsWith' },
];
function getDefaultValue () {
return {
mode: MODE_OPTIONS[0].value,
inverted: INVERTED_OPTIONS[0].value,
value: '',
};
}
var TextFilter = React.createClass({
propTypes: {
filter: React.PropTypes.shape({
mode: React.PropTypes.oneOf(MODE_OPTIONS.map(i => i.value)),
inverted: React.PropTypes.boolean,
value: React.PropTypes.string,
}),
},
statics: {
getDefaultValue: getDefaultValue,
},
getDefaultProps () {
return {
filter: getDefaultValue(),
};
},
updateFilter (value) {
this.props.onChange({ ...this.props.filter, ...value });
},
selectMode (e) {
const mode = e.target.value;
this.updateFilter({ mode });
findDOMNode(this.refs.focusTarget).focus();
},
toggleInverted (inverted) {
this.updateFilter({ inverted });
findDOMNode(this.refs.focusTarget).focus();
},
updateValue (e) {
this.updateFilter({ value: e.target.value });
},
render () {
const { field, filter } = this.props;
const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0];
const placeholder = field.label + ' ' + mode.label.toLowerCase() + '...';
return (
<div>
<FormField>
<SegmentedControl
equalWidthSegments
onChange={this.toggleInverted}
options={INVERTED_OPTIONS}
value={filter.inverted}
/>
</FormField>
<FormField>
<FormSelect
onChange={this.selectMode}
options={MODE_OPTIONS}
value={mode.value}
/>
</FormField>
<FormInput
autoFocus
onChange={this.updateValue}
placeholder={placeholder}
ref="focusTarget"
value={this.props.filter.value}
/>
</div>
);
},
});
module.exports = TextFilter;
|
src/svg-icons/maps/local-pizza.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalPizza = (props) => (
<SvgIcon {...props}>
<path d="M12 2C8.43 2 5.23 3.54 3.01 6L12 22l8.99-16C18.78 3.55 15.57 2 12 2zM7 7c0-1.1.9-2 2-2s2 .9 2 2-.9 2-2 2-2-.9-2-2zm5 8c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>
</SvgIcon>
);
MapsLocalPizza = pure(MapsLocalPizza);
MapsLocalPizza.displayName = 'MapsLocalPizza';
MapsLocalPizza.muiName = 'SvgIcon';
export default MapsLocalPizza;
|
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/node_modules/antd/es/popover/index.js | bhathiya/test | import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import Tooltip from '../tooltip';
import warning from '../_util/warning';
var Popover = function (_React$Component) {
_inherits(Popover, _React$Component);
function Popover() {
_classCallCheck(this, Popover);
return _possibleConstructorReturn(this, (Popover.__proto__ || Object.getPrototypeOf(Popover)).apply(this, arguments));
}
_createClass(Popover, [{
key: 'getPopupDomNode',
value: function getPopupDomNode() {
return this.refs.tooltip.getPopupDomNode();
}
}, {
key: 'getOverlay',
value: function getOverlay() {
var _props = this.props,
title = _props.title,
prefixCls = _props.prefixCls,
content = _props.content;
warning(!('overlay' in this.props), 'Popover[overlay] is removed, please use Popover[content] instead, ' + 'see: http://u.ant.design/popover-content');
return React.createElement(
'div',
null,
title && React.createElement(
'div',
{ className: prefixCls + '-title' },
title
),
React.createElement(
'div',
{ className: prefixCls + '-inner-content' },
content
)
);
}
}, {
key: 'render',
value: function render() {
var props = _extends({}, this.props);
delete props.title;
return React.createElement(Tooltip, _extends({}, props, { ref: 'tooltip', overlay: this.getOverlay() }));
}
}]);
return Popover;
}(React.Component);
export default Popover;
Popover.defaultProps = {
prefixCls: 'ant-popover',
placement: 'top',
transitionName: 'zoom-big',
trigger: 'hover',
mouseEnterDelay: 0.1,
mouseLeaveDelay: 0.1,
overlayStyle: {}
}; |
src/svg-icons/device/bluetooth-searching.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBluetoothSearching = (props) => (
<SvgIcon {...props}>
<path d="M14.24 12.01l2.32 2.32c.28-.72.44-1.51.44-2.33 0-.82-.16-1.59-.43-2.31l-2.33 2.32zm5.29-5.3l-1.26 1.26c.63 1.21.98 2.57.98 4.02s-.36 2.82-.98 4.02l1.2 1.2c.97-1.54 1.54-3.36 1.54-5.31-.01-1.89-.55-3.67-1.48-5.19zm-3.82 1L10 2H9v7.59L4.41 5 3 6.41 8.59 12 3 17.59 4.41 19 9 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM11 5.83l1.88 1.88L11 9.59V5.83zm1.88 10.46L11 18.17v-3.76l1.88 1.88z"/>
</SvgIcon>
);
DeviceBluetoothSearching = pure(DeviceBluetoothSearching);
DeviceBluetoothSearching.displayName = 'DeviceBluetoothSearching';
DeviceBluetoothSearching.muiName = 'SvgIcon';
export default DeviceBluetoothSearching;
|
src/client/assets/js/nodes/outputs/export/node.js | me-box/platform-sdk | import React from 'react';
//import composeNode from 'utils/composeNode';
import Textfield from 'components/form/Textfield';
import Select from 'components/form/Select';
import Cell from 'components/Cell';
import Cells from 'components/Cells';
import { formatSchema } from 'utils/utils';
import {configNode} from 'utils/ReactDecorators';
@configNode()
export default class Node extends React.Component {
render() {
const {node,values={},updateNode} = this.props;
const nameprops = {
id: "name",
value: values.name || "",
onChange: (property, event)=>{
updateNode("name", event.target.value);
},
}
const urlsprops = {
id: "urls",
value: values.urls || "",
onChange: (property, event)=>{
updateNode("urls", event.target.value.trim());
},
}
const nameinput = <div className="centered"><Textfield {...nameprops}/></div>
const urlsinput = <div className="centered"><Textfield {...urlsprops}/></div>
return <div>
<Cells>
<Cell title={"name"} content={nameinput}/>
<Cell title={"urls"} content={urlsinput}/>
</Cells>
</div>
}
} |
frontend/modules/recipe_form/components/IngredientBox.js | rustymyers/OpenEats | import React from 'react'
import {
injectIntl,
defineMessages,
} from 'react-intl';
import { TextArea } from '../../common/components/FormComponents'
import IngredientGroups from '../../recipe/components/IngredientGroups'
import TabbedView from './TabbedView'
class IngredientBox extends React.Component {
constructor(props) {
super(props);
this.state = {
data: this.props.data || [],
text: this.unarrayify(this.props.data || []),
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.id != this.props.id) {
this.setState({
data: nextProps.data || [],
text: this.unarrayify(nextProps.data || []),
});
}
}
unarrayify = value => {
let tr = '';
if (value) {
value.map(ig => {
if (ig.title) {
tr += ig.title + ':\n';
}
ig.ingredients.map(i => {
tr += i.quantity ? i.quantity + " " : '';
tr += i.measurement ? i.measurement + " " : '';
tr += i.title + '\n'
});
tr += '\n';
});
}
if (tr.length > 3) {
return tr.substring(0, tr.length - 2);
}
return tr;
};
arrayify = value => {
let dict = [{title: '', ingredients: []}];
let igTitle = '';
let ings = dict.find(t => t.title === '').ingredients;
if (value) {
let tags = value.split('\n').filter(t => t.trim().length > 1);
for (let index in tags) {
let line = tags[index].trim();
if (line.length > 0) {
// Check if the line is an IG title
// If line is IG title, update igTitle and continue
// Else add ing to the current ig group
if (line.includes(':') && line.length > 1) {
igTitle = line.substring(0, line.length - 1);
dict.push({title: igTitle, ingredients: []});
ings = dict.find(t => t.title === igTitle).ingredients;
} else {
let tags = line.split(' ');
if (tags.length === 1) {
ings.push({ title: line });
} else if (tags.length === 2) {
if (!(isNaN(tags[0]))) {
ings.push({ quantity: tags[0], title: tags[1] })
} else {
ings.push({ title: line });
}
} else {
if (!(isNaN(tags[0]))) {
let quantity = tags.splice(0,1)[0];
let measurement = tags.splice(0,1)[0];
ings.push({
quantity: quantity,
measurement: measurement,
title: tags.join(' ')
});
} else {
ings.push({ title: line });
}
}
}
}
}
}
return dict
};
handleChange = (key, value) => {
this.setState({
data: this.arrayify(value),
text: value
});
if(this.props.change) {
this.props.change(key, this.arrayify(value));
}
};
render() {
const { formatMessage } = this.props.intl;
const messages = defineMessages({
info_title: {
id: 'recipe.create.ing.info_title',
description: 'info_title',
defaultMessage: 'Ingredient Help',
},
info_desc: {
id: 'recipe.create.ing.info_desc',
description: 'info_desc',
defaultMessage: 'Each Ingredient should be only its own line. Click the Preview to see what the Ingredients will look like.',
},
});
const help = {
infoTitle: formatMessage(messages.info_title),
infoDesc: formatMessage(messages.info_desc)
};
return (
<TabbedView { ...{...this.props, ...help} }>
<TextArea
name={ this.props.name }
rows="8"
change={ this.handleChange }
value={ this.state.text }
/>
<div className="recipe-details">
<div className="recipe-schema">
<IngredientGroups data={ this.state.data }/>
</div>
</div>
</TabbedView>
)
}
}
export default injectIntl(IngredientBox)
|
src/components/Gdzc/StatByYear.js | nagucc/jkef-web-react | 'use strict';
import React from 'react';
import accounting from 'accounting';
import {Bar} from 'react-chartjs'
import * as actions from '../../redux/actions/gdzc';
class StatByYear extends React.Component {
componentWillReceiveProps(nextProps) {
// 历年购入资产金额表
let ctx = document.getElementById("yearAmountStat").getContext("2d");
new Chart(ctx).Bar(nextProps.yearAmountByYearBarData);
// document.getElementById("yearAmountStat").onclick = function(evt) {
// // console.log('active::::', barAmount.getBarsAtEvent(evt));
// }
// 历年购入资产数量统计
let ctxYearCount = document.getElementById("yearCountStat").getContext("2d");
new Chart(ctxYearCount).Bar(nextProps.yearCountBarData);
// 历年购入大型设备金额统计
ctx = document.getElementById("dxsbAmount").getContext("2d");
new Chart(ctx).Bar(nextProps.dxsbAmountBarData);
// 历年购入大型设备数量统计
ctx = document.getElementById("dxsbCount").getContext("2d");
new Chart(ctx).Bar(nextProps.dxsbCountBarData);
// 历年待报废资产金额统计
ctx = document.getElementById("scrapingAmount").getContext("2d");
new Chart(ctx).Bar(nextProps.scrapingAmountBarData);
// 历年待报废资产数量统计
ctx = document.getElementById("scrapingCount").getContext("2d");
new Chart(ctx).Bar(nextProps.scrapingCountBarData);
}
componentDidMount() {
Chart.defaults.global.responsive = true;
this.props.dispatch(actions.fetchStatByYear());
}
render() {
return (
<div className="row">
<h3 className="header blue smaller">年度统计</h3>
<div className="col-xs-12">
<div className="widget-box">
<div className="widget-header widget-header-flat widget-header-small">
<h5 className="widget-title">
<i className="ace-icon fa fa-signal"></i>
购入资产原值(单位:元)
</h5>
</div>
<div className="widget-body">
<div className="widget-main">
<canvas id="yearAmountStat" ></canvas>
</div>
</div>
</div>
</div>
<div className="col-xs-12">
<div className="widget-box">
<div className="widget-header widget-header-flat widget-header-small">
<h5 className="widget-title">
<i className="ace-icon fa fa-signal"></i>
购入资产数量(单位:项)
</h5>
</div>
<div className="widget-body">
<div className="widget-main">
<canvas id="yearCountStat" ></canvas>
</div>
</div>
</div>
</div>
<div className="col-xs-12">
<div className="widget-box">
<div className="widget-header widget-header-flat widget-header-small">
<h5 className="widget-title">
<i className="ace-icon fa fa-signal"></i>
大型设备金额(单位:元)
</h5>
</div>
<div className="widget-body">
<div className="widget-main">
<canvas id="dxsbAmount" ></canvas>
</div>
</div>
</div>
</div>
<div className="col-xs-12">
<div className="widget-box">
<div className="widget-header widget-header-flat widget-header-small">
<h5 className="widget-title">
<i className="ace-icon fa fa-signal"></i>
大型设备数量(单位:项)
</h5>
</div>
<div className="widget-body">
<div className="widget-main">
<canvas id="dxsbCount" ></canvas>
</div>
</div>
</div>
</div>
<div className="col-xs-12">
<div className="widget-box">
<div className="widget-header widget-header-flat widget-header-small">
<h5 className="widget-title">
<i className="ace-icon fa fa-signal"></i>
待报废资产金额(单位:元)
</h5>
</div>
<div className="widget-body">
<div className="widget-main">
<canvas id="scrapingAmount" ></canvas>
</div>
</div>
</div>
</div>
<div className="col-xs-12">
<div className="widget-box">
<div className="widget-header widget-header-flat widget-header-small">
<h5 className="widget-title">
<i className="ace-icon fa fa-signal"></i>
待报废资产数量(单位:项)
</h5>
</div>
<div className="widget-body">
<div className="widget-main">
<canvas id="scrapingCount" ></canvas>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default StatByYear;
|
src/app/components/App.js | technics/isomorphic-js | 'use strict';
import React from 'react';
/**
* The root component of the application.
*/
class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
/**
* @inheritdoc
* @return {boolean} Whether or not the component should update
*/
shouldComponentUpdate() {
return React.addons.PureRenderMixin.shouldComponentUpdate
.apply(this, arguments);
}
/**
* @inheritdoc
* @return {Component} The component to render
*/
render() {
return (
<div>
<p>Hey there</p>
</div>
);
}
}
App.displayName = 'App';
App.propTypes = {};
export default App;
|
src/svg-icons/image/view-comfy.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageViewComfy = (props) => (
<SvgIcon {...props}>
<path d="M3 9h4V5H3v4zm0 5h4v-4H3v4zm5 0h4v-4H8v4zm5 0h4v-4h-4v4zM8 9h4V5H8v4zm5-4v4h4V5h-4zm5 9h4v-4h-4v4zM3 19h4v-4H3v4zm5 0h4v-4H8v4zm5 0h4v-4h-4v4zm5 0h4v-4h-4v4zm0-14v4h4V5h-4z"/>
</SvgIcon>
);
ImageViewComfy = pure(ImageViewComfy);
ImageViewComfy.displayName = 'ImageViewComfy';
ImageViewComfy.muiName = 'SvgIcon';
export default ImageViewComfy;
|
src/containers/login/require_auth.js | wunderg/react-redux-express-mongo-starter | import React, { Component } from 'react';
import { connect } from 'react-redux';
export default function(ComponentToCompose) {
class Authentication extends Component {
static contextTypes = {
router: React.PropTypes.object
}
componentWillMount() {
if (!this.props.authenticated) {
this.context.router.push('/');
}
}
componentWillReceiveProps(nextProps) {
if (!nextProps.authenticated) {
this.context.router.push('/');
}
}
render() {
return (
<ComponentToCompose {...this.props} />
);
}
}
function mapStateToProps(state) {
return { authenticated: state.user.isAuthenticated }
}
return connect(mapStateToProps)(Authentication);
}
|
frontend/js/components/ecosystems/SurveyCreatorOffices.js | Code4HR/okcandidate-platform | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Card from './../atoms/Card';
class SurveyCreatorOffices extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Card>
<pre>Survey Creator Offices</pre>
</Card>
);
}
}
SurveyCreatorOffices.propTypes = {
offices: PropTypes.object
};
export default SurveyCreatorOffices;
|
examples/files/react/ternaryEvaluation.js | dabbott/react-express | import React from 'react'
import { render } from 'react-dom'
function Card({ title, subtitle }) {
return (
<div style={styles.card}>
<h1 style={styles.title}>{title}</h1>
{subtitle ? (
<h2 style={styles.subtitle}>{subtitle}</h2>
) : (
<h3 style={styles.empty}>No subtitle</h3>
)}
</div>
)
}
function App() {
return (
<div>
<Card title={'Title'} />
<Card title={'Title'} subtitle={'Subtitle'} />
</div>
)
}
const styles = {
card: {
padding: '20px',
margin: '20px',
textAlign: 'center',
color: 'white',
backgroundColor: 'steelblue',
border: '1px solid rgba(0,0,0,0.15)',
},
title: {
fontSize: '18px',
lineHeight: '24px',
},
subtitle: {
fontSize: '14px',
lineHeight: '18px',
},
empty: {
fontSize: '12px',
lineHeight: '15px',
opacity: '0.5',
},
}
render(<App />, document.querySelector('#app'))
|
src/js/index.js | mmagr/gui | import React from 'react';
import ReactDOM from 'react-dom';
import { Router, hashHistory } from 'react-router';
import routes from './routes';
import Gatekeeper from './containers/login/Gatekeeper.js';
import AltContainer from 'alt-container';
import LoginStore from './stores/LoginStore';
// window.$ = require('jquery');
// window.jQuery = require('jquery');
// require ('materialize-css/dist/js/materialize.js');
require ('materialize-css/dist/css/materialize.min.css');
require ('font-awesome/scss/font-awesome.scss');
require ('../sass/app.scss');
function Main(props) {
return (
<Gatekeeper>
<Router routes={routes} history={hashHistory} />
</Gatekeeper>
)
}
ReactDOM.render(<Main/>, document.getElementById('app'));
|
client/board.js | carpeliam/kriegspieljs | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import Square from './square';
const ascending = [0, 1, 2, 3, 4, 5, 6, 7];
const descending = [7, 6, 5, 4, 3, 2, 1, 0];
const fileLabels = 'abcdefgh';
function Board({ observingColor }) {
const ranks = (observingColor === 'black') ? ascending : descending;
const files = (observingColor === 'black') ? descending : ascending;
return (
<div className="board">
<header>
{files.map(file => <span key={`file${file}`} className="board__label board__label--file">{fileLabels[file]}</span>)}
</header>
{ranks.map(rank => (
[
<span key={`rank${rank}l`} className="board__label board__label--rank">{rank + 1}</span>,
...files.map(file => <Square x={file} y={rank} />),
<span key={`rank${rank}r`} className="board__label board__label--rank">{rank + 1}</span>
]
))}
<footer>
{files.map(file => <span key={`file${file}`} className="board__label board__label--file">{fileLabels[file]}</span>)}
</footer>
</div>
);
}
Board.propTypes = {
observingColor: PropTypes.oneOf(['white', 'black']).isRequired,
};
export const BoardDragDropContext = DragDropContext(HTML5Backend)(Board);
function mapStateToProps({ user, game: { players } }) {
const observingColor = (players.black && players.black.id === user.id) ? 'black' : 'white';
return { observingColor };
}
export default connect(mapStateToProps)(BoardDragDropContext);
|
components/menu/index.js | react-material-design/react-material-design | import '@material/menu/dist/mdc.menu.css';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { MDCSimpleMenu } from '@material/menu';
// TODO: Dynamically set selectMenu
/** Menu */
class Menu extends Component {
static propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.element),
PropTypes.element,
]).isRequired,
darkTheme: PropTypes.bool,
/** When menu is used as a child within <Select /> */
selectMenu: PropTypes.bool,
}
constructor(props) {
super(props);
this.mainRoot = React.createRef();
}
componentDidMount() {
this.menu = new MDCSimpleMenu(this.mainRoot.current);
this.menu.listen('MDCSimpleMenu:selected', ({ detail }) => {
this.setState({
selectedIndex: detail.index,
});
});
}
handleOpen = (focusIndex) => {
this.menu.show({ focusIndex });
}
render() {
const { children, darkTheme, selectMenu } = this.props;
return (
<div
ref={this.mainRoot}
className={classNames('mdc-simple-menu', { 'mdc-simple-menu--theme-dark': darkTheme }, { 'mdc-select__menu': selectMenu })}
tabIndex="-1"
>
<ul className="mdc-simple-menu__items mdc-list" role="menu" aria-hidden="true">
{children}
</ul>
</div>
);
}
}
export default Menu;
|
enrolment-ui/src/index.js | overture-stack/enrolment | import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter, Switch } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import reportWebVitals from './reportWebVitals';
import { unregister } from './registerServiceWorker';
import configureStore from './redux/store';
import { PrivateRoute, OnlyNonLoggedInRoute } from './routeHelpers';
import './i18n';
import {
App,
Login,
Main,
Dashboard,
Projects,
RegisterProject,
RegisterUser,
NotFound,
} from './modules';
// Removing a previously existing Service Worker, added by the original `Create React App` to allow PWA,
// because it is creating caching issues for some users. Will remove this in a few cycles, to allow propagation.
unregister();
// Create redux store
const store = configureStore();
render(
<Provider store={store}>
<BrowserRouter>
<App>
<Switch>
<OnlyNonLoggedInRoute exact path="/" component={Login} />
<OnlyNonLoggedInRoute exact path="/register-user/:projectId/:userId" component={Login} />
<OnlyNonLoggedInRoute exact path="/login" component={Login} />
<Main>
<Switch>
<PrivateRoute exact path="/dashboard" component={Dashboard} />
<PrivateRoute exact path="/register/project" component={RegisterProject} />
<PrivateRoute exact path="/view/project/:id" component={RegisterProject} />
<PrivateRoute
exact
path="/register/user/:projectId/:userId"
component={RegisterUser}
/>
<PrivateRoute
exact
path="/view/project-user/:projectId/:userId"
component={RegisterUser}
/>
<PrivateRoute exact path="/projects" component={Projects} />
<PrivateRoute component={NotFound} />
</Switch>
</Main>
</Switch>
</App>
</BrowserRouter>
</Provider>,
document.getElementById('root'),
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals(localStorage.DEBUG && console.log);
|
src/js/components/soon/index.js | Arlefreak/web_client.afk | import React from 'react';
import PropTypes from 'prop-types';
const Soon = () => (
<div>
<article className="glitch">
<span>ALWAYS Ɐ WIP</span>
</article>
</div>
);
export default Soon;
|
src/index.js | njt1982/google-sites-exporter | import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import {Main} from './app/main';
ReactDOM.render(
<Main/>,
document.getElementById('root')
);
|
website/src/components/PageInput.js | jwngr/sdow | import get from 'lodash/get';
import filter from 'lodash/filter';
import forEach from 'lodash/forEach';
import debounce from 'lodash/debounce';
import axios from 'axios';
import React from 'react';
import Autosuggest from 'react-autosuggest';
import {getRandomPageTitle} from '../utils';
import PageInputSuggestion from './PageInputSuggestion';
import {AutosuggestWrapper} from './PageInput.styles';
import {WIKIPEDIA_API_URL} from '../resources/constants';
// Autosuggest component helpers.
const getSuggestionValue = (suggestion) => suggestion.title;
const renderSuggestion = (suggestion) => <PageInputSuggestion {...suggestion} />;
class PageInput extends React.Component {
constructor(props) {
super(props);
this.state = {
suggestions: [],
isFetching: false,
};
props.updateInputPlaceholderText(getRandomPageTitle());
this.debouncedLoadSuggestions = debounce(this.loadSuggestions, 250);
}
componentWillReceiveProps(nextProps) {
if (
typeof this.placeholderTextInterval === 'undefined' ||
this.props.value !== nextProps.value
) {
clearInterval(this.placeholderTextInterval);
if (nextProps.value === '') {
this.placeholderTextInterval = setInterval(
() => this.props.updateInputPlaceholderText(getRandomPageTitle()),
5000
);
}
}
}
loadSuggestions(value) {
this.setState({
isFetching: true,
});
const queryParams = {
action: 'query',
format: 'json',
gpssearch: value,
generator: 'prefixsearch',
prop: 'pageprops|pageimages|pageterms',
redirects: '', // Automatically resolve redirects
ppprop: 'displaytitle',
piprop: 'thumbnail',
pithumbsize: '160',
pilimit: '30',
wbptterms: 'description',
gpsnamespace: 0, // Only return results in Wikipedia's main namespace
gpslimit: 5, // Return at most five results
origin: '*',
};
// TODO: add helper for making API requests to WikiMedia API
axios({
method: 'get',
url: WIKIPEDIA_API_URL,
params: queryParams,
headers: {
'Api-User-Agent':
'Six Degrees of Wikipedia/1.0 (https://www.sixdegreesofwikipedia.com/; wenger.jacob@gmail.com)',
},
})
.then((response) => {
const suggestions = [];
const pageResults = get(response, 'data.query.pages', {});
forEach(pageResults, ({ns, index, title, terms, thumbnail}) => {
// Due to https://phabricator.wikimedia.org/T189139, results will not always be limited
// to the main namespace (0), so ignore all results which have a different namespace.
if (ns === 0) {
let description = get(terms, 'description.0');
if (description) {
description = description.charAt(0).toUpperCase() + description.slice(1);
}
suggestions[index - 1] = {
title,
description,
thumbnailUrl: get(thumbnail, 'source'),
};
}
});
// Due to ignoring non-main namespaces above, the suggestions array may have some missing
// items, so remove them via filter().
this.setState({
isFetching: false,
suggestions: filter(suggestions),
});
})
.catch((error) => {
// Report the error to Google Analytics, but don't report any user-facing error since the
// input is still usable even without suggestions.
const defaultErrorMessage = 'Request to fetch page suggestions from Wikipedia API failed.';
window.ga('send', 'exception', {
exDescription: get(error, 'response.data.error', defaultErrorMessage),
exFatal: false,
});
});
}
render() {
const {value, setPageTitle, placeholderText} = this.props;
const {suggestions} = this.state;
return (
<AutosuggestWrapper>
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={({value}) => {
this.debouncedLoadSuggestions(value);
}}
onSuggestionsClearRequested={() => {
this.setState({
suggestions: [],
});
}}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={{
placeholder: placeholderText,
onChange: (event, {newValue}) => {
setPageTitle(newValue);
},
value,
}}
/>
</AutosuggestWrapper>
);
}
}
export default PageInput;
|
src/svg-icons/action/view-module.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionViewModule = (props) => (
<SvgIcon {...props}>
<path d="M4 11h5V5H4v6zm0 7h5v-6H4v6zm6 0h5v-6h-5v6zm6 0h5v-6h-5v6zm-6-7h5V5h-5v6zm6-6v6h5V5h-5z"/>
</SvgIcon>
);
ActionViewModule = pure(ActionViewModule);
ActionViewModule.displayName = 'ActionViewModule';
export default ActionViewModule;
|
components/label/Detail/Detail.js | Mudano/m-dash-ui | import React from 'react';
import PropTypes from 'prop-types';
import { css } from 'glamor';
import Label from '..';
const detailStyle = css({
fontSize: 13,
letterSpacing: 1.6
});
export default class Detail extends React.PureComponent {
static propTypes = {
label: PropTypes.string.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
style: PropTypes.object
};
render() {
const { label, value = '', style = {} } = this.props;
return (
<div className={css(detailStyle, style)}>
<Label
style={{
fontSize: 9,
letterSpacing: 1.1
}}
>
{label}
</Label>
{typeof value === 'string'
? <span>{value}</span>
: value}
</div>
);
}
}
|
Component/Message/Message.js | outman1992/Taoertao | /**
* Created by 58484 on 2016/9/9.
*/
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
var Login = require('../Mine/Login');
var Message = React.createClass({
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Message
</Text>
<TouchableOpacity
onPress={()=>{
this.props.navigator.push(
{
component: Login,
passProps: {
setLogined: this.setLogined,
setLogouted: this.setLogouted
}
}
);
}}
>
<Text style={styles.welcome}>
登录
</Text>
</TouchableOpacity>
</View>
);
}
})
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
}
});
module.exports = Message; |
packages/showcase/app.js | uber/react-vis | // Copyright (c) 2016 - 2017 Uber Technologies, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import ReactDOM from 'react-dom';
import React from 'react';
import document from 'global/document';
import {BrowserRouter, Route} from 'react-router-dom';
import ShowcaseApp from './showcase-app';
import '../react-vis/src/styles/examples.scss';
export default function App() {
// using react-router to trigger react updates on url change
return (
<BrowserRouter>
<Route path="/" component={ShowcaseApp} />
</BrowserRouter>
);
}
const el = document.createElement('div');
document.body.appendChild(el);
ReactDOM.render(<App />, el);
|
5.ParentChildComunication/src/WelCome.js | hiren2728/ReactDemo | import React from 'react';
export default class WelCome extends React.Component{
constructor(props)
{
super(props);
this.state = {
userInput : ""
};
}
render(){
return <div>
<button onClick={this.props.name}>Click Me</button><br/>
Enter Your Name : <input onChange={this.inputFieldChangeEvent}/>
<button onClick={this.changeWelcomName}>Change Name</button>
</div>;
}
changeWelcomName = (e) =>{
if(this.state.userInput == ""){
alert("Plase enter name.");
}
else{
this.props.changeValue(this.state.userInput);
}
};
inputFieldChangeEvent = (e) => {
this.setState({
userInput: e.target.value
});
}
} |
src/containers/utils/DevTools.js | hannupekka/splitthebill | // @flow
import React from 'react';
// Exported from redux-devtools
import { createDevTools } from 'redux-devtools';
// Monitors are separate packages, and you can make a custom one
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
// createDevTools takes a monitor and produces a DevTools component
const DevTools = createDevTools(
// Monitors are individually adjustable with props.
// Consult their repositories to learn about those props.
// Here, we put LogMonitor inside a DockMonitor.
// Note: DockMonitor is hidden by default.
<DockMonitor
toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-q"
defaultIsVisible={false}
>
<LogMonitor theme="tomorrow" />
</DockMonitor>
);
export default DevTools;
|
examples/todomvc/index.js | paulkogel/redux | import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import App from './containers/App'
import configureStore from './store/configureStore'
import 'todomvc-app-css/index.css'
const store = configureStore()
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
assets/jqwidgets/demos/react/app/datatable/showorhidecolumn/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxDataTable from '../../../jqwidgets-react/react_jqxdatatable.js';
import JqxListBox from '../../../jqwidgets-react/react_jqxlistbox.js';
class App extends React.Component {
componentDidMount() {
this.refs.myListBox.on('checkChange', (event) => {
this.refs.myDataTable.beginUpdate();
if (event.args.checked) {
this.refs.myDataTable.showColumn(event.args.value);
}
else {
this.refs.myDataTable.hideColumn(event.args.value);
}
this.refs.myDataTable.endUpdate();
});
}
render() {
let source =
{
dataType: 'json',
dataFields: [
{ name: 'name' },
{ name: 'type' },
{ name: 'calories', type: 'int' },
{ name: 'totalfat' },
{ name: 'protein' }
],
id: 'id',
url: '../sampledata/beverages.txt'
};
let dataAdapter = new $.jqx.dataAdapter(source);
let columns =
[
{ text: 'Name', datafield: 'name', width: 200 },
{ text: 'Beverage Type', dataField: 'type', width: 200 },
{ text: 'Calories', dataField: 'calories', width: 200 }
];
let listSource =
[
{ label: 'Beverage Type', value: 'type', checked: true },
{ label: 'Calories', value: 'calories', checked: true }
];
return (
<div>
<JqxListBox ref='myListBox' style={{ float: 'left' }}
width={150} height={200} source={listSource} checkboxes={true}
/>
<JqxDataTable ref='myDataTable' style={{ float: 'left', marginLeft: 20 }}
source={dataAdapter} pagerButtonsCount={10}
pageable={true} columnsResize={true} columns={columns}
/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
client/src/javascript/components/modals/ModalFormSectionHeader.js | stephdewit/flood | import React from 'react';
class ModalFormSectionHeader extends React.PureComponent {
render() {
return <h2 className="h4">{this.props.children}</h2>;
}
}
export default ModalFormSectionHeader;
|
components/form_field.js | runesam/react-redux-next | import React from 'react';
const FormFeild = ({
label,
element,
input,
placeholder,
type,
meta: { touched, error, warning, invalid }
}) => {
const CustomTag = element;
return (
<div>
<div className={`form-group ${touched && invalid ? 'has-danger' : ''}`}>
<h5>{label}</h5>
<CustomTag {...input} placeholder={placeholder} type={type || ''} className='form-control' />
{touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
</div>
</div>
);
};
export default FormFeild;
|
src/Editor/ContentHtml.js | skystebnicki/chamel | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import ThemeService from '../styles/ChamelThemeService';
import RichText from '../Input/RichText';
import EditorToolbar from './EditorToolbar';
/**
* Contains both the toolbar and an instance of RichText component
*/
class ContentHtml extends Component {
/**
* Class constructor
*
* @param {Object} props Properties to send to the render function
*/
constructor(props) {
// Call parent constructor
super(props);
this.state = {
value: this.props.value,
toggleStyle: null,
toggleType: null,
};
}
/**
* Handle when the editor has changed
*
* @param {string} value The value of the editor
* @private
*/
_onChange = value => {
if (this.props.onChange) {
this.props.onChange(value);
}
this.setState({ value });
};
_onToggle = value => {
if (this.props.onChange) {
this.props.onChange(value);
}
this.setState({
value,
toggleStyle: null,
toggleType: null,
});
};
/**
* Handle when the editor looses the focus
*
* @param {string} value The value of the editor
* @private
*/
_onBlur = value => {
if (this.props.onBlur) {
this.props.onBlur(value);
} else {
//this.setState({value});
}
};
/**
* Handles when the user set the focus in the editor
*
* @param {string} value The value of the editor
* @private
*/
_onFocus = value => {
if (this.props.onFocus) {
this.props.onFocus(value);
} else {
//this.setState({value});
}
};
/**
* Handles the toggling of styles in the toolbar icons
*
* @param {string} style The style that was clicked. It is either block style or inline style
* @param {string} type The style type that was toggled. (e.g. bold, italic, underline, h1, h2, h3, ul, ol)
* @private
*/
_handleStyleToggle = (style, type) => {
console.log('toggle');
this.setState({
toggleStyle: style,
toggleType: type,
});
};
/**
* Handles the toggling of content view
*
* @param {int} contentView The content view we are switching to
* @private
*/
_handleContentViewToggle = contentView => {
if (this.props.onContentViewToggle) {
this.props.onContentViewToggle(contentView, this.state.value);
}
};
render() {
// Determine which theme to use
let theme =
this.context.chamelTheme && this.context.chamelTheme.editor
? this.context.chamelTheme.editor
: ThemeService.defaultTheme.editor;
return (
<div className={theme.richTextContainer}>
<EditorToolbar
contentViewType={this.props.contentViewType}
onStyleToggle={this._handleStyleToggle}
onContentViewToggle={this._handleContentViewToggle}
/>
<RichText
commandToggleType={this.state.toggleType}
commandToggleStyle={this.state.toggleStyle}
onToggle={this._onToggle}
onChange={this._onChange}
onBlur={this._onBlur}
onFocus={this._onFocus}
value={this.state.value}
/>
</div>
);
}
}
/**
* Set accepted properties
*/
ContentHtml.propTypes = {
/**
* The callback function used when user changes the content of the editor
*
* @type {function}
*/
onChange: PropTypes.func,
/**
* The callback function used when user looses the focus of the editor
*
* @type {function}
*/
onBlur: PropTypes.func,
/**
* The initial value of the content editor
*
* @type {string}
*/
value: PropTypes.string,
/**
* Handles the toggling of content view
*
* @type {function}
*/
onContentViewToggle: PropTypes.func,
};
/**
* An alternate theme may be passed down by a provider
*/
ContentHtml.contextTypes = {
chamelTheme: PropTypes.object,
};
export default ContentHtml;
|
examples/multiple.js | eternalsky/select | /* eslint no-console: 0 */
import React from 'react';
import Select, { Option } from 'rc-select';
import 'rc-select/assets/index.less';
import ReactDOM from 'react-dom';
const children = [];
for (let i = 10; i < 36; i++) {
children.push(
<Option key={i.toString(36) + i} disabled={i === 10} title={`中文${i}`}>
中文{i}
</Option>
);
}
class Test extends React.Component {
state = {
useAnim: 0,
value: ['a10'],
}
onChange = (value) => {
console.log('onChange', value);
this.setState({
value,
});
}
onSelect = (...args) => {
console.log(args);
}
onDeselect = (...args) => {
console.log(args);
}
useAnim = (e) => {
this.setState({
useAnim: e.target.checked,
});
}
render() {
const dropdownMenuStyle = {
maxHeight: 200,
overflow: 'auto',
};
return (
<div>
<h2>multiple select(scroll the menu)</h2>
<p>
<label>
anim
<input checked={this.state.useAnim} type="checkbox" onChange={this.useAnim} />
</label>
</p>
<div style={{ width: 300 }}>
<Select
value={this.state.value}
animation={this.state.useAnim ? 'slide-up' : null}
choiceTransitionName="rc-select-selection__choice-zoom"
dropdownMenuStyle={dropdownMenuStyle}
style={{ width: 500 }}
multiple
allowClear
optionFilterProp="children"
optionLabelProp="children"
onSelect={this.onSelect}
onDeselect={this.onDeselect}
placeholder="please select"
onChange={this.onChange}
onFocus={() => console.log('focus')}
tokenSeparators={[' ', ',']}
>
{children}
</Select>
</div>
</div>
);
}
}
ReactDOM.render(<Test />, document.getElementById('__react-content'));
|
src/Accordion.js | xsistens/react-bootstrap | import React from 'react';
import PanelGroup from './PanelGroup';
const Accordion = React.createClass({
render() {
return (
<PanelGroup {...this.props} accordion>
{this.props.children}
</PanelGroup>
);
}
});
export default Accordion;
|
docs/app/Examples/modules/Popup/Usage/PopupExampleFocus.js | koenvg/Semantic-UI-React | import React from 'react'
import { Input, Popup } from 'semantic-ui-react'
const PopupExampleFocus = () => (
<Popup
trigger={<Input icon='search' placeholder='Search...' />}
header='Movie Search'
content='You may search by genre, header, year and actors'
on='focus'
/>
)
export default PopupExampleFocus
|
entry.react.js | raroman/raroman.github.io | import React from 'react';
import { render } from 'react-dom';
import { Router, Route, IndexRoute, applyRouterMiddleware, browserHistory } from 'react-router';
import { useScroll } from 'react-router-scroll';
import Index from './index.react.js';
import NoMatch from './no-match.react.js';
import 'tether';
import 'bootstrap';
import 'app.scss';
render(
<Router
history={browserHistory}
render={applyRouterMiddleware(useScroll())}
>
<Route path='/' component={Index} />
<Route path='*' component={NoMatch} />
</Router>
, document.getElementById('react')
);
|
src/components/button.js | LINKIWI/react-elemental | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { compose, withForwardedRef, withToggleState } from '@linkiwi/hoc';
import Text from 'components/text';
import { colors } from 'styles/color';
import { transitionStyle } from 'styles/transition';
import { KEY_CODE_ENTER } from 'util/constants';
import omit from 'util/omit';
// Mapping of button sizes to the corresponding default text size.
const textSizeMap = {
gamma: 'lambda',
beta: 'kilo',
alpha: 'iota',
};
// Mapping of primary button sizes to the corresponding button padding values.
const primaryPaddingMap = {
gamma: '6px 12px',
beta: '10px 16px',
alpha: '12px 22px',
};
// Mapping of secondary button sizes to the corresponding button padding values.
const secondaryPaddingMap = {
gamma: '4px 10px',
beta: '8px 14px',
alpha: '10px 20px',
};
/**
* Button component.
*/
class Button extends Component {
static propTypes = {
color: PropTypes.string,
size: PropTypes.oneOf(['alpha', 'beta', 'gamma']),
text: PropTypes.string,
disabled: PropTypes.bool,
secondary: PropTypes.bool,
style: PropTypes.object,
children: PropTypes.any,
// HOC props
handleMouseEnter: PropTypes.func.isRequired,
handleMouseLeave: PropTypes.func.isRequired,
handleMouseDown: PropTypes.func.isRequired,
handleMouseUp: PropTypes.func.isRequired,
handleFocus: PropTypes.func.isRequired,
handleBlur: PropTypes.func.isRequired,
isHover: PropTypes.bool.isRequired,
isActive: PropTypes.bool.isRequired,
isFocus: PropTypes.bool.isRequired,
forwardedRef: PropTypes.oneOfType([
PropTypes.shape({ current: PropTypes.instanceOf(Element) }),
PropTypes.func,
]),
};
static defaultProps = {
color: undefined,
size: 'beta',
text: null,
disabled: false,
secondary: false,
style: {},
children: null,
forwardedRef: null,
};
handleMouseLeave = () => {
const { handleMouseLeave, handleMouseUp } = this.props;
handleMouseLeave();
handleMouseUp();
};
handleKeyDown = ({ keyCode }) => (keyCode === KEY_CODE_ENTER) && this.props.handleMouseDown();
handleKeyUp = ({ keyCode }) => (keyCode === KEY_CODE_ENTER) && this.props.handleMouseUp();
render() {
const {
color = colors.primary,
size,
text,
disabled,
secondary,
style: overrides,
children,
handleMouseEnter,
handleMouseDown,
handleMouseUp,
handleFocus,
handleBlur,
isHover,
isActive,
isFocus,
forwardedRef,
...props
} = this.props;
const proxyProps = omit(props, ['handleMouseLeave']);
const brightness = (() => {
if (isActive) {
return 0.95;
}
if (isHover || isFocus) {
return 1.05;
}
return 1;
})();
const style = {
backgroundColor: secondary ? 'transparent' : color,
border: secondary ? `2px solid ${color}` : 'none',
borderRadius: 0,
color,
cursor: 'pointer',
filter: `brightness(${brightness})`,
opacity: disabled ? 0.4 : 1,
padding: (secondary ? secondaryPaddingMap : primaryPaddingMap)[size],
pointerEvents: disabled ? 'none' : 'inherit',
textDecoration: 'none',
...transitionStyle(),
...overrides,
};
return (
<button
ref={forwardedRef}
type="button"
style={style}
onMouseEnter={handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onTouchStart={handleMouseDown}
onTouchEnd={handleMouseUp}
onFocus={handleFocus}
onBlur={handleBlur}
onKeyDown={this.handleKeyDown}
onKeyUp={this.handleKeyUp}
disabled={disabled}
{...proxyProps}
>
{text && (
<Text
size={textSizeMap[size]}
color={secondary ? color : 'gray5'}
style={{ pointerEvents: 'none' }}
uppercase
bold
inline
>
{text}
</Text>
)}
{children}
</button>
);
}
}
export default compose(
withForwardedRef,
withToggleState({ key: 'isHover', enable: 'handleMouseEnter', disable: 'handleMouseLeave' }),
withToggleState({ key: 'isActive', enable: 'handleMouseDown', disable: 'handleMouseUp' }),
withToggleState({ key: 'isFocus', enable: 'handleFocus', disable: 'handleBlur' }),
)(Button);
|
src/router/router.js | moxun33/react-mobx-antd-boilerplate | import React from 'react';
import AsyncComponent from 'components/AsyncComponent';
import { Route, Switch } from 'react-router-dom';
const Home = AsyncComponent(() => import('pages/Main/Home'));
const Antd = AsyncComponent(() => import('pages/Main/Antd'));
const User = AsyncComponent(() => import('pages/Main/User'));
import { createNotFoundRoute } from '../utils/router';
const getRouter = _ => (
<div>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/user' component={User} />
<Route exact path='/antd' component={Antd} />
{createNotFoundRoute()}
</Switch>
</div>
);
export default getRouter;
|
tosort/2016/jspm/lib_react_101/index.js | Offirmo/html_tests | import React from 'react';
import ReactDOM from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin'
// http://www.material-ui.com/
// https://design.google.com/icons/
import Layout from './components/layout/index'
import '../../assets/fonts/MaterialIcons/material-icons.css!'
import '../../assets/fonts/Roboto/roboto-regular.css!'
import { createStore } from 'redux'
const store = createStore(function init(...args) {
console.log('Init reducer was called with args', args)
})
injectTapEventPlugin()
ReactDOM.render(
<Layout />,
document.getElementById('content')
)
|
frontend/src/components/frame/components/DrawerContent/components/ListItem.js | jf248/scrape-the-plate | import React from 'react';
import PropTypes from 'prop-types';
import * as PowerPlug from 'lib/react-powerplug';
import { RoutePush } from 'controllers/route-push';
import ListItemPres from './ListItemPres';
ListItem.propTypes = {
to: PropTypes.string.isRequired,
};
function ListItem(props) {
const { to, ...rest } = props;
const renderFunc = ({ push, path }) => {
const onClick = () => push(to);
const selected = path === to;
return <ListItemPres {...{ selected, onClick, ...rest }} />;
};
return (
/* eslint-disable react/jsx-key */
<PowerPlug.Compose components={[<RoutePush />]} render={renderFunc} />
/* eslint-enable react/jsx-key */
);
}
export default ListItem;
|
examples/with-heroku/src/server.js | jaredpalmer/razzle | import App from './App';
import React from 'react';
import express from 'express';
import { renderToString } from 'react-dom/server';
const assets = require(process.env.RAZZLE_ASSETS_MANIFEST);
const cssLinksFromAssets = (assets, entrypoint) => {
return assets[entrypoint] ? assets[entrypoint].css ?
assets[entrypoint].css.map(asset=>
`<link rel="stylesheet" href="${asset}">`
).join('') : '' : '';
};
const jsScriptTagsFromAssets = (assets, entrypoint, extra = '') => {
return assets[entrypoint] ? assets[entrypoint].js ?
assets[entrypoint].js.map(asset=>
`<script src="${asset}"${extra}></script>`
).join('') : '' : '';
};
export const renderApp = (req, res) => {
const markup = renderToString(<App />);
const html =
// prettier-ignore
`<!doctype html>
<html lang="">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charSet='utf-8' />
<title>Welcome to Razzle</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
${cssLinksFromAssets(assets, 'client')}
</head>
<body>
<div id="root">${markup}</div>
${jsScriptTagsFromAssets(assets, 'client', ' defer crossorigin')}
</body>
</html>`;
return { html };
};
const server = express();
server
.disable('x-powered-by')
.use(express.static(process.env.RAZZLE_PUBLIC_DIR))
.get('/*', (req, res) => {
const { html } = renderApp(req, res);
res.send(html);
});
export default server;
|
src/components/sidebar-menu/index.js | Lokiedu/libertysoil-site | /*
This file is a part of libertysoil.org website
Copyright (C) 2016 Loki Education (Social Enterprise)
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 { omit, values } from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import { MediaTargets as ts, MediaQueries as qs } from '../../consts/media';
import Navigation from '../navigation';
import * as MenuItemsObject from './items';
const MenuItems = values(MenuItemsObject);
function getMatchedMedia(ignore) {
if (ignore !== ts.xs && window.matchMedia(qs.xs).matches) {
return ts.xs;
}
if (ignore !== ts.s && window.matchMedia(qs.s).matches) {
return ts.s;
}
if (ignore !== ts.m && window.matchMedia(qs.m).matches) {
return ts.m;
}
if (ignore !== ts.l && window.matchMedia(qs.l).matches) {
return ts.l;
}
return ts.xl;
}
export default class SidebarMenu extends React.PureComponent {
static propTypes = {
adaptive: PropTypes.bool
};
static propKeys = Object.keys(SidebarMenu.propTypes);
constructor(props, context) {
super(props, context);
const state = { media: undefined };
if (
props.adaptive &&
typeof window !== 'undefined' &&
window !== null &&
window.matchMedia
) {
state.media = getMatchedMedia();
this.attachListener(state.media);
} else {
state.media = ts.xs;
}
this.state = state;
this.restProps = omit(props, SidebarMenu.propKeys);
}
componentWillReceiveProps(nextProps) {
this.restProps = omit(nextProps, SidebarMenu.propKeys);
}
componentWillUpdate(nextProps, nextState) {
if (nextState.media !== this.state.media) {
this.detachListener();
this.attachListener(nextState.media);
}
}
componentWillUnmount() {
if (this.query) {
this.detachListener();
}
}
attachListener = (media) => {
this.query = window.matchMedia(qs[media]);
this.query.addListener(this.handleViewChange);
};
detachListener = () => {
this.query.removeListener(this.handleViewChange);
};
handleViewChange = () => {
const next = getMatchedMedia(this.state.media);
this.setState(state => ({ ...state, media: next }));
};
query = null;
render() {
const { media } = this.state;
return (
<Navigation>
{MenuItems.map(Item => (
<Item
key={Item.displayName}
media={media}
{...this.restProps}
/>
))}
</Navigation>
);
}
}
|
docs/src/app/components/pages/components/Stepper/VerticalLinearStepper.js | xmityaz/material-ui | import React from 'react';
import {
Step,
Stepper,
StepLabel,
StepContent,
} from 'material-ui/Stepper';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
/**
* Vertical steppers are designed for narrow screen sizes. They are ideal for mobile.
*
* To use the vertical stepper with the contained content as seen in spec examples,
* you must use the `<StepContent>` component inside the `<Step>`.
*
* <small>(The vertical stepper can also be used without `<StepContent>` to display a basic stepper.)</small>
*/
class VerticalLinearStepper extends React.Component {
state = {
finished: false,
stepIndex: 0,
};
handleNext = () => {
const {stepIndex} = this.state;
this.setState({
stepIndex: stepIndex + 1,
finished: stepIndex >= 2,
});
};
handlePrev = () => {
const {stepIndex} = this.state;
if (stepIndex > 0) {
this.setState({stepIndex: stepIndex - 1});
}
};
renderStepActions(step) {
const {stepIndex} = this.state;
return (
<div style={{margin: '12px 0'}}>
<RaisedButton
label={stepIndex === 2 ? 'Finish' : 'Next'}
disableTouchRipple={true}
disableFocusRipple={true}
primary={true}
onTouchTap={this.handleNext}
style={{marginRight: 12}}
/>
{step > 0 && (
<FlatButton
label="Back"
disabled={stepIndex === 0}
disableTouchRipple={true}
disableFocusRipple={true}
onTouchTap={this.handlePrev}
/>
)}
</div>
);
}
render() {
const {finished, stepIndex} = this.state;
return (
<div style={{width: 380, height: 400, margin: 'auto'}}>
<Stepper activeStep={stepIndex} orientation="vertical">
<Step>
<StepLabel>Select campaign settings</StepLabel>
<StepContent>
<p>
For each ad campaign that you create, you can control how much
you're willing to spend on clicks and conversions, which networks
and geographical locations you want your ads to show on, and more.
</p>
{this.renderStepActions(0)}
</StepContent>
</Step>
<Step>
<StepLabel>Create an ad group</StepLabel>
<StepContent>
<p>An ad group contains one or more ads which target a shared set of keywords.</p>
{this.renderStepActions(1)}
</StepContent>
</Step>
<Step>
<StepLabel>Create an ad</StepLabel>
<StepContent>
<p>
Try out different ad text to see what brings in the most customers,
and learn how to enhance your ads using features like ad extensions.
If you run into any problems with your ads, find out how to tell if
they're running and how to resolve approval issues.
</p>
{this.renderStepActions(2)}
</StepContent>
</Step>
</Stepper>
{finished && (
<p style={{margin: '20px 0', textAlign: 'center'}}>
<a
href="#"
onClick={(event) => {
event.preventDefault();
this.setState({stepIndex: 0, finished: false});
}}
>
Click here
</a> to reset the example.
</p>
)}
</div>
);
}
}
export default VerticalLinearStepper;
|
src/routes/Admin/Position/ListPosition/Position.component.js | kritikasoni/smsss-react | import React from 'react';
import classes from './Position.component.scss';
export const Position = (props) => (
<div>
<div className={classes.topic12}>
<div className="row">
<div className="col-md-12">
<div className="col-md-6 text-right">{props.name}</div>
</div>
</div>
</div>
</div>
)
Position.propTypes = {
name: React.PropTypes.string.isRequired,
}
export default Position;
|
index.android.js | Notificare/notificare-push-lib-react-native | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
FlatList,
StyleSheet,
Text,
Linking,
NativeModules,
DeviceEventEmitter,
TouchableHighlight,
PermissionsAndroid,
View
} from 'react-native';
const Notificare = NativeModules.NotificareReactNativeAndroid;
export default class App extends Component {
constructor(props){
super(props);
this.state = {
dataSource: []
};
}
componentDidMount() {
console.log("componentDidMount");
Notificare.launch();
Linking.getInitialURL().then((url) => {
if (url) {
this._handleOpenURL(url);
}
}).catch(err => console.error('An error occurred', err));
Linking.addEventListener('url', this._handleOpenURL);
DeviceEventEmitter.addListener('ready', async (data) => {
console.log(data);
console.log(await Notificare.fetchDevice());
Notificare.registerForNotifications();
console.log(await Notificare.fetchTags());
await Notificare.addTag("react-native");
const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, {
'title': 'Location Permission',
'message': 'We need your location so we can send you relevant push notifications'
});
if (granted) {
Notificare.startLocationUpdates()
}
try {
await Notificare.login("joris@notifica.re", "Test123!")
} catch (err) {
console.warn(err.message);
}
});
DeviceEventEmitter.addListener('urlClickedInNotification', (data) => {
console.log(data);
});
DeviceEventEmitter.addListener('deviceRegistered', (data) => {
console.log(data);
});
DeviceEventEmitter.addListener('remoteNotificationReceivedInBackground', (data) => {
console.log(data);
Notificare.presentNotification(data);
});
DeviceEventEmitter.addListener('remoteNotificationReceivedInForeground', (data) => {
console.log(data);
});
DeviceEventEmitter.addListener('badgeUpdated', (data) => {
console.log(data);
});
DeviceEventEmitter.addListener('inboxLoaded', (data) => {
console.log(data);
this.setState({
dataSource: data
});
});
DeviceEventEmitter.addListener('activationTokenReceived', async (data) => {
console.log(data);
if (data && data.token) {
try {
await Notificare.validateAccount(data.token);
} catch (err) {
console.warn(err.message);
}
}
});
DeviceEventEmitter.addListener('resetPasswordTokenReceived', (data) => {
console.log(data);
});
}
componentWillUnmount() {
console.log('componentWillUnmount');
Notificare.unmount();
Linking.removeEventListener('url', this._handleOpenURL);
DeviceEventEmitter.removeAllListeners();
}
_handleOpenURL(url) {
console.log("Deeplink URL: " + url);
}
render() {
return (
<View style={styles.view}>
<FlatList
data={this.state.dataSource}
renderItem={this.renderRow}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
renderRow ({item}) {
return (
<TouchableHighlight onPress={() => Notificare.presentInboxItem(item)}>
<View>
<View style={styles.row}>
<Text style={styles.text}>
{item.message}
</Text>
<Text style={styles.text}>
{item.time}
</Text>
</View>
</View>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
view: {flex: 1, paddingTop: 22},
row: {
flexDirection: 'row',
justifyContent: 'center',
paddingTop: 20,
paddingBottom: 20,
paddingLeft: 10,
paddingRight: 5,
backgroundColor: '#F6F6F6'
},
text: {
flex: 1,
fontSize: 12,
}
});
|
src/util/file-browser.js | ordinarygithubuser/IDE | import React from 'react';
import { equalsPath } from '../util/common';
const isSelected = (selected, file) => {
return selected && equalsPath(selected, file);
};
const DirectoryItem = props => {
const { file, select, selected, toggle, setContext } = props;
const status = file.open ? 'caret-down' : 'caret-right';
const className = isSelected(selected, file) ? 'selected' : '';
const renderChildren = () => {
if (!file.children || !file.open) {
return <noscript />;
}
return <Files {...props} file={file} />;
};
const onClick = event => {
select(file);
if (event.ctrlKey && setContext) {
setContext('dir', event, file);
}
};
return <li className={`file ${className}`}>
<div className="name">
<i className={`fa fa-${status}`} onClick={() => toggle({ file })} />
<i className={`fa fa-folder`} onClick={onClick} />
<span onClick={onClick}>{file.name}</span>
</div>
{renderChildren()}
</li>;
};
const FileItem = ({ file, selected, read, select, setContext }) => {
const className = isSelected(selected, file) ? 'selected' : '';
const onClick = event => {
select(file);
if (event.ctrlKey && setContext) {
setContext('file', event, file)
}
};
return <li className={`file ${className}`}>
<div className="name" onDoubleClick={() => read(file)}>
<i className="fa fa-file iconSmall" onClick={onClick} />
<span onClick={onClick}>{file.name}</span>
</div>
</li>;
};
const Files = props => {
const elements = props.file.children.map((file, key) => {
const Component = file.type == 'dir' ? DirectoryItem : FileItem;
return <Component key={key} {...props} file={file} />;
});
return <ul>{elements}</ul>;
};
export default class FileBrowser extends React.Component {
render () {
const { props } = this;
return <div className="fileBrowser">
<div className="scroll">
<Files {...props} />
</div>
</div>;
}
} |
app/assets/javascripts/components/forms/Checkbox.js | Codeminer42/cm42-central | import React from 'react';
const Checkbox = ({ name, onChange, checked, disabled, children, label }) =>
<label>
<input
type='checkbox'
name={name}
checked={checked}
disabled={disabled}
onChange={onChange}
/>
{ label }
{ children }
</label>
export default Checkbox;
|
src/index.js | ServerChef/serverchef-ui | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter as Router } from 'react-router-dom';
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);
|
src/routes/User/childRoutes.js | Peturman/resume-app | import React from 'react'
import { Route } from 'react-router'
export default [
<Route path='login' component={require('./view/login').default} />,
<Route path='register' component={require('./view/register').default} />
]
|
src/components/ControllerUnit.js | wangjinqing123/gallery-by-react |
import React from 'react';
export default class ControllerUnit extends React.Component{
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
}
}
handleClick(e){
if(this.props.arrange.isCenter){
this.props.inverse();
}else{
this.props.center();
}
e.stopPropagation();
e.preventDefault();
}
render(){
var controllerUnitName = 'controller-unit';
if(this.props.arrange.isCenter){
controllerUnitName += ' is-center';
if(this.props.arrange.isInverse){
controllerUnitName += ' is-inverse'
}
}
return (
<span
className={controllerUnitName}
onClick={this.handleClick}
></span>
)
}
}
|
app/javascript/mastodon/features/compose/components/search_results.js | narabo/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import AccountContainer from '../../../containers/account_container';
import StatusContainer from '../../../containers/status_container';
import Link from 'react-router/lib/Link';
import ImmutablePureComponent from 'react-immutable-pure-component';
class SearchResults extends ImmutablePureComponent {
static propTypes = {
results: ImmutablePropTypes.map.isRequired,
};
render () {
const { results } = this.props;
let accounts, statuses, hashtags;
let count = 0;
if (results.get('accounts') && results.get('accounts').size > 0) {
count += results.get('accounts').size;
accounts = (
<div className='search-results__section'>
{results.get('accounts').map(accountId => <AccountContainer key={accountId} id={accountId} />)}
</div>
);
}
if (results.get('statuses') && results.get('statuses').size > 0) {
count += results.get('statuses').size;
statuses = (
<div className='search-results__section'>
{results.get('statuses').map(statusId => <StatusContainer key={statusId} id={statusId} />)}
</div>
);
}
if (results.get('hashtags') && results.get('hashtags').size > 0) {
count += results.get('hashtags').size;
hashtags = (
<div className='search-results__section'>
{results.get('hashtags').map(hashtag =>
<Link className='search-results__hashtag' to={`/timelines/tag/${hashtag}`}>
#{hashtag}
</Link>
)}
</div>
);
}
return (
<div className='search-results'>
<div className='search-results__header'>
<FormattedMessage id='search_results.total' defaultMessage='{count, number} {count, plural, one {result} other {results}}' values={{ count }} />
</div>
{accounts}
{statuses}
{hashtags}
</div>
);
}
}
export default SearchResults;
|
app/javascript/mastodon/components/loading_indicator.js | pso2club/mastodon | import React from 'react';
import { FormattedMessage } from 'react-intl';
const LoadingIndicator = () => (
<div className='loading-indicator'>
<div className='loading-indicator__figure' />
<FormattedMessage id='loading_indicator.label' defaultMessage='Loading...' />
</div>
);
export default LoadingIndicator;
|
src/slides/007-es7.js | brudil/slides-es6andbeyond | import React from 'react';
import Radium from 'radium';
// import {bindShowHelper} from '../utils';
@Radium
export default class TitleSlide extends React.Component {
static actionCount = 0;
static propTypes = {
actionIndex: React.PropTypes.number.isRequired,
style: React.PropTypes.object.isRequired
}
render() {
// const show = bindShowHelper(this.props.actionIndex);
return (
<div style={this.props.style}>
<h1>ES7 (probably)</h1>
</div>
);
}
}
|
apps/search/bible/ui/src/components/Dropdown.js | lucifurtun/myquotes | import React from 'react'
import Select from 'react-select'
import { connect } from 'react-redux'
import { formChange } from '../redux/filters'
import { isObject } from 'lodash'
const DropDown = ({ name, options, placeholder, value, dispatch }) => {
let preparedValue = null
if (isObject(value)) {
preparedValue = value || null
} else {
preparedValue = value ? { value: value, label: value } : null
}
return (
<Select
styles={{
clearIndicator: (provided, state) => ({
...provided,
paddingLeft: '0',
paddingRight: '0',
}
),
dropdownIndicator: (provided, state) => ({
...provided,
paddingLeft: '0',
paddingRight: '0',
}
)
}}
isClearable
options={options}
value={preparedValue}
placeholder={placeholder}
onChange={(event) => dispatch(formChange(name, event ? event.value : null))}
/>
)
}
export default connect()(DropDown)
|
actor-apps/app-web/src/app/components/sidebar/RecentSectionItem.react.js | berserkertdl/actor-platform | import React from 'react';
import classNames from 'classnames';
import DialogActionCreators from 'actions/DialogActionCreators';
import DialogStore from 'stores/DialogStore';
import AvatarItem from 'components/common/AvatarItem.react';
class RecentSectionItem extends React.Component {
static propTypes = {
dialog: React.PropTypes.object.isRequired
};
constructor(props) {
super(props);
}
onClick = () => {
DialogActionCreators.selectDialogPeer(this.props.dialog.peer.peer);
}
render() {
const dialog = this.props.dialog,
selectedDialogPeer = DialogStore.getSelectedDialogPeer();
let isActive = false,
title;
if (selectedDialogPeer) {
isActive = (dialog.peer.peer.id === selectedDialogPeer.id);
}
if (dialog.counter > 0) {
const counter = <span className="counter">{dialog.counter}</span>;
const name = <span className="col-xs title">{dialog.peer.title}</span>;
title = [name, counter];
} else {
title = <span className="col-xs title">{dialog.peer.title}</span>;
}
let recentClassName = classNames('sidebar__list__item', 'row', {
'sidebar__list__item--active': isActive,
'sidebar__list__item--unread': dialog.counter > 0
});
return (
<li className={recentClassName} onClick={this.onClick}>
<AvatarItem image={dialog.peer.avatar}
placeholder={dialog.peer.placeholder}
size="tiny"
title={dialog.peer.title}/>
{title}
</li>
);
}
}
export default RecentSectionItem;
|
src/app/Routes.js | imprevo/modular-react-app | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Route, Switch } from 'react-router-dom';
import PageNotFound from './pages/NotFound';
import asyncComponent from '../asyncComponent';
const Preloader = () => (<span>...</span>);
class Routes extends Component {
static propTypes = {
routeList: PropTypes.arrayOf(
PropTypes.shape({
path: PropTypes.string,
getComponent: PropTypes.func,
})
),
onLoadRoute: PropTypes.func,
};
render() {
const { routeList, onLoadRoute } = this.props;
return (
<Switch>
{routeList.map(({ path, getComponent }) => {
const component = asyncComponent(() => getComponent().then(onLoadRoute), Preloader);
return (
<Route
exact
key={path}
path={path}
component={component}
/>
);
})}
<Route component={PageNotFound} />
</Switch>
);
}
}
export default Routes;
|
P/lixil/src/components/Home/AboutSection.js | imuntil/React | import React from 'react'
import HomeSection from './HomeSection'
import {Row, Col} from 'antd'
import './AboutSection.css'
function AboutSection() {
const title = <img src={require('../../assets/product/aboutUs.png')} alt=""/>
const body = (
<div className="about-section">
<Row>
<Col xs={24}>
<p className='p top'>
LIXIL(骊住)是建材・建筑设备领域的全球性综合制造商。我们提供从独栋住宅・公寓到办公空间・商业设施等建筑多领域被广泛使用的多品类建材・建筑设备的设计、生产、供应及相关服务。
</p>
</Col>
</Row>
<Row>
<Col xs={24} sm={12}>
<img width="95%" src={require('../../assets/product/voide.png')} alt=""/>
</Col>
<Col xs={24} sm={12}>
<p className="p">
我们始终坚持以人为中心的创新,以提高人们的生活空间质量为制造的原点。从门窗、入户玄关门、庭院系统、瓷砖等建筑外观材料,到收纳系统、室内门、地板、卫生洁具、浴室和系统橱柜 、软装布艺等室内装饰材料,以及大规模的大厦铝合金幕墙制品,LIXIL始终保持业界第一的丰富产品力及专业性的产品服务。利用全球性的销售网络以及凝聚多年来日本国内积累的专业知识与技术能力LIXIL(骊住)持续为全球用户提供设计优良,经久耐用,可信赖的高品质商品。
</p>
</Col>
</Row>
</div>
)
return (
<HomeSection body={body} title={title} border={true} />
)
}
export default AboutSection |
example/app.js | wayofthefuture/react-input-moment | require('../src/less/base.less');
require('./app.less');
import React from 'react';
import ReactDOM from 'react-dom';
import moment from 'moment';
import {InputMoment, BigInputMoment, DatePicker, DatePickerRange, TimePicker} from '../src/index';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
inputMoment: moment(),
bigInputMoment: moment(),
datePickerMoment: moment(),
datePickerRangeStartMoment: moment().subtract(3, 'days'),
datePickerRangeEndMoment: moment(),
timePickerMoment: moment(),
showSeconds: true,
locale: 'en',
size: 'medium'
};
}
render() {
let {inputMoment, bigInputMoment, datePickerMoment, datePickerRangeStartMoment, datePickerRangeEndMoment, timePickerMoment, showSeconds, locale, size} = this.state;
let wrapperClass = 'wrapper ' + size;
return (
<div className="app">
<div className="header">
React Input Moment
</div>
<input
type="button"
className="header-button"
value="GitHub"
onClick={() => window.location = 'https://github.com/wayofthefuture/react-input-moment'}
/>
<input
type="button"
className="header-button"
value="NPM"
onClick={() => window.location = 'https://www.npmjs.com/package/react-input-moment'}
/>
<br/>
<div className="options">
<label>
<input
type="checkbox"
checked={showSeconds}
onChange={this.handleShowSeconds.bind(this)}
/>
Show Seconds
</label>
<br/>
<label>
Locale:
<select value={locale} onChange={this.handleLocale.bind(this)}>
<option value="en">English</option>
<option value="fr">French</option>
<option value="ar">Arabic</option>
</select>
</label>
<br/>
<input
type="button"
className="header-button"
value="Small"
onClick={() => this.setState({size: 'small'})}
/>
<input
type="button"
className="header-button"
value="Medium"
onClick={() => this.setState({size: 'medium'})}
/>
<input
type="button"
className="header-button"
value="Large"
onClick={() => this.setState({size: 'large'})}
/>
</div>
<div className="header">InputMoment</div>
<input
className="output"
type="text"
value={inputMoment.format('llll')}
readOnly
/>
<div className={wrapperClass}>
<InputMoment
moment={inputMoment}
locale={locale}
showSeconds={showSeconds}
onChange={mom => this.setState({inputMoment: mom})}
/>
</div>
<br/>
<div className="header">BigInputMoment</div>
<input
className="output"
type="text"
value={bigInputMoment.format('llll')}
readOnly
/>
<div className={wrapperClass}>
<BigInputMoment
moment={bigInputMoment}
locale={locale}
showSeconds={showSeconds}
onChange={mom => this.setState({bigInputMoment: mom})}
/>
</div>
<br/>
<div className="header">DatePicker</div>
<input
className="output"
type="text"
value={datePickerMoment.format('llll')}
readOnly
/>
<div className={wrapperClass}>
<DatePicker
moment={datePickerMoment}
locale={locale}
showSeconds={showSeconds}
onChange={mom => this.setState({datePickerMoment: mom})}
/>
</div>
<br/>
<div className="header">DatePickerRange</div>
<input
style={{width: '525px'}}
className="output"
type="text"
value={datePickerRangeStartMoment.format('llll') + ' - ' + datePickerRangeEndMoment.format('llll')}
readOnly
/>
<div className={wrapperClass}>
<DatePickerRange
startMoment={datePickerRangeStartMoment}
endMoment={datePickerRangeEndMoment}
locale={locale}
onChange={(startMoment, endMoment) => this.setState({datePickerRangeStartMoment: startMoment, datePickerRangeEndMoment: endMoment})}
/>
</div>
<br/>
<div className="header">TimePicker</div>
<input
className="output"
type="text"
value={timePickerMoment.format('llll')}
readOnly
/>
<div className={wrapperClass}>
<TimePicker
moment={timePickerMoment}
locale={locale}
showSeconds={showSeconds}
onChange={mom => this.setState({timePickerMoment: mom})}
/>
</div>
</div>
);
}
handleShowSeconds(e) {
this.setState({showSeconds: e.target.checked});
}
handleLocale(e) {
this.setState({locale: e.target.value});
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
//testing
window.moment = moment;
|
example/examples/PolylineCreator.js | jrichardlai/react-native-maps | import React from 'react';
import {
StyleSheet,
View,
Text,
Dimensions,
TouchableOpacity,
} from 'react-native';
import MapView from 'react-native-maps';
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
let id = 0;
class PolylineCreator extends React.Component {
constructor(props) {
super(props);
this.state = {
region: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
},
polylines: [],
editing: null,
};
}
finish() {
const { polylines, editing } = this.state;
this.setState({
polylines: [...polylines, editing],
editing: null,
});
}
onPanDrag(e) {
const { editing } = this.state;
if (!editing) {
this.setState({
editing: {
id: id++,
coordinates: [e.nativeEvent.coordinate],
},
});
} else {
this.setState({
editing: {
...editing,
coordinates: [
...editing.coordinates,
e.nativeEvent.coordinate,
],
},
});
}
}
render() {
return (
<View style={styles.container}>
<MapView
style={styles.map}
initialRegion={this.state.region}
scrollEnabled={false}
onPanDrag={e => this.onPanDrag(e)}
>
{this.state.polylines.map(polyline => (
<MapView.Polyline
key={polyline.id}
coordinates={polyline.coordinates}
strokeColor="#000"
fillColor="rgba(255,0,0,0.5)"
strokeWidth={1}
/>
))}
{this.state.editing &&
<MapView.Polyline
key="editingPolyline"
coordinates={this.state.editing.coordinates}
strokeColor="#F00"
fillColor="rgba(255,0,0,0.5)"
strokeWidth={1}
/>
}
</MapView>
<View style={styles.buttonContainer}>
{this.state.editing && (
<TouchableOpacity
onPress={() => this.finish()}
style={[styles.bubble, styles.button]}
>
<Text>Finish</Text>
</TouchableOpacity>
)}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
...StyleSheet.absoluteFillObject,
},
bubble: {
backgroundColor: 'rgba(255,255,255,0.7)',
paddingHorizontal: 18,
paddingVertical: 12,
borderRadius: 20,
},
latlng: {
width: 200,
alignItems: 'stretch',
},
button: {
width: 80,
paddingHorizontal: 12,
alignItems: 'center',
marginHorizontal: 10,
},
buttonContainer: {
flexDirection: 'row',
marginVertical: 20,
backgroundColor: 'transparent',
},
});
module.exports = PolylineCreator;
|
client/src/app/App.js | flyrightsister/boxcharter | /*
* Copyright (c) 2017 Bonnie Schulkin. All Rights Reserved.
*
* This file is part of BoxCharter.
*
* BoxCharter 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.
*
* BoxCharter 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 BoxCharter. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* Main component for BoxCharter
* @module
* App
*/
import React, { Component } from 'react';
import Header from '../nav/Header';
import Routes from './Routes';
import ErrorBoundary from '../error/ErrorBoundary';
import axiosInstance from '../config/axiosInstance';
// import { clearLoadingEvents } from '../loading/loadingActions';
/**
* @class AppComponent
*/
export default class App extends Component {
/**
* Initialize axios auth header and reset loading states.
* @method constructor
* @param {object} props - Props.
* @returns {undefined}
*/
constructor(props) {
super(props);
// restore axios header if token exists
const token = localStorage.getItem('token');
if (token) {
axiosInstance.defaults.headers.common.authorization = token;
}
// TODO: clear any loading state
}
/**
* @method render
* @returns {JSX.Element} - Rendered component.
*/
render() {
return (
<div className="full-page">
<ErrorBoundary>
<Header />
</ErrorBoundary>
<Routes />
</div>
);
}
}
|
client/app/components/Toggle/index.js | KamillaKhabibrakhmanova/postcardsforchange-api | /**
*
* LocaleToggle
*
*/
import React from 'react';
import Select from './Select';
import ToggleOption from '../ToggleOption';
function Toggle(props) {
let content = (<option>--</option>);
// If we have items, render them
if (props.values) {
content = props.values.map((value) => (
<ToggleOption key={value} value={value} message={props.messages[value]} />
));
}
return (
<Select value={props.value} onChange={props.onToggle}>
{content}
</Select>
);
}
Toggle.propTypes = {
onToggle: React.PropTypes.func,
values: React.PropTypes.array,
value: React.PropTypes.string,
messages: React.PropTypes.object,
};
export default Toggle;
|
src/parser/warrior/arms/modules/talents/Skullsplitter.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import { formatThousands } from 'common/format';
import Analyzer from 'parser/core/Analyzer';
import AbilityTracker from 'parser/shared/modules/AbilityTracker';
import SpellLink from 'common/SpellLink';
import StatisticListBoxItem from 'interface/others/StatisticListBoxItem';
/**
* Bash an enemy's skull, dealing [ 84% of Attack Power ] Physical damage.
*/
class Skullsplitter extends Analyzer {
static dependencies = {
abilityTracker: AbilityTracker,
};
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.SKULLSPLITTER_TALENT.id);
}
subStatistic() {
const Skullsplitter = this.abilityTracker.getAbility(SPELLS.SKULLSPLITTER_TALENT.id);
const total = Skullsplitter.damageEffective || 0;
const avg = total / (Skullsplitter.casts || 1);
return (
<StatisticListBoxItem
title={<>Average <SpellLink id={SPELLS.SKULLSPLITTER_TALENT.id} /> damage</>}
value={formatThousands(avg)}
valueTooltip={`Total Skullsplitter damage: ${formatThousands(total)}`}
/>
);
}
}
export default Skullsplitter;
|
packages/forms/src/rhf/fields/Input/RHFInput.component.js | Talend/ui | import React from 'react';
import PropTypes from 'prop-types';
import { useFormContext } from 'react-hook-form';
import get from 'lodash/get';
import Input from '../../../widgets/fields/Input';
function RHFInput(props) {
const { rules = {}, ...rest } = props;
const { errors, register } = useFormContext();
const error = get(errors, rest.name)?.message;
return <Input {...rest} ref={register(rules)} error={error} />;
}
if (process.env.NODE_ENV !== 'production') {
RHFInput.propTypes = {
rules: PropTypes.object,
};
}
export default RHFInput;
|
src/layouts/CoreLayout/CoreLayout.js | MingYinLv/blog-admin | import React from 'react';
import './CoreLayout.scss';
import '../../styles/core.scss';
export const CoreLayout = ({ children }) => (
<div style={{ height: '100%' }}>
{children}
</div>
);
CoreLayout.propTypes = {
children: React.PropTypes.element.isRequired,
};
export default CoreLayout;
|
src/App/components/Star.react.js | Rezmodeus/Multiplikation | import React from 'react';
import {Glyphicon} from 'react-bootstrap';
export default React.createClass({
render() {
const cls = this.props.filled ? 'star filled' : 'star';
return (
<span className={cls}>
{this.props.filled ? <Glyphicon glyph="star"/> : <Glyphicon glyph="star-empty"/>}
</span>
)
}
});
|
index.js | ruanyl/g26client | // import css from './static/css/style.css';
import thunkMiddleware from 'redux-thunk';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './containers/App';
import {applyMiddleware, createStore, compose} from 'redux';
import {Provider} from 'react-redux';
import reducers from './reducers/reducers';
// Redux DevTools store enhancers
import {devTools, persistState} from 'redux-devtools';
// React components for Redux DevTools
import {DevTools, DebugPanel, LogMonitor} from 'redux-devtools/lib/react';
const createStoreWithMiddleware = compose(
applyMiddleware(thunkMiddleware),
devTools(),
persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
)(createStore);
const store = createStoreWithMiddleware(reducers);
ReactDOM.render(
<div>
<Provider store={store}>
<App />
</Provider>
<DebugPanel top right bottom>
<DevTools store={store} monitor={LogMonitor} />
</DebugPanel>
</div>,
document.getElementById('content')
);
|
src/components/topic/snapshots/foci/builder/nyttheme/NytThemeSummary.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import { FormattedMessage, injectIntl } from 'react-intl';
const localMessages = {
intro: { id: 'focus.create.confirm.nytTheme.intro', defaultMessage: 'We will create 5 subtopics:' },
};
const NytThemeSummary = (props) => {
const { counts } = props;
return (
<>
<p><FormattedMessage {...localMessages.intro} /></p>
<ul>
{counts.map(ctry => <li>{ctry.label}</li>)}
</ul>
</>
);
};
NytThemeSummary.propTypes = {
// from parent
topicId: PropTypes.number.isRequired,
formValues: PropTypes.object.isRequired,
counts: PropTypes.object.isRequired,
// form context
intl: PropTypes.object.isRequired,
};
const mapStateToProps = state => ({
fetchStatus: state.topics.selected.focalSets.create.nytThemeStoryCounts.fetchStatus,
counts: state.topics.selected.focalSets.create.nytThemeStoryCounts.story_counts,
});
export default
injectIntl(
connect(mapStateToProps)(
NytThemeSummary
)
);
|
src/components/Html.js | bharathbhsp/refactored-funicular | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import serialize from 'serialize-javascript';
import config from '../config';
/* eslint-disable react/no-danger */
class Html extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
styles: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
cssText: PropTypes.string.isRequired,
}).isRequired,
),
scripts: PropTypes.arrayOf(PropTypes.string.isRequired),
app: PropTypes.object, // eslint-disable-line
children: PropTypes.string.isRequired,
};
static defaultProps = {
styles: [],
scripts: [],
};
render() {
const { title, description, styles, scripts, app, children } = this.props;
return (
<html className="no-js" lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<title>
{title}
</title>
<meta name="description" content={description} />
<meta name="viewport" content="width=device-width, initial-scale=1" />
{scripts.map(script =>
<link key={script} rel="preload" href={script} as="script" />,
)}
<link rel="apple-touch-icon" href="apple-touch-icon.png" />
{styles.map(style =>
<style
key={style.id}
id={style.id}
dangerouslySetInnerHTML={{ __html: style.cssText }}
/>,
)}
</head>
<body>
<div id="app" dangerouslySetInnerHTML={{ __html: children }} />
<script
dangerouslySetInnerHTML={{ __html: `window.App=${serialize(app)}` }}
/>
{scripts.map(script => <script key={script} src={script} />)}
{config.analytics.googleTrackingId &&
<script
dangerouslySetInnerHTML={{
__html:
'window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;' +
`ga('create','${config.analytics
.googleTrackingId}','auto');ga('send','pageview')`,
}}
/>}
{config.analytics.googleTrackingId &&
<script
src="https://www.google-analytics.com/analytics.js"
async
defer
/>}
</body>
</html>
);
}
}
export default Html;
|
src/shared/components/form/formCheckBox/formCheckBox.js | tal87/operationcode_frontend | import React from 'react';
import PropTypes from 'prop-types';
import styles from './formCheckBox.css';
const FormCheckBox = ({ checkBox, name, value, onChange, label }) => (
<div style={checkBox}>
<input
type="checkbox"
name={name}
id={value}
value={value}
onChange={onChange}
className={styles.input}
/>
<label style={label} htmlFor={name}>
{value}
</label>
</div>
);
FormCheckBox.propTypes = {
name: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
onChange: PropTypes.func,
checkBox: PropTypes.shape({
display: PropTypes.string,
margin: PropTypes.string
}),
label: PropTypes.shape({
textTransform: PropTypes.string,
fontWeight: PropTypes.string,
margin: PropTypes.string
})
};
FormCheckBox.defaultProps = {
onChange: null,
checkBox: null,
label: null
};
export default FormCheckBox;
|
src/components/App.js | PedroAlvCha/ud918-readable | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Route, withRouter } from 'react-router-dom';
import NavBarInstance from './NavigationHeader.js';
import ListPostsComponent from './PostList.js';
class App extends Component {
render() {
const categoryForMe = this.props.match.params.category;
return (
<div >
<Route render={() => (
<div >
<NavBarInstance />
<ListPostsComponent
categorySelected={categoryForMe}
/>
</div>
)}/>
</div>
);
}
}
function mapStateToProps (state) {
}
function mapDispatchToProps (dispatch) {
return {
}
}
export default withRouter(connect(
mapStateToProps,
mapDispatchToProps
)(App))
|
examples/webview_example/src/RootNavigator.js | BranchMetrics/react-native-branch | import React from 'react';
import { YellowBox } from 'react-native';
// disable a warning generated by react-navigation
YellowBox.ignoreWarnings([
'Warning: componentWillReceiveProps',
]);
import { createAppContainer, createStackNavigator } from 'react-navigation';
import Article from './Article';
import ArticleList from './ArticleList';
const RootNavigator = createStackNavigator({
Home: {
screen: ArticleList,
},
Article: {
screen: Article,
}
});
export default createAppContainer(RootNavigator);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.