path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
blueprints/form/files/__root__/forms/__name__Form/__name__Form.js
joopand/presensi
import React from 'react' import { reduxForm } from 'redux-form' export const fields = [] const validate = (values) => { const errors = {} return errors } type Props = { handleSubmit: Function, fields: Object, } export class <%= pascalEntityName %> extends React.Component { props: Props; defaultProps = { fields: {}, } render() { const { fields, handleSubmit } = this.props return ( <form onSubmit={handleSubmit}> </form> ) } } <%= pascalEntityName %> = reduxForm({ form: '<%= pascalEntityName %>', fields, validate })(<%= pascalEntityName %>) export default <%= pascalEntityName %>
app/app.js
dijahmac/JobWeasel-FrontEnd
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Switch, Route } from 'react-router-dom'; import '!file-loader?name=[name].[ext]!./favicon.ico'; import '!file-loader?name=[name].[ext]!./manifest.json'; import Home from 'containers/Home'; import About from 'containers/About'; import Profile from 'containers/Profile'; import NotFound from 'containers/NotFound'; import AddJob from 'containers/AddJob'; import JobDetails from 'containers/JobDetails'; import Jobs from 'containers/Jobs'; import SignUp from 'containers/SignUp'; import Admin from 'containers/Admin'; import ViewProfiles from 'containers/ViewProfiles'; ReactDOM.render(( <BrowserRouter> <Switch> <Route exact path='/' component={Home}/> <Route path='/About' component={About}/> <Route path='/AddJob' component={AddJob}/> <Route path='/JobDetails/:id' component={JobDetails}/> <Route path='/Jobs' component={Jobs}/> <Route path='/Profile/:id' component={Profile}/> <Route path='/Profile' component={Profile}/> <Route path='/SignUp' component={SignUp}/> <Route path='/Admin' component={Admin}/> <Route path='/ViewProfiles' component={ViewProfiles}/> <Route path='*' component={NotFound}/> </Switch> </BrowserRouter> ), document.getElementById('app')); if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require }
src/navbar.js
kngroo/Kngr
import React, { Component } from 'react'; import { Link, IndexLink } from 'react-router'; require('./styles/navbar.scss'); export default class Navbar extends Component { render() { return ( <div id="navbar"> <div className="navbar-spacer"></div> <nav className="navbar"> <div className="container"> <ul className="navbar-list"> <li className="navbar-item"> <IndexLink className="navbar-link" to="/">Home</IndexLink> </li> <li className="navbar-item"> <Link className="navbar-link" to="/projects">Projects</Link> </li> <li className="navbar-item"> <Link className="navbar-link" to="/about">About</Link> </li> <li className="navbar-item"> <Link className="navbar-link" to="/contact">Contact</Link> </li> </ul> </div> </nav> </div> ) } }
app/javascript/mastodon/features/search/index.js
clworld/mastodon
import React from 'react'; import SearchContainer from 'mastodon/features/compose/containers/search_container'; import SearchResultsContainer from 'mastodon/features/compose/containers/search_results_container'; const Search = () => ( <div className='column search-page'> <SearchContainer /> <div className='drawer__pager'> <div className='drawer__inner darker'> <SearchResultsContainer /> </div> </div> </div> ); export default Search;
packages/slate-react/test/rendering/fixtures/custom-block.js
6174/slate
/** @jsx h */ import React from 'react' import h from '../../helpers/h' export const schema = { nodes: { code: (props) => { return ( React.createElement('pre', props.attributes, React.createElement('code', {}, props.children) ) ) } } } export const state = ( <state> <document> <code> word </code> </document> </state> ) export const output = ` <div data-slate-editor="true" contenteditable="true" role="textbox"> <pre> <code> <span> <span>word</span> </span> </code> </pre> </div> `.trim()
src/parser/shaman/enhancement/modules/features/Checklist/Component.js
fyruna/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import Checklist from 'parser/shared/modules/features/Checklist'; import PreparationRule from 'parser/shared/modules/features/Checklist/PreparationRule'; import Rule from 'parser/shared/modules/features/Checklist/Rule'; import Requirement from 'parser/shared/modules/features/Checklist/Requirement'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import GenericCastEfficiencyRequirement from 'parser/shared/modules/features/Checklist/GenericCastEfficiencyRequirement'; class EnhancementShamanChecklist extends React.PureComponent { static propTypes = { combatant: PropTypes.shape({ hasTalent: PropTypes.func.isRequired, hasTrinket: PropTypes.func.isRequired, }).isRequired, thresholds: PropTypes.object.isRequired, }; render() { const { castEfficiency, combatant, thresholds } = this.props; const AbilityRequirement = props => ( <GenericCastEfficiencyRequirement isMaxCasts castEfficiency={castEfficiency.getCastEfficiencyForSpellId(props.spell)} {...props} /> ); return ( <Checklist> <Rule name="Always be casting" description={<>You should try to avoid doing nothing during the fight. If you have to move, try casting something instant with range like <SpellLink id={SPELLS.FLAMETONGUE.id} /> or <SpellLink id={SPELLS.ROCKBITER.id} /></>} > <Requirement name="Downtime" thresholds={thresholds.alwaysBeCasting} /> </Rule> <Rule name="Use your offensive cooldowns as often as possible" description={( <> You should aim to use your offensive cooldowns as often as you can to maximize your damage output.{' '} <a href="https://www.wowhead.com/enhancement-shaman-rotation-guide#offensive-defensive-cooldowns" target="_blank" rel="noopener noreferrer">More info.</a> </> )} > <AbilityRequirement spell={SPELLS.FERAL_SPIRIT.id} /> {combatant.hasTalent(SPELLS.ASCENDANCE_TALENT_ENHANCEMENT.id) && <AbilityRequirement spell={SPELLS.ASCENDANCE_TALENT_ENHANCEMENT.id} />} {combatant.hasTalent(SPELLS.EARTHEN_SPIKE_TALENT.id) && <AbilityRequirement spell={SPELLS.EARTHEN_SPIKE_TALENT.id} />} {combatant.hasTalent(SPELLS.TOTEM_MASTERY_TALENT_ENHANCEMENT.id) && <AbilityRequirement spell={SPELLS.TOTEM_MASTERY_TALENT_ENHANCEMENT.id} />} </Rule> <PreparationRule thresholds={thresholds} /> </Checklist> ); } } export default EnhancementShamanChecklist;
webpack/JobWizard/steps/AdvancedFields/AdvancedFields.js
adamruzicka/foreman_remote_execution
import React from 'react'; import PropTypes from 'prop-types'; import { useSelector } from 'react-redux'; import { Form } from '@patternfly/react-core'; import { selectEffectiveUser, selectAdvancedTemplateInputs, selectTemplateInputs, } from '../../JobWizardSelectors'; import { EffectiveUserField, TimeoutToKillField, PasswordField, KeyPassphraseField, EffectiveUserPasswordField, ConcurrencyLevelField, TimeSpanLevelField, TemplateInputsFields, ExecutionOrderingField, } from './Fields'; import { DescriptionField } from './DescriptionField'; import { WIZARD_TITLES } from '../../JobWizardConstants'; import { WizardTitle } from '../form/WizardTitle'; export const AdvancedFields = ({ advancedValues, setAdvancedValues }) => { const effectiveUser = useSelector(selectEffectiveUser); const advancedTemplateInputs = useSelector(selectAdvancedTemplateInputs); const templateInputs = useSelector(selectTemplateInputs); return ( <> <WizardTitle title={WIZARD_TITLES.advanced} className="advanced-fields-title" /> <Form id="advanced-fields-job-template" autoComplete="off"> <TemplateInputsFields inputs={advancedTemplateInputs} value={advancedValues.templateValues} setValue={newValue => setAdvancedValues({ templateValues: newValue })} /> {effectiveUser?.overridable && ( <EffectiveUserField value={advancedValues.effectiveUserValue} setValue={newValue => setAdvancedValues({ effectiveUserValue: newValue, }) } /> )} <DescriptionField inputs={templateInputs} value={advancedValues.description} setValue={newValue => setAdvancedValues({ description: newValue })} /> <TimeoutToKillField value={advancedValues.timeoutToKill} setValue={newValue => setAdvancedValues({ timeoutToKill: newValue, }) } /> <PasswordField value={advancedValues.password} setValue={newValue => setAdvancedValues({ password: newValue, }) } /> <KeyPassphraseField value={advancedValues.keyPassphrase} setValue={newValue => setAdvancedValues({ keyPassphrase: newValue, }) } /> <EffectiveUserPasswordField value={advancedValues.effectiveUserPassword} setValue={newValue => setAdvancedValues({ effectiveUserPassword: newValue, }) } /> <ConcurrencyLevelField value={advancedValues.concurrencyLevel} setValue={newValue => setAdvancedValues({ concurrencyLevel: newValue, }) } /> <TimeSpanLevelField value={advancedValues.timeSpan} setValue={newValue => setAdvancedValues({ timeSpan: newValue, }) } /> <ExecutionOrderingField isRandomizedOrdering={advancedValues.isRandomizedOrdering} setValue={newValue => setAdvancedValues({ isRandomizedOrdering: newValue, }) } /> </Form> </> ); }; AdvancedFields.propTypes = { advancedValues: PropTypes.object.isRequired, setAdvancedValues: PropTypes.func.isRequired, }; export default AdvancedFields;
src/components/ReplEntries.js
antonyr/Mancy
import React from 'react'; import _ from 'lodash'; import md5 from 'md5'; import ReplEntry from './ReplEntry'; export default class ReplEntries extends React.Component { constructor(props) { super(props); } render() { return ( <div className='repl-entries'> { _.map(this.props.entries, (entry, pos) => { return <ReplEntry log={entry} index={pos} key={md5(entry.command + pos)}/>; }) } </div> ); } }
frontend/src/index.js
McMenemy/awsAutoDeploy
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, browserHistory } from 'react-router'; import App from './components/App'; ReactDOM.render(( <Router history={browserHistory}> <Route path="/" component={App} /> </Router> ), document.getElementById('root'), );
react-dev/containers/posts_index.js
575617819/yanghang
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { PostIndexItem } from '../components/post_index_item'; import { fetchPosts, fetchSiteInfo } from '../actions/index'; class PostsIndex extends Component { componentWillMount() { this.props.fetchPosts(); this.props.fetchSiteInfo(); } render() { return ( <div> <PostIndexItem posts={this.props.posts} siteInfo={this.props.siteInfo} /> </div> ); } } function mapStateToProps(state) { return { posts: state.posts.all, siteInfo: state.siteInfo.all }; } export default connect(mapStateToProps, { fetchPosts, fetchSiteInfo })(PostsIndex);
internal/webpack/withServiceWorker/offlinePageTemplate.js
sergiokopplin/react-universally
/** * This is used by the HtmlWebpackPlugin to generate an html page that we will * use as a fallback for our service worker when the user is offline. It will * embed all the required asset paths needed to bootstrap the application * in an offline session. */ import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import HTML from '../../../shared/components/HTML'; module.exports = function generate(context) { // const config = context.htmlWebpackPlugin.options.custom.config; const ClientConfig = context.htmlWebpackPlugin.options.custom.ClientConfig; const html = renderToStaticMarkup( <HTML bodyElements={<ClientConfig nonce="OFFLINE_PAGE_NONCE_PLACEHOLDER" />} />, ); return `<!DOCTYPE html>${html}`; };
examples/CardSimple.js
mattBlackDesign/react-materialize
import React from 'react'; import Card from '../src/Card'; import Col from '../src/Col'; export default <Col m={6} s={12}> <Card className='blue-grey darken-1' textClassName='white-text' title='Card title' actions={[<a href='#'>This is a link</a>]}> I am a very simple card. </Card> </Col>;
src/pages/repos.js
giupo/prodomo
'use strict'; import React from 'react'; export default React.createClass({ displayName : 'ReposPage', render () { /* jshint ignore:start */ return <h1>repos page</h1>; /* jshint ignore:end */ } });
src/app/components/cookie-policy.js
pashist/soundcloud-like-player
import React from 'react'; export default class CookiePolicy extends React.Component { render() { return ( <div className="cookie-policy"> <a href="https://soundcloud.com/pages/cookies" target="_blank">Cookie policy</a> </div> ) } }
app/modules/agile_client/src/js/containers/DevTools.js
curcuz/agile-ui-berlindemo
import React from 'react' 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' import SliderMonitor from 'redux-slider-monitor' // createDevTools takes a monitor and produces a DevTools component export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q" changeMonitorKey="ctrl-m"> <LogMonitor theme="nicinabox" /> <SliderMonitor keyboardEnabled /> </DockMonitor> )
nativeExample/reactNative/index.ios.js
zhanglizhao/react-native-knowledge
/** * 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 reactNative 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.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('reactNative', () => reactNative);
React_Redux/weather_search/src/components/app.js
awg3/LearnCodeImprove
import React from 'react'; import { Component } from 'react'; import SearchBar from '../containers/search_bar'; import WeatherList from '../containers/weather_list'; import Header from '../components/header'; import Footer from '../components/footer'; export default class App extends Component { render() { return ( <div> <Header /> <SearchBar /> <WeatherList /> <Footer /> </div> ); } }
src/routes/system/User/ModalForm.js
daizhen256/i5xwxdoctor-web
import React from 'react' import PropTypes from 'prop-types' import { Form, Input, InputNumber, Radio, Modal, Icon } from 'antd' import { validPhone } from '../../../utils/utilsValid' const FormItem = Form.Item const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } } const ModalForm = ({ modal: { curItem, type, visible }, loading, form: { getFieldDecorator, validateFields, resetFields }, onOk, onCancel }) => { function handleOk () { validateFields((errors, values) => { if (errors) { return } const data = { ...values, id: curItem.id } onOk(data) }) } const modalFormOpts = { title: type === 'create' ? <div><Icon type="plus-circle-o" /> 新建用户</div> : <div><Icon type="edit" /> 修改用户</div>, visible, wrapClassName: 'vertical-center-modal', confirmLoading: loading, onOk: handleOk, onCancel, afterClose() { resetFields() //必须项,编辑后如未确认保存,关闭时必须重置数据 } } return ( <Modal {...modalFormOpts}> <Form> <FormItem label='用户名:' hasFeedback {...formItemLayout}> {getFieldDecorator('name', { initialValue: curItem.name, rules: [ { required: true, message: '用户名不能为空' } ] })(<Input />)} </FormItem> <FormItem label='手机号:' hasFeedback {...formItemLayout}> {getFieldDecorator('mobile', { initialValue: curItem.mobile, rules: [ { required: true, message: '手机号不能为空' }, { validator: validPhone } ] })(<Input />)} </FormItem> <FormItem label='邮箱:' hasFeedback {...formItemLayout}> {getFieldDecorator('email', { initialValue: curItem.email, rules: [ { required: true, message: '邮箱不能为空' }, { type: 'email', message: '邮箱格式不正确' } ] })(<Input />)} </FormItem> </Form> </Modal> ) } ModalForm.propTypes = { modal: PropTypes.object.isRequired, form: PropTypes.object.isRequired } export default Form.create()(ModalForm)
app/components/Charts/Donut/index.js
prudhvisays/newsb
import React from 'react'; import './Donut.css'; let donut; class DonutChart extends React.Component { //eslint-disable-line constructor(props) { super(props); this.state = { data: [ { label: 'Target', value: 100 }, { label: 'Total', value: 0 }, ] } this.targets = this.targets.bind(this); this.setValue = this.setValue.bind(this); } componentDidMount() { const { total } = this.props.stateOrderStats; donut = Morris.Donut({ //eslint-disable-line element: 'chart', data: this.state.data, labelColor: '#333', size: true, colors: [ '#6bc9c5', '#FFCA28', ], }); } componentWillReceiveProps(nextProps) { const { completed } = nextProps.stateOrderStats; if (nextProps.stateOrderStats.completed !== this.props.stateOrderStats.completed) { this.targets(completed); } } targets(total) { this.setState({ data: [ { label: 'Target', value: 100 }, { label: 'Total', value: total }, ] },this.setValue) } setValue() { donut.setData(this.state.data); } render() { return ( <div id="chart"></div> ); } } export default DonutChart;
src/svg-icons/content/report.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentReport = (props) => ( <SvgIcon {...props}> <path d="M15.73 3H8.27L3 8.27v7.46L8.27 21h7.46L21 15.73V8.27L15.73 3zM12 17.3c-.72 0-1.3-.58-1.3-1.3 0-.72.58-1.3 1.3-1.3.72 0 1.3.58 1.3 1.3 0 .72-.58 1.3-1.3 1.3zm1-4.3h-2V7h2v6z"/> </SvgIcon> ); ContentReport = pure(ContentReport); ContentReport.displayName = 'ContentReport'; ContentReport.muiName = 'SvgIcon'; export default ContentReport;
src/elements/title.js
bokuweb/re-bulma
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styles from '../../build/styles'; export default class Title extends Component { static propTypes = { children: PropTypes.any, className: PropTypes.string, size: PropTypes.oneOf([ 'is1', 'is2', 'is3', 'is4', 'is5', 'is6', ]), }; static defaultProps = { className: '', }; createClassName() { return [ styles.title, styles[this.props.size], this.props.className, ].join(' ').trim(); } render() { return ( <p {...this.props} className={this.createClassName()}> {this.props.children} </p> ); } }
src/components/options/OptionsFeedbackText.js
m0sk1t/react_email_editor
import React from 'react'; const OptionsFeedbackText = ({ block, language, onPropChange }) => { const fontSize = block.options.container.fontSize.match(/\d+/)?block.options.container.fontSize.match(/\d+/)[0]: '16'; return ( <div> <div> <label>{language["Custom style"]}: <input type="checkbox" checked={block.options.container.customStyle? 'checked': '' } onChange={(e) => onPropChange('customStyle', !block.options.container.customStyle, true)} /></label> </div> <div> <label>{language["Color"]}: <input type="color" value={block.options.container.color} onChange={(e) => onPropChange('color', e.target.value, true)} /></label> </div> <div> <label>{language["Background"]}: <input type="color" value={block.options.container.backgroundColor} onChange={(e) => onPropChange('backgroundColor', e.target.value, true)} /></label> </div> <hr /> <div> <label>{language["Font size"]}: <input type="number" value={fontSize.match(/\d+/)[0]} onChange={(e) => onPropChange('fontSize', `${e.target.value}px`, true)} /></label> </div> <div> <label> {language["Font family"]}: <select style={{width: '50%'}} onChange={(e) => onPropChange('fontFamily', e.target.value, true)}> <option value="Georgia, serif">Georgia, serif</option> <option value="Tahoma, Geneva, sans-serif">Tahoma, Geneva, sans-serif</option> <option value="Verdana, Geneva, sans-serif">Verdana, Geneva, sans-serif</option> <option value="Arial, Helvetica, sans-serif">Arial, Helvetica, sans-serif</option> <option value="Impact, Charcoal, sans-serif">Impact, Charcoal, sans-serif</option> <option value="'Times New Roman', Times, serif">"Times New Roman", Times, serif</option> <option value="'Courier New', Courier, monospace">"Courier New", Courier, monospace</option> <option value="'Arial Black', Gadget, sans-serif">"Arial Black", Gadget, sans-serif</option> <option value="'Lucida Console', Monaco, monospace">"Lucida Console", Monaco, monospace</option> <option value="'Comic Sans MS', cursive, sans-serif">"Comic Sans MS", cursive, sans-serif</option> <option value="'Trebuchet MS', Helvetica, sans-serif">"Trebuchet MS", Helvetica, sans-serif</option> <option value="'Lucida Sans Unicode', 'Lucida Grande', sans-serif">"Lucida Sans Unicode", "Lucida Grande", sans-serif</option> <option value="'Palatino Linotype', 'Book Antiqua', Palatino, serif">"Palatino Linotype", "Book Antiqua", Palatino, serif</option> </select> </label> </div> <hr /> <div> <label> {language["Icons area size"]}: <input type="range" min="0" max="3" step="1" value={block.options.elements[0].iconsSize} onChange={(e) => { switch (+e.target.value) { case 0: onPropChange('width', '50', false, 0); onPropChange('width', '500', false, 1); break; case 1: onPropChange('width', '100', false, 0); onPropChange('width', '450', false, 1); break; case 2: onPropChange('width', '200', false, 0); onPropChange('width', '350', false, 1); break; case 3: onPropChange('width', '275', false, 0); onPropChange('width', '275', false, 1); break; default: break; } onPropChange('iconsSize', e.target.value, false, 0); }} /> </label> </div> <div> <label>{language["Icons position"]}: <select onChange={(e) => onPropChange('textAlign', e.target.value, false, 0)}> <option value="left">{language["left"]}</option> <option value="right">{language["right"]}</option> </select> </label> </div> <div> <label> {language["Icons type"]}: <select value={block.options.elements[0].like_source.match(/_\w+/)[0].split('').splice(1).join('')} onChange={(e) => { const el = block.options.elements[0]; onPropChange('like_source', el.like_source.replace(/like_\w+/, `like_${e.target.value}`), false, 0); onPropChange('dislike_source', el.dislike_source.replace(/dislike_\w+/, `dislike_${e.target.value}`), false, 0); onPropChange('neutral_source', el.neutral_source.replace(/neutral_\w+/, `neutral_${e.target.value}`), false, 0); }}> <option value="3d">3d</option> <option value="round">round</option> <option value="square">square</option> <option value="material">material</option> </select> </label> </div> <hr /> <div> <label> {language["Like"]}: <input type="checkbox" checked={block.options.elements[0].like_display === ''? 'none': ''} onChange={(e) => onPropChange('like_display', (block.options.elements[0].like_display === ''? 'none': ''), false, 0)} /> <input type="text" value={block.options.elements[0].like_link} onChange={(e) => onPropChange('like_link', e.target.value, false, 0)} /> </label> </div> <div> <label> {language["Dislike"]}: <input type="checkbox" checked={block.options.elements[0].dislike_display === ''? 'none': ''} onChange={(e) => onPropChange('dislike_display', (block.options.elements[0].dislike_display === ''? 'none': ''), false, 0)} /> <input type="text" value={block.options.elements[0].dislike_link} onChange={(e) => onPropChange('dislike_link', e.target.value, false, 0)} /> </label> </div> <div> <label> {language["Neutral"]}: <input type="checkbox" checked={block.options.elements[0].neutral_display === ''? 'none': ''} onChange={(e) => onPropChange('neutral_display', (block.options.elements[0].neutral_display === ''? 'none': ''), false, 0)} /> <input type="text" value={block.options.elements[0].neutral_link} onChange={(e) => onPropChange('neutral_link', e.target.value, false, 0)} /> </label> </div> </div> ); }; export default OptionsFeedbackText;
fields/types/cloudinaryimage/CloudinaryImageFilter.js
Ftonso/keystone
import classNames from 'classnames'; import React from 'react'; import { SegmentedControl } from 'elemental'; var PasswordFilter = React.createClass({ getInitialState () { return { checked: this.props.value || true, }; }, toggleChecked (checked) { this.setState({ checked: checked, }); }, renderToggle () { let options = [ { label: 'Is Set', value: true }, { label: 'Is NOT Set', value: false } ]; return <SegmentedControl equalWidthSegments options={options} value={this.state.checked} onChange={this.toggleChecked} />; }, render () { let { field } = this.props; let { checked } = this.state; return this.renderToggle(); } }); module.exports = PasswordFilter;
examples/autocomplete/src/App-Multi-Index.js
algolia/react-instantsearch
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Autosuggest from 'react-autosuggest'; import { InstantSearch, Configure, Index, Highlight, connectAutoComplete, } from 'react-instantsearch-dom'; import algoliasearch from 'algoliasearch/lite'; const searchClient = algoliasearch( 'latency', '6be0576ff61c053d5f9a3225e2a90f76' ); const App = () => ( <InstantSearch searchClient={searchClient} indexName="instant_search"> <AutoComplete /> <Configure hitsPerPage={1} /> <Index indexName="bestbuy" /> <Index indexName="airbnb" /> </InstantSearch> ); class Example extends Component { static propTypes = { hits: PropTypes.arrayOf(PropTypes.object).isRequired, currentRefinement: PropTypes.string.isRequired, refine: PropTypes.func.isRequired, }; state = { value: this.props.currentRefinement, }; onChange = (event, { newValue }) => { this.setState({ value: newValue, }); }; onSuggestionsFetchRequested = ({ value }) => { this.props.refine(value); }; onSuggestionsClearRequested = () => { this.props.refine(); }; getSuggestionValue(hit) { return hit.name; } renderSuggestion(hit) { return <Highlight attribute="name" hit={hit} tagName="mark" />; } renderSectionTitle(section) { return section.index; } getSectionSuggestions(section) { return section.hits; } render() { const { hits } = this.props; const { value } = this.state; const inputProps = { placeholder: 'Search for a product...', onChange: this.onChange, value, }; return ( <Autosuggest suggestions={hits} multiSection={true} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} getSuggestionValue={this.getSuggestionValue} renderSuggestion={this.renderSuggestion} inputProps={inputProps} renderSectionTitle={this.renderSectionTitle} getSectionSuggestions={this.getSectionSuggestions} /> ); } } const AutoComplete = connectAutoComplete(Example); export default App;
application/components/user/orders/index.js
ronanamsterdam/squaredcoffee
import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; import Button from 'react-native-button' import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import AppActions from '../../../actions'; import styles from '../../../statics/styles'; class Orders extends Component { testClick() { this.props.actions.appTestAction('some text'); } render = () => { return ( <View style={{ ...styles.container, height: '100%' }} > <Button style={styles.buttonStyle} onPress={this.testClick.bind(this)} > TestAction #1 </Button> </View> ); } }; const mapState = (state) => { return { justAWholeState: state.testReducer }; }; const mapDispatch = dispatch => ({ actions: bindActionCreators(AppActions, dispatch) }); export default connect(mapState, mapDispatch)(Orders)
src/containers/Root.js
prashantpawar/blockapps-js-tutorial
import React from 'react' import { Provider } from 'react-redux' import { Router } from 'react-router' export default class Root extends React.Component { static propTypes = { history: React.PropTypes.object.isRequired, routes: React.PropTypes.element.isRequired, store: React.PropTypes.object.isRequired } get content () { return ( <Router history={this.props.history}> {this.props.routes} </Router> ) } get devTools () { if (__DEBUG__) { if (__DEBUG_NEW_WINDOW__) { require('../redux/utils/createDevToolsWindow')(this.props.store) } else { const DevTools = require('containers/DevTools') return <DevTools /> } } } render () { return ( <Provider store={this.props.store}> <div style={{ height: '100%' }}> {this.content} {this.devTools} </div> </Provider> ) } }
app/main.js
billyct/fil
import React from 'react'; import {Provider} from 'react-redux'; import store from 'store'; import App from 'components/App'; React.render( <Provider store={store}> {() => <App />} </Provider>, document.body );
app/javascript/mastodon/containers/mastodon.js
alarky/mastodon
import React from 'react'; import { Provider } from 'react-redux'; import PropTypes from 'prop-types'; import configureStore from '../store/configureStore'; import { updateTimeline, deleteFromTimelines, refreshHomeTimeline, connectTimeline, disconnectTimeline, } from '../actions/timelines'; import { showOnboardingOnce } from '../actions/onboarding'; import { updateNotifications, refreshNotifications } from '../actions/notifications'; import BrowserRouter from 'react-router-dom/BrowserRouter'; import Route from 'react-router-dom/Route'; import ScrollContext from 'react-router-scroll/lib/ScrollBehaviorContext'; import UI from '../features/ui'; import { hydrateStore } from '../actions/store'; import createStream from '../stream'; import { IntlProvider, addLocaleData } from 'react-intl'; import { getLocale } from '../locales'; const { localeData, messages } = getLocale(); addLocaleData(localeData); const store = configureStore(); const initialState = JSON.parse(document.getElementById('initial-state').textContent); store.dispatch(hydrateStore(initialState)); export default class Mastodon extends React.PureComponent { static propTypes = { locale: PropTypes.string.isRequired, }; componentDidMount() { const { locale } = this.props; const streamingAPIBaseURL = store.getState().getIn(['meta', 'streaming_api_base_url']); const accessToken = store.getState().getIn(['meta', 'access_token']); const setupPolling = () => { this.polling = setInterval(() => { store.dispatch(refreshHomeTimeline()); store.dispatch(refreshNotifications()); }, 20000); }; const clearPolling = () => { clearInterval(this.polling); this.polling = undefined; }; this.subscription = createStream(streamingAPIBaseURL, accessToken, 'user', { connected () { clearPolling(); store.dispatch(connectTimeline('home')); }, disconnected () { setupPolling(); store.dispatch(disconnectTimeline('home')); }, received (data) { switch(data.event) { case 'update': store.dispatch(updateTimeline('home', JSON.parse(data.payload))); break; case 'delete': store.dispatch(deleteFromTimelines(data.payload)); break; case 'notification': store.dispatch(updateNotifications(JSON.parse(data.payload), messages, locale)); break; } }, reconnected () { clearPolling(); store.dispatch(connectTimeline('home')); store.dispatch(refreshHomeTimeline()); store.dispatch(refreshNotifications()); }, }); // Desktop notifications if (typeof window.Notification !== 'undefined' && Notification.permission === 'default') { Notification.requestPermission(); } store.dispatch(showOnboardingOnce()); } componentWillUnmount () { if (typeof this.subscription !== 'undefined') { this.subscription.close(); this.subscription = null; } if (typeof this.polling !== 'undefined') { clearInterval(this.polling); this.polling = null; } } render () { const { locale } = this.props; return ( <IntlProvider locale={locale} messages={messages}> <Provider store={store}> <BrowserRouter basename='/web'> <ScrollContext> <Route path='/' component={UI} /> </ScrollContext> </BrowserRouter> </Provider> </IntlProvider> ); } }
src/components/App.js
hailin1008/react-exercise
import React from 'react' import AppointmentTable from '../containers/AppointmentTable' const App = () => ( <AppointmentTable/> ) export default App
src/components/example.js
richard-lopes/webpack-example
import React from 'react'; import connectToStores from 'alt/utils/connectToStores'; import DummyStore from 'stores/dummyStore'; import DummyActions from 'actions/dummyActions'; @connectToStores class Example extends React.Component { constructor(props) { super(props); this.state = { name: props.name } } static getStores(props) { return [DummyStore]; } static getPropsFromStores(props) { return DummyStore.getState(); } render() { return ( <div> <input type="text" value={this.state.name} onChange={this.onChange}/> <h1>It works: {this.props.name}</h1> </div> ); } onChange = evt => { this.setState({name: evt.target.value}); DummyActions.updateName(evt.target.value); } } export default Example;
src/Components/SubPage.js
ashwinath/personal-website-2.0
import React, { Component } from 'react'; import PageDetails from '../Components/PageDetails'; import PropTypes from 'prop-types'; class SubPage extends Component { render() { return ( <div className="col-xs-9 main-section"> <PageDetails pageName={this.props.pageName}/> {this.props.children} </div> ); } } PageDetails.propTypes = { pageName: PropTypes.string } export default SubPage;
src/One.js
ekazakov/catcher
import React, { Component } from 'react'; export class One extends Component { render() { return <div> <div>One</div> <div>{this.props.children}</div> </div>; } }
src/components/Projects.js
jasonrundell/jasonrundell-react-site-2017
import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { markPostAsRread } from '../actions/markPostAsRread' import { READ, UNREAD } from '../constants' import './Projects.css'; const ProjectPostLinkList = ({ projects = () => {} }) => { return <ul> { projects.map((post, i) => <li key={ i }> <Link href={`/projects/${post.slug}`}>{post.title}</Link> <button onClick={() => markPostAsRread(post.id)}>Mark As Read</button> </li> ) } </ul>; }; const Projects = ({ projects = {} }) => ( <div> <div className="ls-row"> <div className="ls-col-100"> <h1>Projects</h1> <ProjectPostLinkList projects={ projects } /> </div> </div> </div> ); const mapStateToProps = (state) => ({ projects: state.projects }); const mapDispatchToProps = (dispatch) => ({ markPostAsRead: () => dispatch({ type: READ }), markPostAsUnread: () => dispatch({ type: UNREAD }) }); export default connect(mapStateToProps, mapDispatchToProps)(Projects);
examples/shared-root/app.js
tmbtech/react-router
import React from 'react'; import { history } from 'react-router/lib/HashHistory'; import { Router, Route, Link } from 'react-router'; var App = React.createClass({ render() { return ( <div> <p> This illustrates how routes can share UI w/o sharing the url, when routes have no path, they never match themselves but their children can, allowing "/signin" and "/forgot-password" to both be render in the <code>SignedOut</code> component. </p> <ol> <li><Link to="/home">Home</Link></li> <li><Link to="/signin">Sign in</Link></li> <li><Link to="/forgot-password">Forgot Password</Link></li> </ol> {this.props.children} </div> ); } }); var SignedIn = React.createClass({ render() { return ( <div> <h2>Signed In</h2> {this.props.children} </div> ); } }); var Home = React.createClass({ render() { return ( <h3>Welcome home!</h3> ); } }); var SignedOut = React.createClass({ render() { return ( <div> <h2>Signed Out</h2> {this.props.children} </div> ); } }); var SignIn = React.createClass({ render() { return ( <h3>Please sign in.</h3> ); } }); var ForgotPassword = React.createClass({ render() { return ( <h3>Forgot your password?</h3> ); } }); React.render(( <Router history={history}> <Route path="/" component={App}> <Route component={SignedOut}> <Route path="signin" component={SignIn}/> <Route path="forgot-password" component={ForgotPassword}/> </Route> <Route component={SignedIn}> <Route path="home" component={Home}/> </Route> </Route> </Router> ), document.getElementById('example'));
blueocean-material-icons/src/js/components/svg-icons/navigation/chevron-left.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const NavigationChevronLeft = (props) => ( <SvgIcon {...props}> <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/> </SvgIcon> ); NavigationChevronLeft.displayName = 'NavigationChevronLeft'; NavigationChevronLeft.muiName = 'SvgIcon'; export default NavigationChevronLeft;
src/components/singleHeading/index.js
nickfranciosi/terminal-frontend
import React from 'react'; import ScrollListener from '../scrollListener'; import ScrollAnimate from '../scrollAnimate'; import styles from './style.module.css'; class SingleHeading extends React.Component { constructor(props) { super(props); this.state = { animate: false, }; this.triggerAnimation = this.triggerAnimation.bind(this); } triggerAnimation() { if(!this.state.animate) { this.setState({ animate: true, }); } } render() { return ( <ScrollListener onEnter={() => this.triggerAnimation()} offset={650}> <div className={styles.container}> <h3 className={styles.headline}> <ScrollAnimate animate={this.state.animate} > {this.props.children} </ScrollAnimate> </h3> </div> </ScrollListener> ); } } export default SingleHeading;
storybook/stories/button.story.js
3846masa/mastodon
import React from 'react'; import { action, storiesOf } from '@kadira/storybook'; import Button from 'mastodon/components/button'; storiesOf('Button', module) .add('default state', () => ( <Button text="submit" onClick={action('clicked')} /> )) .add('secondary', () => ( <Button secondary text="submit" onClick={action('clicked')} /> )) .add('disabled', () => ( <Button disabled text="submit" onClick={action('clicked')} /> )) .add('block', () => ( <Button block text="submit" onClick={action('clicked')} /> ));
src/scenes/Layout/components/Representation/components/Week/Week.js
czonios/schedule-maker-app
import React from 'react'; import './week.css'; import { Grid, Header } from 'semantic-ui-react'; import dateService from '../../../../../../services/dates/dateService'; import WeekdayColumns from '../WeekDayColumns/WeekdayColumns'; import DayOfWeek from './components/DayOfWeek/DayOfWeek'; import PropTypes from 'prop-types'; const propTypes = { events: PropTypes.array.isRequired }; // const defaultProps = {}; const Week = ({ events }) => ( <div className="week"> <Grid columns={8} celled> <Grid.Row> <Grid.Column><Header></Header></Grid.Column> <WeekdayColumns /> </Grid.Row> {dateService.OClocks24.map((oclock, i) => ( <Grid.Row key={i}> <Grid.Column className="time" width={2}> {oclock} </Grid.Column> <Grid.Column> <DayOfWeek time={oclock} day="mon" /> </Grid.Column> <Grid.Column> <DayOfWeek time={oclock} day="tue" /> </Grid.Column> <Grid.Column> <DayOfWeek time={oclock} day="wed" /> </Grid.Column> <Grid.Column> <DayOfWeek time={oclock} day="thu" /> </Grid.Column> <Grid.Column> <DayOfWeek time={oclock} day="fri" /> </Grid.Column> <Grid.Column> <DayOfWeek time={oclock} day="sat" /> </Grid.Column> <Grid.Column> <DayOfWeek time={oclock} day="sun" /> </Grid.Column> </Grid.Row> ))} </Grid> </div> ); Week.propTypes = propTypes; // Week.defaultProps = defaultProps; export default Week;
src/organizer/workshops/create.js
GrayTurtle/rocket-workshop
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import DatePicker from 'react-datepicker'; import { firebaseConnect, isLoaded, isEmpty } from 'react-redux-firebase'; import { connect } from 'react-redux'; import { compose } from 'redux'; import moment from 'moment'; import './create.css'; import 'react-datepicker/dist/react-datepicker.css'; import uid from 'uid'; class Create extends Component { static propTypes = { }; constructor(props) { super(props); this.state = { name: '', date: moment(), id: uid() }; } onChange = ({ target: { value }}) => { this.setState({ name: value }); } handleChange = (date) => { this.setState({ date }); } handleCreate = () => { const { firebase, match: { params: { organizerId } }, history } = this.props; const { name, date, id } = this.state; firebase.set(`/organizers/${organizerId}/workshops/${id}`, { title: name, date: date.toString(), id, attendee: [], step: 0, status: 'WORKING', mentors: [], presenter: '', steps: [] }) .then(() => { history.push(`/organizer/${organizerId}/workshops/${id}/edit`); }) } render() { const { name, date } = this.state; return ( <div className="create-orgnization"> <input className="title" type="text" name="name" value={name} onChange={this.onChange} placeholder="Workshop Title" /> <DatePicker className="workshop-date" selected={date} onChange={this.handleChange} placeholderText="Date of Workshop" showTimeSelect timeIntervals={15} dateFormat="LLL" /> <button className="create-workshop" name="create" onClick={this.handleCreate}>Create</button> </div> ); } } export default firebaseConnect()(Create);
src/widgets/ContentBanner/ReactionNumbers.js
mydearxym/mastani
import React from 'react' import { prettyNum, numberWithCommas } from '@/utils/helper' import { NumbersInfo, NumberSection, NumberDivider, NumberTitle, NumberItem, } from './styles/reaction_numbers' const ReactionNumbers = ({ data: { views, collectsCount, upvotesCount } }) => ( <NumbersInfo> <NumberSection readOnly> <NumberTitle readOnly>浏览</NumberTitle> <NumberItem readOnly>{prettyNum(views)}</NumberItem> </NumberSection> <NumberDivider /> {upvotesCount >= 0 && ( <> <NumberSection> <NumberTitle>喜欢</NumberTitle> <NumberItem>{numberWithCommas(upvotesCount)}</NumberItem> </NumberSection> <NumberDivider /> </> )} {collectsCount >= 0 && ( <NumberSection> <NumberTitle>收藏</NumberTitle> <NumberItem>{numberWithCommas(collectsCount)}</NumberItem> </NumberSection> )} {/* <NumberDivider /> <NumberSection> <NumberTitle>关注</NumberTitle> <NumberItem>TD</NumberItem> </NumberSection> */} </NumbersInfo> ) export default React.memo(ReactionNumbers)
app/javascript/mastodon/components/autosuggest_emoji.js
tootcafe/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import unicodeMapping from '../features/emoji/emoji_unicode_mapping_light'; import { assetHost } from 'mastodon/utils/config'; export default class AutosuggestEmoji extends React.PureComponent { static propTypes = { emoji: PropTypes.object.isRequired, }; render () { const { emoji } = this.props; let url; if (emoji.custom) { url = emoji.imageUrl; } else { const mapping = unicodeMapping[emoji.native] || unicodeMapping[emoji.native.replace(/\uFE0F$/, '')]; if (!mapping) { return null; } url = `${assetHost}/emoji/${mapping.filename}.svg`; } return ( <div className='autosuggest-emoji'> <img className='emojione' src={url} alt={emoji.native || emoji.colons} /> {emoji.colons} </div> ); } }
src/templates/product-page.js
svj2291/svj2291.github.io
import React from 'react' import Features from '../components/Features' import Testimonials from '../components/Testimonials' import Pricing from '../components/Pricing' export const ProductPageTemplate = ({ image, title, heading, description, intro, main, testimonials, fullImage, pricing, }) => ( <section className="section section--gradient"> <div className="container"> <div className="section"> <div className="columns"> <div className="column is-10 is-offset-1"> <div className="content"> <div className="full-width-image-container margin-top-0" style={{ backgroundImage: `url(${image})` }} > <h2 className="has-text-weight-bold is-size-1" style={{ boxShadow: '0.5rem 0 0 #f40, -0.5rem 0 0 #f40', backgroundColor: '#f40', color: 'white', padding: '1rem', }} > {title} </h2> </div> <div className="columns"> <div className="column is-7"> <h3 className="has-text-weight-semibold is-size-2"> {heading} </h3> <p>{description}</p> </div> </div> <Features gridItems={intro.blurbs} /> <div className="columns"> <div className="column is-7"> <h3 className="has-text-weight-semibold is-size-3"> {main.heading} </h3> <p>{main.description}</p> </div> </div> <div className="tile is-ancestor"> <div className="tile is-vertical"> <div className="tile"> <div className="tile is-parent is-vertical"> <article className="tile is-child"> <img style={{ borderRadius: '5px' }} src={main.image1.image} alt={main.image1.alt} /> </article> </div> <div className="tile is-parent"> <article className="tile is-child"> <img style={{ borderRadius: '5px' }} src={main.image2.image} alt={main.image2.alt} /> </article> </div> </div> <div className="tile is-parent"> <article className="tile is-child"> <img style={{ borderRadius: '5px' }} src={main.image3.image} alt={main.image3.alt} /> </article> </div> </div> </div> <Testimonials testimonials={testimonials} /> <div className="full-width-image-container" style={{ backgroundImage: `url(${fullImage})` }} /> <h2 className="has-text-weight-semibold is-size-2"> {pricing.heading} </h2> <p className="is-size-5">{pricing.description}</p> <Pricing data={pricing.plans} /> </div> </div> </div> </div> </div> </section> ) export default ({ data }) => { const { frontmatter } = data.markdownRemark return ( <ProductPageTemplate image={frontmatter.image} title={frontmatter.title} heading={frontmatter.heading} description={frontmatter.description} intro={frontmatter.intro} main={frontmatter.main} testimonials={frontmatter.testimonials} fullImage={frontmatter.full_image} pricing={frontmatter.pricing} /> ) } export const productPageQuery = graphql` query ProductPage($id: String!) { markdownRemark(id: { eq: $id }) { frontmatter { title image heading description intro { blurbs { image text } heading description } main { heading description image1 { alt image } image2 { alt image } image3 { alt image } } testimonials { author quote } full_image pricing { heading description plans { description items plan price } } } } } `
src/ui/components/views/Offline.js
scrollback/pure
/* @flow */ import React, { Component } from 'react'; import Radium from 'radium'; import shallowCompare from 'react-addons-shallow-compare'; import Colors from '../../Colors'; import Page from './Page/Page'; const styles = { container: { padding: 16, backgroundColor: Colors.white, }, image: { marginLeft: 16, marginRight: 16, marginTop: 48, marginBottom: 48, }, header: { color: Colors.darkGrey, fontSize: 20, }, footer: { color: Colors.darkGrey, }, }; type Props = { style?: any; } class Offline extends Component<void, Props, void> { static propTypes = { style: Page.propTypes.style, }; shouldComponentUpdate(nextProps: Props, nextState: any): boolean { return shallowCompare(this, nextProps, nextState); } render() { return ( <Page {...this.props} style={[ styles.container, this.props.style ]}> <div style={styles.header}>Network unavailable!</div> <img style={styles.image} src={require('../../../../assets/offline-balloon.png')} /> <div style={styles.footer}>Waiting for connection…</div> </Page> ); } } export default Radium(Offline);
fields/types/cloudinaryimage/CloudinaryImageFilter.js
joerter/keystone
import React from 'react'; import { SegmentedControl } from 'elemental'; var PasswordFilter = React.createClass({ getInitialState () { return { checked: this.props.value || true, }; }, toggleChecked (checked) { this.setState({ checked: checked, }); }, render () { const options = [ { label: 'Is Set', value: true }, { label: 'Is NOT Set', value: false }, ]; return <SegmentedControl equalWidthSegments options={options} value={this.state.checked} onChange={this.toggleChecked} />; }, }); module.exports = PasswordFilter;
src/App.js
laurids-reichardt/Currency-Exchange-Rates
// library imports import React, { Component } from 'react'; import { Divider, Container, Grid, Icon, Segment } from 'semantic-ui-react'; import axios from 'axios'; // component imports import Header from './components/Header'; import InfoText from './components/InfoText'; import AmountInput from './components/AmountInput'; import CurrencyDropdown from './components/CurrencyDropdown'; import CurrencyDisplay from './components/CurrencyDisplay'; import Chart from './components/Chart'; import ImplementationInfo from './components/ImplementationInfo'; import Footer from './components/Footer'; // utility component imports import DefaultState from './utilities/DefaultState'; import DropdownOptions from './utilities/DropdownOptions'; import ExchangeRateData from './utilities/ExchangeRateData'; class App extends Component { constructor(props) { super(props); // get the initial default state this.state = DefaultState; // bind handler functions to the App component this.handleSourceCurrencyChange = this.handleSourceCurrencyChange.bind( this ); this.handleTargetCurrencyChange = this.handleTargetCurrencyChange.bind( this ); this.handleAmountChange = this.handleAmountChange.bind(this); this.handleIconClick = this.handleIconClick.bind(this); } // make initial api calls to fixer.io and set initial currency amount to 1 componentDidMount() { // initialize utility component objects and put them in utils const utils = { fx: new ExchangeRateData(), dropdownOptions: new DropdownOptions() }; // get urls for the api calls to fixer.io const urls = utils.fx.getURLs(); // make api calls and kick off app by setting amount to 1 // also put utils into internal state axios .all(urls) .then(arr => { utils.fx.init(arr); this.setState({ utils: utils }, () => { this.handleAmountChange(0, { value: 1 }); }); }) .catch(error => console.log(error)); } // handler functions - handle input changes from the input field, dropdowns and switch button handleSourceCurrencyChange(event, data) { this.setState( { sourceCurrency: data.value }, this.updateTargetCurrencyOptions ); } handleTargetCurrencyChange(event, data) { this.setState({ targetCurrency: data.value }, this.updateResult); } handleAmountChange(event, data) { this.setState( { amount: Number(data.value), input: data.value }, this.updateResult ); } handleIconClick() { const sourceCurrency = this.state.sourceCurrency; this.setState({ sourceCurrency: this.state.targetCurrency }); this.setState({ targetCurrency: sourceCurrency }, this.updateResult); } // update functions - react to in the state (e.g. change from dropdown) and update state accordingly // update target currency dropdown options (deactivate source currency from possible selection) updateTargetCurrencyOptions() { this.setState( { targetCurrencyOptions: this.state.utils.dropdownOptions.getTargetCurrencyOptions( this.state.sourceCurrency ) }, this.updateTargetCurrency ); } // if source currency = target currency, target currency jumps to the next option updateTargetCurrency() { this.setState( { targetCurrency: this.state.utils.dropdownOptions.getTargetCurrency( this.state.sourceCurrency, this.state.targetCurrency ) }, this.updateResult ); } // calculate resulting amount from currency conversion updateResult() { this.setState( { result: this.state.utils.fx.get( this.state.sourceCurrency, this.state.targetCurrency, this.state.amount ) }, this.updateChartData ); } // update chart data updateChartData() { this.setState({ chartData: this.state.utils.fx.getChartData( this.state.sourceCurrency, this.state.targetCurrency ) }); } render() { return ( <div className="App"> <Container text textAlign="justified"> <Header /> <InfoText /> <Divider horizontal>Selection</Divider> {/* grid displays the input field, currency dropdowns and the currency switch button */} <Grid> <Grid.Row> <Grid.Column> {/* allows the user to insert the desired amount of currency */} <AmountInput value={this.state.input} onChange={this.handleAmountChange} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={7}> {/* dropdown element to select the source currency */} <CurrencyDropdown currency={this.state.sourceCurrency} options={this.state.sourceCurrencyOptions} onChange={this.handleSourceCurrencyChange} /> </Grid.Column> <Grid.Column textAlign="center" verticalAlign="middle" width={2}> {/* icon button that allows to switches the source and target currency */} <Icon name="exchange" size="large" onClick={this.handleIconClick} /> </Grid.Column> <Grid.Column width={7}> {/* dropdown element to select the target currency */} <CurrencyDropdown currency={this.state.targetCurrency} options={this.state.targetCurrencyOptions} onChange={this.handleTargetCurrencyChange} /> </Grid.Column> </Grid.Row> </Grid> <Divider horizontal>Output</Divider> {/* presents the information resulting from the user input */} <Grid textAlign="center" verticalAlign="middle"> <Grid.Row> <Grid.Column width={7}> <Segment color="red"> {' '} <CurrencyDisplay currency={this.state.sourceCurrency} amount={this.state.amount} />{' '} </Segment> </Grid.Column> <Grid.Column width={2}> <Icon name="long arrow right" size="large" /> </Grid.Column> <Grid.Column width={7}> <Segment color="green"> {' '} <CurrencyDisplay currency={this.state.targetCurrency} amount={this.state.result} />{' '} </Segment> </Grid.Column> </Grid.Row> </Grid> <Chart data={this.state.chartData} /> <Divider horizontal>Implementation</Divider> <ImplementationInfo /> <Divider horizontal>Impress</Divider> <Footer /> </Container> </div> ); } } export default App;
src/components/Layout/Layout.js
renegens/blog
// @flow strict import React from 'react'; import Helmet from 'react-helmet'; import { withPrefix } from 'gatsby'; import type { Node as ReactNode } from 'react'; import { useSiteMetadata } from '../../hooks'; import styles from './Layout.module.scss'; type Props = { children: ReactNode, title: string, description?: string, socialImage? :string }; const Layout = ({ children, title, description, socialImage }: Props) => { const { author, url } = useSiteMetadata(); const metaImage = socialImage != null ? socialImage : author.photo; const metaImageUrl = url + withPrefix(metaImage); return ( <div className={styles.layout}> <Helmet> <html lang="en" /> <title>{title}</title> <meta name="description" content={description} /> <meta property="og:site_name" content={title} /> <meta property="og:image" content={metaImageUrl} /> <meta name="twitter:card" content="summary" /> <meta name="twitter:title" content={title} /> <meta name="twitter:description" content={description} /> <meta name="twitter:image" content={metaImageUrl} /> </Helmet> {children} </div> ); }; export default Layout;
node_modules/react-bootstrap/es/Jumbotron.js
newphew92/newphew92.github.io
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import classNames from 'classnames'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'div' }; var Jumbotron = function (_React$Component) { _inherits(Jumbotron, _React$Component); function Jumbotron() { _classCallCheck(this, Jumbotron); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Jumbotron.prototype.render = function render() { var _props = this.props; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return Jumbotron; }(React.Component); Jumbotron.propTypes = propTypes; Jumbotron.defaultProps = defaultProps; export default bsClass('jumbotron', Jumbotron);
src/encoded/static/components/browse/SearchView.js
hms-dbmi/fourfront
'use strict'; import React from 'react'; import memoize from 'memoize-one'; import _ from 'underscore'; import url from 'url'; import { getAbstractTypeForType, getAllSchemaTypesFromSearchContext } from '@hms-dbmi-bgm/shared-portal-components/es/components/util/schema-transforms'; import { SearchView as CommonSearchView } from '@hms-dbmi-bgm/shared-portal-components/es/components/browse/SearchView'; import { console, isSelectAction,schemaTransforms, logger } from '@hms-dbmi-bgm/shared-portal-components/es/components/util'; import { columnExtensionMap } from './columnExtensionMap'; import { Schemas } from './../util'; import { TitleAndSubtitleBeside, PageTitleContainer, TitleAndSubtitleUnder, pageTitleViews, EditingItemPageTitle, StaticPageBreadcrumbs } from './../PageTitle'; import { replaceString as placeholderReplacementFxn } from './../static-pages/placeholders'; /** * Function which is passed into a `.filter()` call to * filter context.facets down, usually in response to frontend-state. * * Currently is meant to filter out type facet if we're in selection mode, * as well as some fields from embedded 'experiment_set' which might * give unexpected results. * * @todo Potentially get rid of this and do on backend. * * @param {{ field: string }} facet - Object representing a facet. * @returns {boolean} Whether to keep or discard facet. */ export function filterFacet(facet, currentAction, session){ // Set in backend or schema for facets which are under development or similar. if (facet.hide_from_view) return false; // Remove the @type facet while in selection mode. if (facet.field === 'type' && isSelectAction(currentAction)) return false; // Most of these would only appear if manually entered into browser URL. if (facet.field.indexOf('experiments.experiment_sets.') > -1) return false; if (facet.field === 'experiment_sets.@type') return false; if (facet.field === 'experiment_sets.experimentset_type') return false; return true; } /** * Filter down the `@type` facet options down to abstract types only (if none selected) for Search. * Also, whatever defined in `filterFacet`. */ export function transformedFacets(href, context, currentAction, session, schemas){ // Clone/filter list of facets. // We may filter out type facet completely at this step, // in which case we can return out of func early. const facets = _.filter( context.facets, function(facet){ return filterFacet(facet, currentAction, session); } ); const searchItemTypes = getAllSchemaTypesFromSearchContext(context); // "Item" is excluded if (searchItemTypes.length > 0) { logger.info("A (non-'Item') type filter is present. Will skip filtering Item types in Facet."); // Keep all terms/leaf-types - backend should already filter down to only valid sub-types through // nature of search itself. if (searchItemTypes.length > 1) { logger.warning("More than one \"type\" filter is selected. This is intended to not occur, at least as a consequence of interacting with the UI. Perhaps have entered multiple types into URL."); } return facets; } // Find facet for '@type' const typeFacetIndex = _.findIndex(facets, { 'field' : 'type' }); if (typeFacetIndex === -1) { logger.error('"Could not get type facet, though some filter for it is present."'); return facets; } // Avoid modifying in place. facets[typeFacetIndex] = _.clone(facets[typeFacetIndex]); // Show only base types (exclude leaf types) for when no non-Item type filter is present. facets[typeFacetIndex].terms = _.filter(facets[typeFacetIndex].terms, function(itemType){ const parentType = getAbstractTypeForType(itemType.key, schemas); return !parentType || parentType === itemType.key; }); return facets; } export default class SearchView extends React.PureComponent { constructor(props){ super(props); this.memoized = { transformedFacets: memoize(transformedFacets) }; } render(){ const { isFullscreen, href, context, currentAction, session, schemas } = this.props; const facets = this.memoized.transformedFacets(href, context, currentAction, session, schemas); const tableColumnClassName = "expset-result-table-fix col-12" + (facets.length > 0 ? " col-sm-7 col-lg-8 col-xl-" + (isFullscreen ? '10' : '9') : ""); const facetColumnClassName = "col-12 col-sm-5 col-lg-4 col-xl-" + (isFullscreen ? '2' : '3'); return ( <div className="container" id="content"> <CommonSearchView {...this.props} {...{ columnExtensionMap, tableColumnClassName, facetColumnClassName, facets, placeholderReplacementFxn }} termTransformFxn={Schemas.Term.toName} separateSingleTermFacets /> </div> ); } } const SearchViewPageTitle = React.memo(function SearchViewPageTitle(props) { const { context, schemas, currentAction, alerts, session, href } = props; if (schemaTransforms.getSchemaTypeFromSearchContext(context) === "Publication") { return ( <PageTitleContainer alerts={alerts}> <StaticPageBreadcrumbs {...{ context, session, href }} key="breadcrumbs" /> <TitleAndSubtitleUnder> Publications </TitleAndSubtitleUnder> </PageTitleContainer> ); } if (currentAction === "add") { // Fallback unless any custom PageTitles registered for @type=<ItemType>SearchResults & currentAction=add return <EditingItemPageTitle {...{ context, schemas, currentAction, alerts }} />; } const searchType = schemaTransforms.getSchemaTypeFromSearchContext(context); const thisTypeTitle = schemaTransforms.getTitleForType(searchType, schemas); if (currentAction === "selection") { return ( <PageTitleContainer alerts={alerts}> <StaticPageBreadcrumbs {...{ context, session, href }} key="breadcrumbs" /> <TitleAndSubtitleUnder subtitle="Select an Item and click the Apply button." subTitleClassName="smaller"> <span className="title">Selecting</span><span className="prominent subtitle">{thisTypeTitle}</span> </TitleAndSubtitleUnder> </PageTitleContainer> ); } if (currentAction === "multiselect") { return ( <PageTitleContainer alerts={alerts}> <StaticPageBreadcrumbs {...{ context, session, href }} key="breadcrumbs" /> <TitleAndSubtitleUnder subtitle="Select one or more Items and click the Apply button." subTitleClassName="smaller"> <span className="title">Selecting</span><span className="prominent subtitle">{thisTypeTitle}</span> </TitleAndSubtitleUnder> </PageTitleContainer> ); } if (searchType === "Publication" && !isSelectAction(currentAction)) { return null; } const subtitle = thisTypeTitle ? ( <span><small className="text-300">for</small> {thisTypeTitle}</span> ) : null; return ( <PageTitleContainer alerts={alerts}> <StaticPageBreadcrumbs {...{ context, session, href }} key="breadcrumbs" /> <TitleAndSubtitleBeside subtitle={subtitle}> Search </TitleAndSubtitleBeside> </PageTitleContainer> ); }); pageTitleViews.register(SearchViewPageTitle, "Search"); pageTitleViews.register(SearchViewPageTitle, "Search", "selection"); pageTitleViews.register(SearchViewPageTitle, "Search", "multiselect"); pageTitleViews.register(SearchViewPageTitle, "Search", "add");
app/components/Header/index.js
AnhHT/react-boilerplate
import React from 'react'; import { FormattedMessage } from 'react-intl'; import A from './A'; import Img from './Img'; import NavBar from './NavBar'; import HeaderLink from './HeaderLink'; import Banner from './banner.jpg'; import messages from './messages'; class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <A href="https://twitter.com/mxstbr"> <Img src={Banner} alt="react-boilerplate - Logo" /> </A> <NavBar> <HeaderLink to="/"> <FormattedMessage {...messages.home} /> </HeaderLink> <HeaderLink to="/features"> <FormattedMessage {...messages.features} /> </HeaderLink> </NavBar> </div> ); } } export default Header;
src/parser/hunter/marksmanship/CHANGELOG.js
FaideWW/WoWAnalyzer
import React from 'react'; import { Putro } from 'CONTRIBUTORS'; import SpellLink from 'common/SpellLink'; import SPELLS from 'common/SPELLS'; export default [ { date: new Date('2018-11-20'), changes: <> Added a simple <SpellLink id={SPELLS.PRECISE_SHOTS.id} /> module. </>, contributors: [Putro], }, { date: new Date('2018-11-14'), changes: <> Created a module for <SpellLink id={SPELLS.BORN_TO_BE_WILD_TALENT.id} /> and <SpellLink id={SPELLS.BINDING_SHOT_TALENT.id} />. </>, contributors: [Putro], }, { date: new Date('2018-09-28'), changes: <>Adds simple tracking for <SpellLink id={SPELLS.STEADY_AIM.id} /> azerite trait, and disables focus capping module when that trait is active.</>, contributors: [Putro], }, { date: new Date('2018-08-06'), changes: <>Adds initial tracking for <SpellLink id={SPELLS.STEADY_FOCUS_TALENT.id} /> to ensure the GCD is accurate in the analyzer.</>, contributors: [Putro], }, { date: new Date('2018-08-12'), changes: 'Removed all legendaries and tier gear in preparation for Battle for Azeroth launch', contributors: [Putro], }, { date: new Date('2018-08-06'), changes: <>Adds buff indicators to relevant spells in the timeline, adjusted placement of statistic boxes and added example logs to everything BFA related.</>, contributors: [Putro], }, { date: new Date('2018-07-23'), changes: 'Updated a large amount of modules to be ready for pre-patch and BFA. Updated patch combatility to 8.0.1.', contributors: [Putro], }, ];
exercises/event/solution/app.js
kohei-takata/learnyoureact
import React from 'react'; import ReactDOM from 'react-dom'; import TodoBox from './views/index.jsx'; let data = JSON.parse(document.getElementById('initial-data').getAttribute('data-json')); ReactDOM.render(<TodoBox data={data} />, document.getElementById("app"));
stories/resources/Card.js
jquense/react-big-calendar
import React from 'react' const propTypes = {} function Card({ children, className, style }) { return ( <div className={`${className || ''} card`} style={style}> {children} </div> ) } Card.propTypes = propTypes export default Card
src/Input/Ticker/Ticker.js
skyiea/wix-style-react
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import styles from './Ticker.scss'; const ArrowUp = () => <svg width="10" height="4" viewBox="0 0 10 4" xmlns="http://www.w3.org/2000/svg"> <path d="M9 4L5 0 1 4" stroke="#3899EC" fill="none" fillRule="evenodd"/> </svg>; const Ticker = ({onUp, onDown, upDisabled, downDisabled}) => { const upProps = buildProps(styles.up, onUp, upDisabled); const downProps = buildProps(styles.down, onDown, downDisabled); return ( <div className={styles.root} data-hook="ticker"> <div {...upProps}><ArrowUp/></div> <div {...downProps}><ArrowUp/></div> </div> ); }; Ticker.displayName = 'Input.Ticker'; Ticker.propTypes = { onUp: PropTypes.func, onDown: PropTypes.func, upDisabled: PropTypes.bool, downDisabled: PropTypes.bool }; function buildProps(clazz, onClick, disabled) { return { className: classnames(clazz, { [styles.disabled]: disabled }), onClick: disabled ? null : onClick }; } export default Ticker;
YEAR 3/SEM 1/MOBILE/mobile_exam_prep/screens/Experiment/SelfProfile/index.js
Zephyrrus/ubb
import React from 'react' import PropTypes from 'prop-types' import contactData from '../../../mocks/contact.json' import Profile from './Profile' const ProfileScreen = () => <Profile {...contactData} /> /*ProfileScreen.navigationOptions = () => ({ header: null, })*/ ProfileScreen.navigationOptions = () => ({ title: 'Profile' }) ProfileScreen.propTypes = { navigation: PropTypes.object.isRequired, } export default ProfileScreen
src/app/components/ui/SuperBoxGallery.js
backpackcoder/world-in-flames
import React from 'react' (function ($) { $.fn.SuperBox = function (options) { var superbox = $('<div class="superbox-show"></div>'), superboximg = $('<img src="" class="superbox-current-img"><div id="imgInfoBox" class="superbox-imageinfo inline-block"> <h1>Image Title</h1><span><p><em>http://imagelink.com/thisimage.jpg</em></p><p class="superbox-img-description">Image description</p><p><a href="javascript:void(0);" class="btn btn-primary btn-sm">Edit Image</a> <a href="javascript:void(0);" class="btn btn-danger btn-sm">Delete</a></p></span> </div>'), superboxclose = $('<div class="superbox-close txt-color-white"><i class="fa fa-times fa-lg"></i></div>'); superbox.append(superboximg).append(superboxclose); var imgInfoBox = $('.superbox-imageinfo'); return this.each(function () { $('.superbox-list').click(function () { //$('.superbox-list', $(this)).click(function() { var $this = $(this); var currentimg = $this.find('.superbox-img'), imgData = currentimg.data('img'), imgDescription = currentimg.attr('alt') || "No description", imgLink = imgData, imgTitle = currentimg.attr('title') || "No Title"; //console.log(imgData, imgDescription, imgLink, imgTitle) superboximg.attr('src', imgData); $('.superbox-list').removeClass('active'); $this.addClass('active'); //$('#imgInfoBox em').text(imgLink); //$('#imgInfoBox >:first-child').text(imgTitle); //$('#imgInfoBox .superbox-img-description').text(imgDescription); superboximg.find('em').text(imgLink); superboximg.find('>:first-child').text(imgTitle); superboximg.find('.superbox-img-description').text(imgDescription); //console.log("fierd") if ($('.superbox-current-img').css('opacity') == 0) { $('.superbox-current-img').animate({opacity: 1}); } if ($(this).next().hasClass('superbox-show')) { if (superbox.is(":visible")) $('.superbox-list').removeClass('active'); superbox.toggle(); } else { superbox.insertAfter(this).css('display', 'block'); $this.addClass('active'); } $('html, body').animate({ scrollTop: superbox.position().top - currentimg.width() }, 'medium'); }); $('.superbox').on('click', '.superbox-close', function () { $('.superbox-list').removeClass('active'); $('.superbox-current-img').animate({opacity: 0}, 200, function () { $('.superbox-show').slideUp(); }); }); }); }; })(jQuery); export default class SuperBoxGallery extends React.Component { componentDidMount() { let element = $(this.refs.galleryContainer); element.SuperBox(); } render() { let items = this.props.items || []; return ( <div> <div ref="galleryContainer" className={this.props.className}> {items.map(function (item, idx) { return ( <div className="superbox-list" key={idx}> <img src={item.src} data-img={item.img} alt={item.alt} title={item.title} className="superbox-img"/> </div> ) })} <div className="superbox-float"/> </div> </div> ) } }
docs/src/components/example-step.js
adisuryadi/nuclear-js
import React from 'react' export default React.createClass({ render() { var className = 'example-step'; let push = this.props.push if (push === 'right') { className += ' example-step__push-right' } return <div className={className}> {this.props.children} </div> } })
client/js/modules/entries/components/NoArticleSelectedTeaser.js
fdietz/whistler_news_reader
import React from 'react'; import LayoutHeader from '../../../layouts/LayoutHeader'; import LayoutContent from '../../../layouts/LayoutContent'; import LayoutContainer from '../../../layouts/LayoutContainer'; import Teaser from '../../../components/Teaser'; import { EarthSVGIcon } from '../../../components/SVGIcon'; const NoArticleSelectedTeaser = function render() { return ( <LayoutContainer> <LayoutHeader /> <LayoutContent> <Teaser> <EarthSVGIcon size="xxlarge" color="gray" /> <h2>Moin moin from Hamburg</h2> <p>Have a nice day!</p> </Teaser> </LayoutContent> </LayoutContainer> ); }; export default NoArticleSelectedTeaser;
src/index.js
gibbok/react-redux-weather-app
// flow import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import store from './app/store' import Root from './app/Root' render( <Root store={store} />, document.getElementById('root') )
src/muiThemeable.js
Syncano/material-ui
import React from 'react'; import getMuiTheme from './styles/getMuiTheme'; function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } export default function muiThemeable(WrappedComponent) { const MuiComponent = (props, {muiTheme = getMuiTheme()}) => { return <WrappedComponent {...props} muiTheme={muiTheme} />; }; MuiComponent.displayName = getDisplayName(WrappedComponent); MuiComponent.contextTypes = { muiTheme: React.PropTypes.object, }; MuiComponent.childContextTypes = { muiTheme: React.PropTypes.object, }; return MuiComponent; }
src/parser/deathknight/frost/modules/features/checklist/Component.js
sMteX/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import Checklist from 'parser/shared/modules/features/Checklist'; import Rule from 'parser/shared/modules/features/Checklist/Rule'; import Requirement from 'parser/shared/modules/features/Checklist/Requirement'; import PreparationRule from 'parser/shared/modules/features/Checklist/PreparationRule'; import GenericCastEfficiencyRequirement from 'parser/shared/modules/features/Checklist/GenericCastEfficiencyRequirement'; class FrostDeathKnightChecklist extends React.PureComponent { static propTypes = { castEfficiency: PropTypes.object.isRequired, combatant: PropTypes.shape({ hasTalent: PropTypes.func.isRequired, hasTrinket: PropTypes.func.isRequired, }).isRequired, thresholds: PropTypes.object.isRequired, }; render() { const { combatant, castEfficiency, thresholds } = this.props; const AbilityRequirement = props => ( <GenericCastEfficiencyRequirement castEfficiency={castEfficiency.getCastEfficiencyForSpellId(props.spell)} {...props} /> ); return ( <Checklist> <Rule name="Use cooldowns as often as possible" description={( <> You should aim to use your cooldowns as often as you can to maximize your damage output.{' '} <a href="https://www.wowhead.com/frost-death-knight-rotation-guide#cooldown-usage" target="_blank" rel="noopener noreferrer">More info.</a> </> )} > <AbilityRequirement spell={SPELLS.PILLAR_OF_FROST.id} /> {combatant.hasTalent(SPELLS.BREATH_OF_SINDRAGOSA_TALENT.id) && ( <AbilityRequirement spell={SPELLS.BREATH_OF_SINDRAGOSA_TALENT.id} /> )} <AbilityRequirement spell={SPELLS.EMPOWER_RUNE_WEAPON.id} /> {/* We can't detect race, so disable this when it has never been cast. */} {castEfficiency.getCastEfficiencyForSpellId(SPELLS.ARCANE_TORRENT_RUNIC_POWER.id) && ( <AbilityRequirement spell={SPELLS.ARCANE_TORRENT_RUNIC_POWER.id} /> )} </Rule> <Rule name="Try to avoid being inactive for a large portion of the fight" description={( <> While some downtime is inevitable in fights with movement, you should aim to reduce downtime to prevent capping Runes. In a worst case scenario, you can cast <SpellLink id={SPELLS.HOWLING_BLAST.id} /> to prevent Rune capping </> )} > <Requirement name="Downtime" thresholds={thresholds.downtimeSuggestionThresholds} /> </Rule> <Rule name="Avoid capping Runes" description="Death Knights are a resource based class, relying on Runes and Runic Power to cast core abilities. You can have up to three runes recharging at once. You want to dump runes whenever you have 4 or more runes to make sure none are wasted" > <Requirement name={'Rune Efficiency'} thresholds={thresholds.runeEfficiency} /> </Rule> <Rule name="Avoid capping Runic Power" description={(<>Death Knights are a resource based class, relying on Runes and Runic Power to cast core abilities. Cast <SpellLink id={SPELLS.FROST_STRIKE_CAST.id} /> when you have 76 or more Runic Power to avoid overcapping.</>)} > <Requirement name={'Runic Power Efficiency'} thresholds={thresholds.runicPowerEfficiency} /> </Rule> <PreparationRule thresholds={thresholds} /> </Checklist> ); } } export default FrostDeathKnightChecklist;
js/containers/ApplicationTabs/Home/Tabs/Tab3/index.js
Seedstars/reactnative-mobile-app-base
import React, { Component } from 'react'; import { Text, View, TouchableOpacity, ScrollView } from 'react-native'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import t from 'tcomb-form-native'; import PaymentModal from '../../../../../components/PaymentModal'; import Spinner from '../../../../../components/spiner'; import { orderDeviceValidatePostForms, orderDeviceSaveForms } from '../../../../../actions/forms'; import { openBuyDeviceModal } from '../../../../../actions/modals'; import { validateEmail, PhoneNumber } from '../../../../../utils/validators'; import phoneNumberTransformer from '../../../../../utils/transformers'; import styles from './styles'; import formStyles from '../../../../../styles/form'; import { SECONDARY_COLOR, } from '../../../../../styles/colors'; const Form = t.form.Form; const emailForm = { email: validateEmail }; const generalFormFields = { address: t.String, phone_number: PhoneNumber, }; const options = { stylesheet: formStyles, fields: { address: { error: 'This field is required', label: 'Address', underlineColorAndroid: SECONDARY_COLOR, }, phone_number: { transformer: phoneNumberTransformer, error: 'International phone number format is required', label: 'Contact Number', underlineColorAndroid: SECONDARY_COLOR, }, email: { error: 'This field should be a valid email', underlineColorAndroid: SECONDARY_COLOR, } } }; class Tab3 extends Component { static propTypes = { actionsOrderDeviceSaveForms: React.PropTypes.func, actionsOrderDeviceValidatePostForms: React.PropTypes.func, actionsOpenBuyDeviceModal: React.PropTypes.func, modalVisible: React.PropTypes.bool, index: React.PropTypes.number, auth: React.PropTypes.shape({ token: React.PropTypes.string, email: React.PropTypes.string, }), form: React.PropTypes.shape({ isFetching: React.PropTypes.bool.isRequired, formData: React.PropTypes.object.isRequired, errorCode: React.PropTypes.number, // eslint-disable-line errorObject: React.PropTypes.shape({ non_field_errors: React.PropTypes.arrayOf(React.PropTypes.string) // eslint-disable-line }), }), }; static contextTypes = { analytics: React.PropTypes.object }; constructor(props) { super(props); this.state = { formOptions: options, modalVisible: this.props.modalVisible, orderForm: t.struct(this.calcForm()), }; } componentDidMount() { this.context.analytics.trackScreenView('Tab3'); } componentWillReceiveProps(nextProps) { const errorState = {}; Object.keys(this.calcForm()).forEach((item) => { errorState[item] = { hasError: { $set: false }, error: { $set: '' } }; }); if (nextProps.form.errorObject) { Object.keys(nextProps.form.errorObject).forEach((item) => { errorState[item] = { hasError: { $set: true }, error: { $set: nextProps.form.errorObject[item][0] } }; }); } const newFormOptions = t.update(this.state.formOptions, { fields: errorState }); this.setState({ formOptions: newFormOptions, modalVisible: nextProps.modalVisible }); } calcForm = () => { let email = {}; if (!this.props.auth.email) { email = emailForm; } const newForm = { ...email, ...generalFormFields }; return newForm; } submit = () => { this.form.validate(); const value = this.form.getValue(); if (value) { this.props.actionsOpenBuyDeviceModal(); this.props.actionsOrderDeviceSaveForms(value); } } processPayment = (type) => { const values = Object.assign({}, this.props.form.formData, { payment: type }); if (this.props.auth.email) { this.props.actionsOrderDeviceValidatePostForms(this.props.auth.token, values, this.props.auth.email, this.props.index); } else { this.props.actionsOrderDeviceValidatePostForms(this.props.auth.token, values, values.email, this.props.index); } } render() { let renderScene; if (this.props.form.isFetching) { renderScene = <Spinner/>; } else { renderScene = ( <View style={styles.container}> <ScrollView> <PaymentModal visible={this.state.modalVisible} onPress={this.processPayment}/> <View style={styles.iconContainer}> <Text style={styles.subTitle}> Order Your Cool Device Today! </Text> <Text style={styles.priceColor}> USD 10.99 </Text> </View> <View style={styles.formContainer}> <Form ref={(c) => { this.form = c; }} type={this.state.orderForm} value={this.props.form.formData} options={this.state.formOptions} /> </View> <View style={styles.scheduleButtonContainer}> <TouchableOpacity onPress={() => { this.submit(); }} style={styles.scheduleButton} > <Text style={styles.scheduleButtonTitle}> Select Payment Type </Text> </TouchableOpacity> </View> </ScrollView> </View> ); } return renderScene; } } function mapDispatchToProps(dispatch) { return { dispatch, actionsOrderDeviceValidatePostForms: bindActionCreators(orderDeviceValidatePostForms, dispatch), actionsOrderDeviceSaveForms: bindActionCreators(orderDeviceSaveForms, dispatch), actionsOpenBuyDeviceModal: bindActionCreators(openBuyDeviceModal, dispatch), }; } function mapStateToProps(state) { return { auth: state.auth, form: state.form, index: state.globalNavigation.index, modalVisible: state.modals.BuyDevicevisible }; } export default connect(mapStateToProps, mapDispatchToProps)(Tab3);
clients/packages/admin-client/src/pages/admin/container.js
nossas/bonde-client
import React from 'react' import { Switch } from 'react-router-dom' // Routes import BetaBotPage from './bot' import CommunityCreatePage from './communities/create' import SidebarContainer from './sidebar' import PrivateRoute from './private-route' const Logged = () => { return ( <Switch> <PrivateRoute exact path='/bot' component={BetaBotPage} /> <PrivateRoute exact path='/communities/new' component={CommunityCreatePage} /> <PrivateRoute path='/' component={SidebarContainer} /> </Switch> ); } export default Logged;
src/components/Blog/List/BlogCard.js
lzm854676408/big-demo
import React, { Component } from 'react'; import {hashHistory} from 'react-router'; class BlogCard extends Component { handleClick(){ this.context.router.push(`blog/${this.props.url}`); } render(){ let styles={ root:{ width:'90%', height:'100px', margin:'10px auto', cursor:'pointer', boxShadow: '0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12)', }, index:{ float:'left', width:'80px', height:'100px', textAlign:'center', backgroundColor:'#00bcd4', color:'#fff', lineHeight:'100px' }, content:{ float:'left', color:'#777', paddingLeft:'10px' } } return( <div style={styles.root} onClick={this.handleClick.bind(this)}> <div style={styles.index}>{this.props.index}</div> <div style={styles.content}> <h3>{this.props.title}</h3> <p>{this.props.date}</p> </div> </div> ) } } BlogCard.propTypes = { title: React.PropTypes.string.isRequired, index: React.PropTypes.number.isRequired, date: React.PropTypes.string.isRequired, }; BlogCard.defaultProps = { title: "请输入标题", index: 1, date: '2016.7.19', }; BlogCard.contextTypes = { router:React.PropTypes.object.isRequired }; export default BlogCard;
src/components/playerComponent/playerComponent.js
craigbilner/quizapp
'use strict'; import React from 'react'; import radium from 'radium'; import style from '../playerComponent/playerStyle'; import {status} from '../../enums/gameEnums'; class PlayerComponent extends React.Component { constructor(props) { super(props); } canAnswer() { return this.props.player.get('playerId') === this.props.questioneeId || ( !this.props.questioneeId && (this.props.player.get('teamType') === this.props.answereeTeamType) ); } getOwnQCount(gameHalf) { let count = 0; const ownqs = this.props.player.get('ownqs'); if (ownqs && ownqs === this.props.player.get('questioneeCount')) { if (this.props.round > 0 && this.props.round < 5) { count = gameHalf === 1 ? ownqs : 0; } else { count = gameHalf === 1 ? 4 : ownqs - 4; } } return count; } getOwnQs(gameHalf) { const count = this.getOwnQCount(gameHalf); return '*'.repeat(count); } getTeamOwnQ() { return this.props.teamOwnQs && this.props.teamOwnQs >= this.props.player.get('seat') ? '*' : null; } getPlayerHaloStyle() { let playerHaloStyle = [ style.halo, { backgroundColor: this.props.baseStyles.colours.dark.primary }, this.props.baseStyles.layout.columns ]; if (this.canAnswer()) { playerHaloStyle.push({ animation: `${this.props.baseStyles.animations.flash} 0.5s infinite alternate ease-in-out` }); } return playerHaloStyle; } getPlayerInnerStyle() { const bgColour = this.props.gameStatus > status.WITH_OTEAM && this.props.gameStatus < status.GAME_OVER ? style.endColour : this.props.baseStyles.colours.light.primary; const playerInnerStyle = [ style.inner, { backgroundColor: bgColour }, this.props.baseStyles.layout.flex(1), this.props.baseStyles.layout.columns ]; return playerInnerStyle; } getOwnQBulletStyle(gameHalf) { const ownqBulletStyle = { position: 'absolute', left: '50%', marginLeft: -16, fontSize: 15, top: gameHalf === 1 ? 10 : -10, color: this.props.baseStyles.colours.dark.primary }; if (this.props.player.get('ownqs') === 8) { ownqBulletStyle.color = style.fhColour; ownqBulletStyle.animation = ` ${this.props.baseStyles.animations.flash} 0.5s infinite alternate ease-in-out `; } return ownqBulletStyle; } getTeamOwnQStyle() { return [ style.teamOwnQ, { color: this.props.teamOwnQs === 4 ? style.fhColour : this.props.baseStyles.colours.dark.primary } ]; } render() { const compStyle = [ { position: 'relative' } ]; const playerTextStyle = [ this.props.baseStyles.layout.flex(1), style.text, { color: this.props.baseStyles.colours.dark.primary } ]; const ownQStyle = [ this.props.baseStyles.layout.flex(1), { position: 'relative', height: 18 } ]; return ( <div style={compStyle} onClick={this.props.handleClick.bind(this, { playerId: this.props.player.get('playerId'), teamType: this.props.player.get('teamType'), seat: this.props.player.get('seat') })}> <div style={this.getPlayerHaloStyle()}> </div> <div style={this.getPlayerInnerStyle()}> <div style={ownQStyle}> <span style={this.getOwnQBulletStyle(1)}>{this.getOwnQs(1)}</span> </div> <div style={playerTextStyle}> {this.props.player.get('initials')} </div> <div style={ownQStyle}> <span style={this.getOwnQBulletStyle(2)}>{this.getOwnQs(2)}</span> </div> </div> <div style={this.getTeamOwnQStyle()}>{this.getTeamOwnQ()}</div> </div> ); } } PlayerComponent.propTypes = { handleClick: React.PropTypes.func, player: React.PropTypes.object.isRequired, baseStyles: React.PropTypes.object.isRequired, questioneeId: React.PropTypes.number, answereeTeamType: React.PropTypes.number, gameStatus: React.PropTypes.number.isRequired, round: React.PropTypes.number.isRequired, teamOwnQs: React.PropTypes.number.isRequired }; PlayerComponent.defaultProps = {}; export default radium(PlayerComponent);
docs/app/Examples/collections/Breadcrumb/Variations/BreadcrumbExampleBigSize.js
vageeshb/Semantic-UI-React
import React from 'react' import { Breadcrumb } from 'semantic-ui-react' const BreadcrumbExampleBigSize = () => ( <Breadcrumb size='big'> <Breadcrumb.Section link>Home</Breadcrumb.Section> <Breadcrumb.Divider icon='right chevron' /> <Breadcrumb.Section link>Registration</Breadcrumb.Section> <Breadcrumb.Divider icon='right chevron' /> <Breadcrumb.Section active>Personal Information</Breadcrumb.Section> </Breadcrumb> ) export default BreadcrumbExampleBigSize
src/svg-icons/action/speaker-notes-off.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSpeakerNotesOff = (props) => ( <SvgIcon {...props}> <path d="M10.54 11l-.54-.54L7.54 8 6 6.46 2.38 2.84 1.27 1.73 0 3l2.01 2.01L2 22l4-4h9l5.73 5.73L22 22.46 17.54 18l-7-7zM8 14H6v-2h2v2zm-2-3V9l2 2H6zm14-9H4.08L10 7.92V6h8v2h-7.92l1 1H18v2h-4.92l6.99 6.99C21.14 17.95 22 17.08 22 16V4c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ActionSpeakerNotesOff = pure(ActionSpeakerNotesOff); ActionSpeakerNotesOff.displayName = 'ActionSpeakerNotesOff'; ActionSpeakerNotesOff.muiName = 'SvgIcon'; export default ActionSpeakerNotesOff;
src/app/components/Navigation/Navigation.js
richardkall/react-starter
import React from 'react'; import { NavLink } from 'react-router-dom'; import style from './Navigation.css'; function Navigation() { return ( <nav> <ul className={style.list}> <li className={style.item}> <NavLink className={style.link} activeClassName={style.activeLink} to="/" exact > Home </NavLink> </li> <li className={style.item}> <NavLink className={style.link} activeClassName={style.activeLink} to="/about" exact > About </NavLink> </li> </ul> </nav> ); } export default Navigation;
src/js/routes.js
gollodev/twitchApp
import React from 'react'; import { Route, IndexRoute, Redirect } from 'react-router'; import App from './components/App'; import ListStreamsContainer from './containers/ListStreamsContainer/ListStreamsContainer'; import NotFoundView from './views/NotFoundView'; export default ( <Route path="/" component={App}> <IndexRoute component={ListStreamsContainer} /> <Route path="404" component={NotFoundView} /> <Redirect from="*" to="404" /> </Route> );
app/javascript/mastodon/components/status_list.js
Kirishima21/mastodon
import { debounce } from 'lodash'; import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import StatusContainer from '../containers/status_container'; import ImmutablePureComponent from 'react-immutable-pure-component'; import LoadGap from './load_gap'; import ScrollableList from './scrollable_list'; import RegenerationIndicator from 'mastodon/components/regeneration_indicator'; export default class StatusList extends ImmutablePureComponent { static propTypes = { scrollKey: PropTypes.string.isRequired, statusIds: ImmutablePropTypes.list.isRequired, featuredStatusIds: ImmutablePropTypes.list, onLoadMore: PropTypes.func, onScrollToTop: PropTypes.func, onScroll: PropTypes.func, trackScroll: PropTypes.bool, isLoading: PropTypes.bool, isPartial: PropTypes.bool, hasMore: PropTypes.bool, prepend: PropTypes.node, emptyMessage: PropTypes.node, alwaysPrepend: PropTypes.bool, timelineId: PropTypes.string, }; static defaultProps = { trackScroll: true, }; getFeaturedStatusCount = () => { return this.props.featuredStatusIds ? this.props.featuredStatusIds.size : 0; } getCurrentStatusIndex = (id, featured) => { if (featured) { return this.props.featuredStatusIds.indexOf(id); } else { return this.props.statusIds.indexOf(id) + this.getFeaturedStatusCount(); } } handleMoveUp = (id, featured) => { const elementIndex = this.getCurrentStatusIndex(id, featured) - 1; this._selectChild(elementIndex, true); } handleMoveDown = (id, featured) => { const elementIndex = this.getCurrentStatusIndex(id, featured) + 1; this._selectChild(elementIndex, false); } handleLoadOlder = debounce(() => { this.props.onLoadMore(this.props.statusIds.size > 0 ? this.props.statusIds.last() : undefined); }, 300, { leading: true }) _selectChild (index, align_top) { const container = this.node.node; const element = container.querySelector(`article:nth-of-type(${index + 1}) .focusable`); if (element) { if (align_top && container.scrollTop > element.offsetTop) { element.scrollIntoView(true); } else if (!align_top && container.scrollTop + container.clientHeight < element.offsetTop + element.offsetHeight) { element.scrollIntoView(false); } element.focus(); } } setRef = c => { this.node = c; } render () { const { statusIds, featuredStatusIds, onLoadMore, timelineId, ...other } = this.props; const { isLoading, isPartial } = other; if (isPartial) { return <RegenerationIndicator />; } let scrollableContent = (isLoading || statusIds.size > 0) ? ( statusIds.map((statusId, index) => statusId === null ? ( <LoadGap key={'gap:' + statusIds.get(index + 1)} disabled={isLoading} maxId={index > 0 ? statusIds.get(index - 1) : null} onClick={onLoadMore} /> ) : ( <StatusContainer key={statusId} id={statusId} onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} contextType={timelineId} scrollKey={this.props.scrollKey} showThread /> )) ) : null; if (scrollableContent && featuredStatusIds) { scrollableContent = featuredStatusIds.map(statusId => ( <StatusContainer key={`f-${statusId}`} id={statusId} featured onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} contextType={timelineId} showThread /> )).concat(scrollableContent); } return ( <ScrollableList {...other} showLoading={isLoading && statusIds.size === 0} onLoadMore={onLoadMore && this.handleLoadOlder} ref={this.setRef}> {scrollableContent} </ScrollableList> ); } }
src/admin/client/modules/orders/listHead/components/search.js
cezerin/cezerin
import React from 'react'; import messages from 'lib/text'; import TextField from 'material-ui/TextField'; export default ({ value, setSearch }) => { return ( <TextField className="searchField" value={value} onChange={(e, v) => { setSearch(v); }} hintText={messages.orders_search} underlineShow={false} hintStyle={{ color: 'rgba(255,255,255,0.4)', textIndent: '16px' }} inputStyle={{ color: '#fff', backgroundColor: 'rgba(255,255,255,0.2)', borderRadius: '4px', textIndent: '16px' }} /> ); };
src/modules/categories/components/CategoryPlaylists.js
paramsinghvc/harp
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { getSelectedCategoryDetails } from '../CategoriesActions'; import PlaylistItem from '../../../components/playlist-item/PlaylistItem'; require('./CategoryPlaylists.scss'); @connect((state) => { return { isLoading: state.app.get('isLoading'), category: state.categories.getIn(['selectedCategory']), playlists: state.categories.getIn(['playlists', 'items']) } }, (dispatch) => { return bindActionCreators({ getSelectedCategoryDetails }, dispatch) }) export default class CategoryPlaylists extends Component { componentDidMount() { this.props.getSelectedCategoryDetails(this.props.params.id); } render() { return ( <main className="cat-playlists" aria-labelledby="cat-name" tabIndex="0"> {!this.props.isLoading && (<div> <section className="hero-section"> <img src={this.props.category.get('icons').first().get('url')} alt={this.props.category.get('name')} tabIndex="0" /> <section className="info-section"> <p id="cat-name" role="heading" tabIndex="0">{this.props.category.get('name')}</p> </section> </section> <div className="playlists" role="list" > {this.props.playlists.map((playlist, i) => <PlaylistItem playlist={playlist} idx={i} key={i} setSize={this.props.playlists.size}/>)} </div> </div> )} </main> ) } }
examples/todo/js/components/TodoTextInput.js
michaelchum/relay
/** * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import React from 'react'; import ReactDOM from 'react-dom'; var {PropTypes} = React; var ENTER_KEY_CODE = 13; var ESC_KEY_CODE = 27; export default class TodoTextInput extends React.Component { static defaultProps = { commitOnBlur: false, } static propTypes = { className: PropTypes.string, commitOnBlur: PropTypes.bool.isRequired, initialValue: PropTypes.string, onCancel: PropTypes.func, onDelete: PropTypes.func, onSave: PropTypes.func.isRequired, placeholder: PropTypes.string, } state = { isEditing: false, text: this.props.initialValue || '', }; componentDidMount() { ReactDOM.findDOMNode(this).focus(); } _commitChanges = () => { var newText = this.state.text.trim(); if (this.props.onDelete && newText === '') { this.props.onDelete(); } else if (this.props.onCancel && newText === this.props.initialValue) { this.props.onCancel(); } else if (newText !== '') { this.props.onSave(newText); this.setState({text: ''}); } } _handleBlur = () => { if (this.props.commitOnBlur) { this._commitChanges(); } } _handleChange = (e) => { this.setState({text: e.target.value}); } _handleKeyDown = (e) => { if (this.props.onCancel && e.keyCode === ESC_KEY_CODE) { this.props.onCancel(); } else if (e.keyCode === ENTER_KEY_CODE) { this._commitChanges(); } } render() { return ( <input className={this.props.className} onBlur={this._handleBlur} onChange={this._handleChange} onKeyDown={this._handleKeyDown} placeholder={this.props.placeholder} value={this.state.text} /> ); } }
puzzle-frontend/src/index.js
nathandaddio/puzzle_app
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import { Provider } from 'react-redux' import { createStore, applyMiddleware, compose } from 'redux' import thunkMiddleware from 'redux-thunk' import { createLogger } from 'redux-logger' import rootReducer from './reducers' import { fetchBoards } from './actions' const loggerMiddleware = createLogger() const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; let store = createStore( rootReducer, composeEnhancers( applyMiddleware( thunkMiddleware, loggerMiddleware ) ) ) store.dispatch(fetchBoards()) ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); registerServiceWorker();
docs/src/app/components/pages/components/Dialog/Page.js
manchesergit/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import dialogReadmeText from './README'; import DialogExampleSimple from './ExampleSimple'; import dialogExampleSimpleCode from '!raw!./ExampleSimple'; import DialogExampleModal from './ExampleModal'; import dialogExampleModalCode from '!raw!./ExampleModal'; import DialogExampleCustomWidth from './ExampleCustomWidth'; import dialogExampleCustomWidthCode from '!raw!./ExampleCustomWidth'; import DialogExampleDialogDatePicker from './ExampleDialogDatePicker'; import dialogExampleDialogDatePickerCode from '!raw!./ExampleDialogDatePicker'; import DialogExampleScrollable from './ExampleScrollable'; import DialogExampleScrollableCode from '!raw!./ExampleScrollable'; import DialogExampleAlert from './ExampleAlert'; import DialogExampleAlertCode from '!raw!./ExampleAlert'; import dialogCode from '!raw!material-ui/Dialog/Dialog'; const DialogPage = () => ( <div> <Title render={(previousTitle) => `Dialog - ${previousTitle}`} /> <MarkdownElement text={dialogReadmeText} /> <CodeExample title="Simple dialog" code={dialogExampleSimpleCode} > <DialogExampleSimple /> </CodeExample> <CodeExample title="Modal dialog" code={dialogExampleModalCode} > <DialogExampleModal /> </CodeExample> <CodeExample title="Styled dialog" code={dialogExampleCustomWidthCode} > <DialogExampleCustomWidth /> </CodeExample> <CodeExample title="Nested dialogs" code={dialogExampleDialogDatePickerCode} > <DialogExampleDialogDatePicker /> </CodeExample> <CodeExample title="Scrollable dialog" code={DialogExampleScrollableCode} > <DialogExampleScrollable /> </CodeExample> <CodeExample title="Alert dialog" code={DialogExampleAlertCode} > <DialogExampleAlert /> </CodeExample> <PropTypeDescription code={dialogCode} /> </div> ); export default DialogPage;
src/Row.js
rapilabs/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import CustomPropTypes from './utils/CustomPropTypes'; const Row = React.createClass({ propTypes: { /** * You can use a custom element for this component */ componentClass: CustomPropTypes.elementType }, getDefaultProps() { return { componentClass: 'div' }; }, render() { let ComponentClass = this.props.componentClass; return ( <ComponentClass {...this.props} className={classNames(this.props.className, 'row')}> {this.props.children} </ComponentClass> ); } }); export default Row;
webpack/scenes/RedHatRepositories/components/RecommendedRepositorySetsToggler.js
johnpmitsch/katello
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { translate as __ } from 'foremanReact/common/I18n'; import { Switch, Icon, FieldLevelHelp } from 'patternfly-react'; import './RecommendedRepositorySetsToggler.scss'; const RecommendedRepositorySetsToggler = ({ enabled, className, children, help, onChange, ...props }) => { const classes = classNames('recommended-repositories-toggler-container', className); return ( <div className={classes} {...props}> <Switch bsSize="mini" value={enabled} onChange={() => onChange(!enabled)} /> <Icon type="fa" name="star" /> {children} <FieldLevelHelp content={help} /> </div> ); }; RecommendedRepositorySetsToggler.propTypes = { enabled: PropTypes.bool, className: PropTypes.string, children: PropTypes.node, help: PropTypes.node, onChange: PropTypes.func, }; RecommendedRepositorySetsToggler.defaultProps = { enabled: false, className: '', children: __('Recommended Repositories'), help: __('This shows repositories that are used in a typical setup.'), onChange: () => null, }; export default RecommendedRepositorySetsToggler;
app/components/Navbar/NavDropdownMenu/index.js
josueorozco/parlay
import React from 'react'; import classNames from 'classnames'; /* |-------------------------------------------------------------------------- | NavDropdownMenu |-------------------------------------------------------------------------- | | Stateless component | */ const NavDropdownMenu = ({ className = '', children }) => ( <div className={classNames( 'dropdown-menu', className, )} > {children} </div> ); NavDropdownMenu.propTypes = { className: React.PropTypes.string, children: React.PropTypes.node, }; export default NavDropdownMenu;
src/components/DropdownInput.js
jeremyfry/init-tracker
import React from 'react'; import PropTypes from 'prop-types'; const DropdownInput = (props) => { const handleChange = (e) => { props.onChange(props.name, e.target.value); }; const options = props.options.map(option => <option>{option}</option>); return ( <label className="add-player__label"> <span>{props.label}</span> <select className="add-player__input" placeholder={props.placeholder} value={props.value} onChange={handleChange}> <option>Select a class</option> {options} </select> </label> ); }; DropdownInput.propTypes = { name: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, placeholder: PropTypes.string, value: PropTypes.string, options: PropTypes.array, label: PropTypes.string.isRequired }; export default DropdownInput;
pages/index.js
inthegully/reactPortfolio
import React from 'react'; import { Link } from 'react-router'; import { prefixLink } from 'gatsby-helpers'; import Helmet from 'react-helmet'; import { config } from 'config'; import '../css/index.css'; import LogoHouse from '../components/LogoHouse/LogoHouse'; import About from '../components/About/About'; import Projects from '../components/Projects/Projects'; import Contact from '../components/Contact/Contact'; export default class Index extends React.Component { render() { return ( <div> <div className="index-body"> </div> <div> <LogoHouse /> <About /> <Contact /> <Projects /> </div> </div> ); } }
client/extensions/woocommerce/woocommerce-services/views/shipping-label/label-purchase-modal/customs-step/item-row-header.js
Automattic/woocommerce-services
/** * External dependencies */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { localize } from 'i18n-calypso'; import { ExternalLink, Tooltip } from '@wordpress/components'; /** * Internal dependencies */ import { getShippingLabel } from 'woocommerce/woocommerce-services/state/shipping-label/selectors'; import Gridicon from "gridicons"; export const TariffCodeTitle = localize( ( { translate } ) => ( <span> { translate( 'HS Tariff number' ) } ( <ExternalLink href="https://docs.woocommerce.com/document/woocommerce-shipping-and-tax/woocommerce-shipping/#section-29" > { translate( 'more info' ) } </ExternalLink> ) </span> ) ); export const OriginCountryTitle = localize( ( { translate } ) => ( <span> { translate( 'Origin country' ) } <Tooltip text={ translate( 'Country where the product was manufactured or assembled' ) }> <span> <Gridicon icon="info-outline" size={ 18 } /> </span> </Tooltip> </span> ) ); const ItemRowHeader = ( { translate, weightUnit } ) => ( <div className="customs-step__item-rows-header"> <span className="customs-step__item-description-column">{ translate( 'Description' ) }</span> <span className="customs-step__item-code-column">{ <TariffCodeTitle /> }</span> <span className="customs-step__item-weight-column"> { translate( 'Weight (%s per unit)', { args: [ weightUnit ] } ) } </span> <span className="customs-step__item-value-column">{ translate( 'Value ($ per unit)' ) }</span> <span className="customs-step__item-country-column">{ <OriginCountryTitle /> }</span> </div> ); ItemRowHeader.propTypes = { siteId: PropTypes.number.isRequired, orderId: PropTypes.number.isRequired, weightUnit: PropTypes.string.isRequired, }; export default connect( ( state, { orderId, siteId } ) => ( { weightUnit: getShippingLabel( state, orderId, siteId ).storeOptions.weight_unit, } ) )( localize( ItemRowHeader ) );
app/components/FollowUp.js
oroszms/nhshd17
// @flow import React, { Component } from 'react'; import { Link, hashHistory } from 'react-router'; import RaisedButton from 'material-ui/RaisedButton'; import Paper from 'material-ui/Paper'; import TextField from 'material-ui/TextField'; import Slider from 'material-ui/Slider'; import Toggle from 'material-ui/Toggle'; import {RadioButton, RadioButtonGroup} from 'material-ui/RadioButton'; import styles from './Home.css'; import { ipcRenderer } from 'electron'; import Checkbox from 'material-ui/Checkbox'; const paperStyle = { paddingLeft: '100px', paddingRight: '50px', paddingTop: '20px', paddingBottom: '20px', height: '80vh', overflow: 'scroll', } const contentStyle = { width: '50%', } export default class FollowUp extends Component { props: { getFilePath: () => void, saveFilePath: () => void, filePath: string }; constructor() { super(); this.state = { "id": "", "discharged_without-follow-up": "", "during_labour": "", "during_delivery": "", "satisfied_with_pain_relief": "", "epidural_stop_working": "", "epidural_fall_out": "", "discomfort": "", "after_operation_pain": "", "nausea": "", "pruritus": "", "pdph": "", "leg_numbness_and_weakness": "", "happy_with_services": "", "would_recommend": "", "follow-up_anaesthetist": "", "notes": "", "follow-up_complete": "", } } handleChange(name, event) { const state = this.state state[name] = event.target.value this.setState(state) } handleSlider(name, event, value) { const state = this.state state[name] = value this.setState(state) } handleClick() { const { getFilePath } = this.props const filePath = getFilePath() + 'FollowUp.csv' const toSave = this.state ipcRenderer.send('create-record', filePath, toSave) this.state = {} hashHistory.push(`/patient`) } render() { return ( <div> <Paper style={ paperStyle } zDepth={1}> <div style={ contentStyle }> <h2 style={{color: '#232C39'}}>Follow-up</h2> <Checkbox label="Discharged without follow-up" style={styles.checkbox} onChange={ this.handleChange.bind(this, 'discharged_without-follow-up') } /> <p>For those who had labour epidural</p> How effective was it for your labour: <Slider step={0.20} onChange={ this.handleSlider.bind(this, 'during_labour') } name="during_labour" /> How effective during delivery: <Slider step={0.20} onChange={ this.handleSlider.bind(this, 'during_delivery') } /> Were you satisfied with your pain relief? <RadioButtonGroup name="satisfied_with_pain_relief" onChange={ this.handleChange.bind(this, 'satisfied_with_pain_relief') } > <RadioButton value="yes" label="Yes" /><RadioButton value="no" label="No" /><RadioButton value="n/a" label="N/A" /> </RadioButtonGroup><br /> Did the epidural stop working at any point?<br /> <RadioButtonGroup name="epidural_stop_working" onChange={ this.handleChange.bind(this, 'epidural_stop_working') } > <RadioButton value="yes" label="Yes" /><RadioButton value="no" label="No" /><RadioButton value="n/a" label="N/A" /> </RadioButtonGroup><br /> Did the epidural 'fall out' at any point?<br /> <RadioButtonGroup name="epidural" onChange={ this.handleChange.bind(this, 'epidural_fall_out') } > <RadioButton value="yes" label="Yes" style={{ display: 'inline-block' }} /><RadioButton value="no" label="No" style={{ display: 'inline-block' }} /><RadioButton value="n/a" label="N/A" style={{ display: 'inline-block' }} /> </RadioButtonGroup><br /> <p>For those who had an operative delivery</p> Did you have any discomfort during your operation? <Slider step={0.20} onChange={ this.handleSlider.bind(this, 'discomfort') } /> Worst pain felt after the operation? <Slider step={0.20} onChange={ this.handleSlider.bind(this, 'after_operation_pain') } /> Did you feel nauseous after the operation?" <Slider step={0.20} onChange={ this.handleSlider.bind(this, 'nausea') } /> <p>For all women.</p> Pruritus? <Slider step={0.20} onChange={ this.handleSlider.bind(this, 'pruritus') } /> Signs of symptoms of PDPH? <RadioButtonGroup name="pdph" defaultSelected="not_light" onChange={ this.handleChange.bind(this, 'pdph') }> <RadioButton value="yes" label="Yes" style={{ display: 'inline-block' }}/> <RadioButton value="no" label="No" style={{ display: 'inline-block' }}/> <RadioButton value="possible" label="Possible" style={{ display: 'inline-block' }}/> </RadioButtonGroup><br /> Weakness, numbness of legs? <RadioButtonGroup name="leg_numbness_and_weakness" onChange={ this.handleChange.bind(this, 'leg_numbness_and_weakness') }> <RadioButton value="yes" label="Yes" style={{ display: 'inline-block' }}/> <RadioButton value="no" label="No" style={{ display: 'inline-block' }}/> </RadioButtonGroup><br /> Are you happy with the Anaesthetic Services that you received? <RadioButtonGroup name="happy_with_services" onChange={ this.handleChange.bind(this, 'happy_with_services') }> <RadioButton value="yes" label="Yes" style={{ display: 'inline-block' }}/> <RadioButton value="no" label="No" style={{ display: 'inline-block' }}/> </RadioButtonGroup><br /> Would you recommend the Anaesthetic Service to your friends/family? <RadioButtonGroup name="would_recommend" onChange={ this.handleChange.bind(this, 'would_recommend') }> <RadioButton value="yes" label="Yes" style={{ display: 'inline-block' }}/> <RadioButton value="no" label="No" style={{ display: 'inline-block' }}/> </RadioButtonGroup><br /> <TextField hintText="Name of anaesthetist completing follow-up" onChange={ this.handleChange.bind(this, 'follow-up_anaesthetist') } /><br /> <TextField hintText="Notes" onChange={ this.handleChange.bind(this, 'notes') } multiLine={true} rows={1} /><br /> <Checkbox label="Follow-up complete" style={styles.checkbox} onChange={ this.handleChange.bind(this, 'follow-up_complete') } /> <RaisedButton label="Save Follow Up Assessment" primary={true} style={{margin: 12}} onClick={() => this.handleClick() } /> </div> </Paper> </div> ); } }
node_modules/react-router/es/Route.js
rralian/steckball-react
import React from 'react'; import invariant from 'invariant'; import { createRouteFromReactElement } from './RouteUtils'; import { component, components } from './InternalPropTypes'; var _React$PropTypes = React.PropTypes, string = _React$PropTypes.string, func = _React$PropTypes.func; /** * A <Route> is used to declare which components are rendered to the * page when the URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is * requested, the tree is searched depth-first to find a route whose * path matches the URL. When one is found, all routes in the tree * that lead to it are considered "active" and their components are * rendered into the DOM, nested in the same order as in the tree. */ /* eslint-disable react/require-render-return */ var Route = React.createClass({ displayName: 'Route', statics: { createRouteFromReactElement: createRouteFromReactElement }, propTypes: { path: string, component: component, components: components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Route> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default Route;
app/javascript/mastodon/components/hashtag.js
masto-donte-com-br/mastodon
// @ts-check import React from 'react'; import { Sparklines, SparklinesCurve } from 'react-sparklines'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Permalink from './permalink'; import ShortNumber from 'mastodon/components/short_number'; import Skeleton from 'mastodon/components/skeleton'; import classNames from 'classnames'; class SilentErrorBoundary extends React.Component { static propTypes = { children: PropTypes.node, }; state = { error: false, }; componentDidCatch () { this.setState({ error: true }); } render () { if (this.state.error) { return null; } return this.props.children; } } /** * Used to render counter of how much people are talking about hashtag * * @type {(displayNumber: JSX.Element, pluralReady: number) => JSX.Element} */ export const accountsCountRenderer = (displayNumber, pluralReady) => ( <FormattedMessage id='trends.counter_by_accounts' defaultMessage='{count, plural, one {{counter} person} other {{counter} people}} talking' values={{ count: pluralReady, counter: <strong>{displayNumber}</strong>, }} /> ); export const ImmutableHashtag = ({ hashtag }) => ( <Hashtag name={hashtag.get('name')} href={hashtag.get('url')} to={`/tags/${hashtag.get('name')}`} people={hashtag.getIn(['history', 0, 'accounts']) * 1 + hashtag.getIn(['history', 1, 'accounts']) * 1} uses={hashtag.getIn(['history', 0, 'uses']) * 1 + hashtag.getIn(['history', 1, 'uses']) * 1} history={hashtag.get('history').reverse().map((day) => day.get('uses')).toArray()} /> ); ImmutableHashtag.propTypes = { hashtag: ImmutablePropTypes.map.isRequired, }; const Hashtag = ({ name, href, to, people, uses, history, className }) => ( <div className={classNames('trends__item', className)}> <div className='trends__item__name'> <Permalink href={href} to={to}> {name ? <React.Fragment>#<span>{name}</span></React.Fragment> : <Skeleton width={50} />} </Permalink> {typeof people !== 'undefined' ? <ShortNumber value={people} renderer={accountsCountRenderer} /> : <Skeleton width={100} />} </div> <div className='trends__item__current'> {typeof uses !== 'undefined' ? <ShortNumber value={uses} /> : <Skeleton width={42} height={36} />} </div> <div className='trends__item__sparkline'> <SilentErrorBoundary> <Sparklines width={50} height={28} data={history ? history : Array.from(Array(7)).map(() => 0)}> <SparklinesCurve style={{ fill: 'none' }} /> </Sparklines> </SilentErrorBoundary> </div> </div> ); Hashtag.propTypes = { name: PropTypes.string, href: PropTypes.string, to: PropTypes.string, people: PropTypes.number, uses: PropTypes.number, history: PropTypes.arrayOf(PropTypes.number), className: PropTypes.string, }; export default Hashtag;
benchmarks/dom-comparison/src/implementations/emotion/View.js
risetechnologies/fela
/* eslint-disable react/prop-types */ import { css } from 'emotion'; import React from 'react'; class View extends React.Component { render() { const { style, ...other } = this.props; return <div {...other} className={css(viewStyle, ...style)} />; } } const viewStyle = { alignItems: 'stretch', borderWidth: 0, borderStyle: 'solid', boxSizing: 'border-box', display: 'flex', flexBasis: 'auto', flexDirection: 'column', flexShrink: 0, margin: 0, padding: 0, position: 'relative', // fix flexbox bugs minHeight: 0, minWidth: 0 }; export default View;
JS Web/ReactJS/Final Project/zoo-market/src/routes.js
mitaka00/SoftUni
import { Route, Switch } from 'react-router-dom' import React from 'react' import NotFoundPage from './components/common/NotFoundPage' import StartingPage from './components/common/StartingPage' import HomePage from './components/common/HomePage' import AddPost from './components/postComponents/AddPost' import MyPosts from './components/postComponents/MyPosts' import Details from './components/postComponents/Details' import Profile from './components/postComponents/Profile' const Routes = () => ( <Switch> <Route path='/' exact component={StartingPage} /> <Route path='/home'exact component={HomePage} /> <Route path='/addPost' exact component={AddPost} /> <Route path='/myPosts' exact component={MyPosts} /> <Route path='/details/:id' exact component={Details} /> <Route path='/profile/:username' exact component={Profile} /> <Route component={NotFoundPage} /> </Switch> ) export default Routes
app/components/IssueIcon/index.js
houlematt/matt-site
import React from 'react'; function IssueIcon(props) { return ( <svg height="1em" width="0.875em" className={props.className} > <path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z m1 3H6v5h2V4z m0 6H6v2h2V10z" /> </svg> ); } IssueIcon.propTypes = { className: React.PropTypes.string, }; export default IssueIcon;
vendor/assets/components/react-autosuggest/examples/src/Footer/Footer.js
UMNLibraries/ikidowinan
require('./Footer.less'); import React, { Component } from 'react'; export default class Footer extends Component { render() { return ( <div className="footer"> <img src="https://gravatar.com/avatar/e56de06f4b56f6f06e4a9a271ed57e26?s=32" alt="Misha Moroshko" /> <span> Crafted with <strong>love</strong> by {' '}<a href="https://twitter.com/moroshko" target="_blank">@moroshko</a> {' '}and <a href="https://github.com/moroshko/react-autosuggest/graphs/contributors" target="_blank">contributors</a> </span> </div> ); } }
examples/basic/components/Home.js
rackt/redux-simple-router
import React from 'react' import { connect } from 'react-redux' import { increase, decrease } from '../actions/count' function Home({ number, increase, decrease }) { return ( <div> Some state changes: {number} <button onClick={() => increase(1)}>Increase</button> <button onClick={() => decrease(1)}>Decrease</button> </div> ) } export default connect( state => ({ number: state.count.number }), { increase, decrease } )(Home)
src/widgets/AlertWidget.js
domoticz/Reacticz
import React, { Component } from 'react'; import GenericWidget from './helpers/GenericWidget'; import './AlertWidget.css'; class AlertWidget extends Component { render() { return ( <GenericWidget class={'AlertWidget level' + this.props.level} icon="warning" value1={this.props.value} {...this.props} /> ); } } export default AlertWidget
src/components/CodeSnippet/CodeSnippet.js
carbon-design-system/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import PropTypes from 'prop-types'; import React, { Component } from 'react'; import classNames from 'classnames'; import ChevronDown16 from '@carbon/icons-react/lib/chevron--down/16'; import { settings } from 'carbon-components'; import Copy from '../Copy'; import CopyButton from '../CopyButton'; import uid from '../../tools/uniqueId'; const { prefix } = settings; export default class CodeSnippet extends Component { static propTypes = { /** * Provide the type of Code Snippet */ type: PropTypes.oneOf(['single', 'inline', 'multi']), /** * Specify an optional className to be applied to the container node */ className: PropTypes.string, /** * Provide the content of your CodeSnippet as a string */ children: PropTypes.string, /** * Specify the string displayed when the snippet is copied */ feedback: PropTypes.string, /** * Specify the description for the Copy Button */ copyButtonDescription: PropTypes.string, /** * An optional handler to listen to the `onClick` even fired by the Copy * Button */ onClick: PropTypes.func, /** * Specify a label to be read by screen readers on the containing <textbox> * node */ copyLabel: PropTypes.string, /** * Specify a label to be read by screen readers on the containing <textbox> * node */ ariaLabel: PropTypes.string, /** * Specify a string that is displayed when the Code Snippet text is more * than 15 lines */ showMoreText: PropTypes.string, /** * Specify a string that is displayed when the Code Snippet has been * interacted with to show more lines */ showLessText: PropTypes.string, /** * Specify whether you are using the light variant of the Code Snippet, * typically used for inline snippest to display an alternate color */ light: PropTypes.bool, }; static defaultProps = { type: 'single', showMoreText: 'Show more', showLessText: 'Show less', }; state = { shouldShowMoreLessBtn: false, expandedCode: false, }; componentDidMount() { if (this.codeContent) { if (this.codeContent.getBoundingClientRect().height > 255) { this.setState({ shouldShowMoreLessBtn: true }); } } } componentDidUpdate(prevProps) { if (this.props.children !== prevProps.children && this.codeContent) { if (this.codeContent.getBoundingClientRect().height > 255) { this.setState({ shouldShowMoreLessBtn: true }); } } } expandCode = () => { this.setState({ expandedCode: !this.state.expandedCode }); }; render() { const { className, type, children, feedback, onClick, ariaLabel, copyLabel, //TODO: Merge this prop to `ariaLabel` in `v11` copyButtonDescription, light, showMoreText, showLessText, ...other } = this.props; // a unique id generated for aria-describedby this.uid = uid(); const codeSnippetClasses = classNames(className, { [`${prefix}--snippet`]: true, [`${prefix}--snippet--single`]: type === 'single', [`${prefix}--snippet--multi`]: type === 'multi', [`${prefix}--snippet--inline`]: type === 'inline', [`${prefix}--snippet--expand`]: this.state.expandedCode, [`${prefix}--snippet--light`]: light, }); const expandCodeBtnText = this.state.expandedCode ? showLessText : showMoreText; const moreLessBtn = ( <button className={`${prefix}--btn ${prefix}--btn--ghost ${prefix}--btn--sm ${prefix}--snippet-btn--expand`} type="button" onClick={this.expandCode}> <span className={`${prefix}--snippet-btn--text`}> {expandCodeBtnText} </span> <ChevronDown16 aria-label={expandCodeBtnText} className={`${prefix}--icon-chevron--down ${prefix}--snippet__icon`} name="chevron--down" role="img" /> </button> ); const code = ( <div role="textbox" tabIndex={0} className={`${prefix}--snippet-container`} aria-label={ariaLabel || copyLabel || 'code-snippet'}> <code> <pre ref={codeContent => { this.codeContent = codeContent; }}> {children} </pre> </code> </div> ); const copy = ( <CopyButton onClick={onClick} feedback={feedback} iconDescription={copyButtonDescription} /> ); if (type === 'inline') { return ( <Copy {...other} onClick={onClick} aria-label={copyLabel || ariaLabel} aria-describedby={this.uid} className={codeSnippetClasses} feedback={feedback}> <code id={this.uid}>{children}</code> </Copy> ); } if (type === 'single') { return ( <div {...other} className={codeSnippetClasses}> {code} {copy} </div> ); } if (!this.state.shouldShowMoreLessBtn && type === 'multi') { return ( <div {...other} className={codeSnippetClasses}> {code} {copy} </div> ); } if (this.state.shouldShowMoreLessBtn && type === 'multi') { return ( <div className={codeSnippetClasses} {...other}> {code} {copy} {moreLessBtn} </div> ); } } }
public/src/components/application/ApplicationScreen.js
sio-iago/essential-plaform-back
// React import React, { Component } from 'react'; // Redux actions import { connect } from 'react-redux'; // Navbar import Menu from './../menu/Menu'; // API Methods const api = require('../../api/endpoints'); // The store and reducer const store = require('../../store/storeConfig').store; // Authorization verification const isUserAuthorized = (token, history) => { api .validateUser() .then(user => null) .catch(error => history.push('/')); } export default class ApplicationScreen extends Component { componentWillMount() { isUserAuthorized(this.props.token, this.props.history); } render() { return ( <div className="dashboard-screen"> <Menu dashboardLink='/dashboard' newJobLink="/jobs/new" logoutLink="/" /> <div className="container"> {this.props.children} </div> </div> ); } }
examples/js/column-filter/filter-style.js
AllenFang/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-unused-vars: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; const qualityType = { 0: 'good', 1: 'bad', 2: 'unknown' }; function addProducts(quantity) { const startId = products.length; const startDate = new Date(2015, 0, 1); const endDate = new Date(); for (let i = 0; i < quantity; i++) { const date = new Date(startDate.getTime() + Math.random() * (endDate.getTime() - startDate.getTime())); const id = startId + i; products.push({ id: id, name: 'Item name ' + id, quality: i % 3, price: Math.floor((Math.random() * 100) + 1), inStockDate: date }); } } addProducts(5); function enumFormatter(cell, row, enumObject) { return enumObject[cell]; } function dateFormatter(cell, row) { return `${('0' + cell.getDate()).slice(-2)}/${('0' + (cell.getMonth() + 1)).slice(-2)}/${cell.getFullYear()}`; } const nameFilterStyle = { borderColor: 'black' }; const qualityFilterStyle = { borderColor: 'red' }; const priceFilterStyle = { number: { backgroundColor: 'antiquewhite' }, comparator: { border: '#0000FF 2.5px solid' } }; const dateFilterStyle = { date: { backgroundColor: 'antiquewhite' }, comparator: { border: '#0000FF 2.5px solid' } }; export default class FilterStyle extends React.Component { render() { return ( <BootstrapTable ref='table' data={ products }> <TableHeaderColumn dataField='id' isKey={ true }> Product ID </TableHeaderColumn> <TableHeaderColumn ref='name1' dataField='name' filter={ { type: 'TextFilter', style: nameFilterStyle } }>Product Name</TableHeaderColumn> <TableHeaderColumn ref='quality' dataField='quality' filter={ { type: 'SelectFilter', options: qualityType, style: qualityFilterStyle } } dataFormat={ enumFormatter } formatExtraData={ qualityType }>Product Quality</TableHeaderColumn> <TableHeaderColumn ref='price' dataField='price' filter={ { type: 'NumberFilter', delay: 1000, style: priceFilterStyle } }>Product Price</TableHeaderColumn> <TableHeaderColumn ref='inStockDate' dataField='inStockDate' filter={ { type: 'DateFilter', style: dateFilterStyle } } dataFormat={ dateFormatter }>In Stock From</TableHeaderColumn> </BootstrapTable> ); } }
node_modules/react-router/es6/RoutingContext.js
HasanSa/hackathon
import React from 'react'; import RouterContext from './RouterContext'; import warning from './routerWarning'; var RoutingContext = React.createClass({ displayName: 'RoutingContext', componentWillMount: function componentWillMount() { process.env.NODE_ENV !== 'production' ? warning(false, '`RoutingContext` has been renamed to `RouterContext`. Please use `import { RouterContext } from \'react-router\'`. http://tiny.cc/router-routercontext') : void 0; }, render: function render() { return React.createElement(RouterContext, this.props); } }); export default RoutingContext;
resources/apps/frontend/src/pages/members/show.js
johndavedecano/PHPLaravelGymManagementSystem
import React from 'react'; import get from 'lodash/get'; import { Card, CardBody, Form, FormGroup, Input, Label, Row, Col, } from 'reactstrap'; import {Link} from 'react-router-dom'; import {showMember} from 'requests/members'; import Breadcrumbs from 'components/Breadcrumbs'; import Loader from 'components/Loader'; class Component extends React.Component { state = { isLoading: false, isLoaded: false, isNotFound: false, data: {}, }; componentDidMount() { this.load(); } load = async () => { try { this.setState({isLoading: true}); const {id} = this.props.match.params; const {data} = await showMember(id); this.setState({ isLoading: false, isNotFound: false, data, isLoaded: true, }); } catch (error) { this.setState({isLoading: false, isNotFound: true}); } }; get previous() { return [ { to: '/members', label: 'Members', }, ]; } render() { if (!this.state.isLoaded) return <Loader show />; const {id} = this.props.match.params; return ( <React.Fragment> <Breadcrumbs previous={this.previous} active="Member Information" /> <Card> <CardBody className="position-relative"> {this.state.isNotFound && 'Page Not Found'} <Form> <Row> <Col md={6}> <FormGroup> <Label for="name">Name</Label> <Input type="text" name="name" id="name" placeholder="Name" required defaultValue={get(this.state.data, 'name')} readOnly /> </FormGroup> </Col> <Col md={6}> <FormGroup> <Label for="email">Email</Label> <Input type="email" name="email" id="email" placeholder="Email" required defaultValue={get(this.state.data, 'email')} readOnly /> </FormGroup> </Col> </Row> <Row> <Col md={6}> <FormGroup> <Label for="date_of_birth">Date of Birth</Label> <Input type="date" name="date_of_birth" id="date_of_birth" placeholder="date_of_birth" defaultValue={get(this.state.data, 'date_of_birth')} readOnly /> </FormGroup> </Col> <Col md={6}> <FormGroup> <Label for="mobile">Mobile Number</Label> <Input type="text" name="mobile" id="mobile" placeholder="Mobile Number" defaultValue={get(this.state.data, 'mobile')} readOnly /> </FormGroup> </Col> </Row> <Row> <Col md={4}> <FormGroup> <Label for="is_active">Active</Label> <Input type="text" name="is_active" id="is_active" placeholder="Active" defaultValue={get(this.state.data, 'is_active')} readOnly /> </FormGroup> </Col> <Col md={4}> <FormGroup> <Label for="is_admin">Admin</Label> <Input type="text" name="is_admin" id="is_admin" placeholder="Admin" defaultValue={get(this.state.data, 'is_admin')} readOnly /> </FormGroup> </Col> <Col md={4}> <FormGroup> <Label for="is_deleted">Deleted</Label> <Input type="text" name="is_deleted" id="is_deleted" placeholder="Deleted" defaultValue={get(this.state.data, 'is_deleted')} readOnly /> </FormGroup> </Col> </Row> <Row> <Col md={12}> <FormGroup> <Label for="address">Address</Label> <Input rows={8} type="textarea" name="address" id="address" placeholder="address" readOnly defaultValue={get(this.state.data, 'address')} /> </FormGroup> </Col> </Row> <Row> <Col md={6}> <FormGroup> <Label for="city">City</Label> <Input type="text" name="city" id="city" placeholder="city" defaultValue={get(this.state.data, 'city')} readOnly /> </FormGroup> </Col> <Col md={6}> <FormGroup> <Label for="state">State</Label> <Input type="text" name="state" id="state" placeholder="State" defaultValue={get(this.state.data, 'state')} readOnly /> </FormGroup> </Col> </Row> <Row> <Col md={6}> <FormGroup> <Label for="country">Country</Label> <Input type="text" name="country" id="country" placeholder="Country" defaultValue={get(this.state.data, 'country')} readOnly /> </FormGroup> </Col> <Col md={6}> <FormGroup> <Label for="postal_code">Postal Code</Label> <Input type="text" name="postal_code" id="postal_code" placeholder="Postal Code" defaultValue={get(this.state.data, 'postal_code')} readOnly /> </FormGroup> </Col> </Row> <Link to={`/members/${id}/edit`} className="btn btn-primary align-right" > Edit Member </Link> </Form> </CardBody> </Card> </React.Fragment> ); } } export default Component;
packages/forms/src/UIForm/fields/Button/Button.component.js
Talend/ui
import PropTypes from 'prop-types'; import React from 'react'; import FieldTemplate from '../FieldTemplate'; import SingleButton from './SingleButton.component'; import { generateDescriptionId, generateErrorId } from '../../Message/generateId'; export default function Button(props) { const { id, errorMessage, isValid, onTrigger, schema } = props; const descriptionId = generateDescriptionId(id); const errorId = generateErrorId(id); return ( <FieldTemplate descriptionId={descriptionId} description={schema.description} errorId={errorId} errorMessage={errorMessage} isValid={isValid} required={schema.required} > <SingleButton id={id} onTrigger={onTrigger} schema={schema} /> </FieldTemplate> ); } if (process.env.NODE_ENV !== 'production') { Button.propTypes = { id: PropTypes.string, isValid: PropTypes.bool, errorMessage: PropTypes.string, onTrigger: PropTypes.func, schema: SingleButton.propTypes.schema, }; } Button.defaultProps = { schema: {}, };
angular/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
DeegC/Zeidon-Northwind
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
src/layouts/CoreLayout/CoreLayout.js
Kelvinmijaya/taralite-starter-kit
import React from 'react' import './assets/normalize.css' import './assets/CoreLayout.css' import { Header } from '../../common/Header/Header' export const CoreLayout = ({ children }) => ( <div className="app"> <Header /> {children} </div> ) CoreLayout.propTypes = { children : React.PropTypes.element.isRequired } export default CoreLayout
websites/svef.is/src/app/middlewares/react-async-component/index.js
svef/www
import React from 'react' import { AsyncComponentProvider, createAsyncContext, } from 'react-async-component' const async = () => session => { const asyncContext = createAsyncContext() const rehydrateState = typeof window === 'undefined' ? undefined : window.REACT_ASYNC_COMPONENT_STATE session.on('server', next => { next() session.document.window.REACT_ASYNC_COMPONENT_STATE = asyncContext.getState() }) return async next => { const children = await next() return ( <AsyncComponentProvider asyncContext={asyncContext} rehydrateState={rehydrateState} > {children} </AsyncComponentProvider> ) } } export default async
server/dashboard/js/components/BenchNav.react.js
moigagoo/mzbench
import React from 'react'; class BenchNav extends React.Component { render() { const tabs = { overview: "Overview", scenario: "Scenario", reports: "Reports", logs: "Logs" }; return ( <ul className="nav nav-tabs bench-nav"> {Object.keys(tabs).map(function (tab) { let name = tabs[tab]; let cssClass = (this.props.selectedTab == tab) ? "active" : ""; let link = `#/bench/${this.props.bench.id}/${tab}`; return (<li role="presentation" key={tab} className={cssClass}><a href={link}>{name}</a></li>); }.bind(this))} </ul> ); } }; BenchNav.propTypes = { bench: React.PropTypes.object.isRequired, selectedTab: React.PropTypes.string }; BenchNav.defaultProps = { selectedTab: "overview" }; export default BenchNav;
src/server.js
kutou/react-starter-kit
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import 'babel-polyfill'; import path from 'path'; import express from 'express'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import expressJwt from 'express-jwt'; import expressGraphQL from 'express-graphql'; import jwt from 'jsonwebtoken'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Html from './components/Html'; import { ErrorPage } from './routes/error/ErrorPage'; import errorPageStyle from './routes/error/ErrorPage.css'; import UniversalRouter from 'universal-router'; import PrettyError from 'pretty-error'; import passport from './core/passport'; import models from './data/models'; import schema from './data/schema'; import routes from './routes'; import assets from './assets'; // eslint-disable-line import/no-unresolved import { port, auth } from './config'; const app = express(); // // Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the // user agent is not known. // ----------------------------------------------------------------------------- global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || 'all'; // // Register Node.js middleware // ----------------------------------------------------------------------------- app.use(express.static(path.join(__dirname, 'public'))); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // // Authentication // ----------------------------------------------------------------------------- app.use(expressJwt({ secret: auth.jwt.secret, credentialsRequired: false, getToken: req => req.cookies.id_token, })); app.use(passport.initialize()); app.get('/login/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false }) ); app.get('/login/facebook/return', passport.authenticate('facebook', { failureRedirect: '/login', session: false }), (req, res) => { const expiresIn = 60 * 60 * 24 * 180; // 180 days const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn }); res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true }); res.redirect('/'); } ); // // Register API middleware // ----------------------------------------------------------------------------- app.use('/graphql', expressGraphQL(req => ({ schema, graphiql: true, rootValue: { request: req }, pretty: process.env.NODE_ENV !== 'production', }))); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- app.get('*', async (req, res, next) => { try { let css = []; let statusCode = 200; const data = { title: '', description: '', style: '', script: assets.main.js, children: '' }; await UniversalRouter.resolve(routes, { path: req.path, query: req.query, context: { insertCss: (...styles) => { styles.forEach(style => css.push(style._getCss())); // eslint-disable-line no-underscore-dangle, max-len }, setTitle: value => (data.title = value), setMeta: (key, value) => (data[key] = value), }, render(component, status = 200) { css = []; statusCode = status; data.children = ReactDOM.renderToString(component); data.style = css.join(''); return true; }, }); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode); res.send(`<!doctype html>${html}`); } catch (err) { next(err); } }); // // Error handling // ----------------------------------------------------------------------------- const pe = new PrettyError(); pe.skipNodeFiles(); pe.skipPackage('express'); app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars console.log(pe.render(err)); // eslint-disable-line no-console const statusCode = err.status || 500; const html = ReactDOM.renderToStaticMarkup( <Html title="Internal Server Error" description={err.message} style={errorPageStyle._getCss()} // eslint-disable-line no-underscore-dangle > {ReactDOM.renderToString(<ErrorPage error={err} />)} </Html> ); res.status(statusCode); res.send(`<!doctype html>${html}`); }); // // Launch the server // ----------------------------------------------------------------------------- /* eslint-disable no-console */ models.sync().catch(err => console.error(err.stack)).then(() => { app.listen(port, () => { console.log(`The server is running at http://localhost:${port}/`); }); }); /* eslint-enable no-console */