path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/index.js
believer/react-starter
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App/App'; ReactDOM.render(<App />, document.getElementById('root'));
website/src/Footer.js
kkamperschroer/react-navigation
import React from 'react'; const Footer = () => ( <div className="footer"><div className="inner-footer"> <section className="copyright"> <a href="https://github.com/react-community/react-navigation"> React Navigation </a> · <a href="https://github.com/react-community/react-navigation/blob/master/LICENSE"> Distributed under BSD License </a> </section> </div></div> ); export default Footer;
src/app/screens/Anonymous/shared/Footer/components/Footer.js
docgecko/react-alt-firebase-starter
/*! React Alt Firebase Starter */ import './Footer.less'; import React from 'react'; import { Link } from 'react-router'; export default class Footer extends React.Component { render() { return ( <footer className="page-footer blue darken-4"> <div className="container"> <div className="row"> <div className="col 8 s8"> <h5 className="white-text">Company</h5> <p className="grey-text text-lighten-4">You can use rows and columns here to organize your footer content.</p> </div> <div className="col 2 offset-8 s2"> <h5 className="white-text">Company</h5> <ul> <li><Link to="about" className="grey-text text-lighten-3">About</Link></li> <li><Link to="contact" className="grey-text text-lighten-3">Contact</Link></li> </ul> </div> <div className="col 2 offset-10 s2"> <h5 className="white-text">Legal</h5> <ul> <li><Link to="privacy" className="grey-text text-lighten-3" href="#/legal/privacy">Privacy</Link></li> <li><Link to="terms-of-service" className="grey-text text-lighten-3" href="#/legal/tos">Terms of Service</Link></li> </ul> </div> </div> </div> <div className="footer-copyright white"> <div className="container"> All text & design is copyright © 2015 Apertun. All rights reserved. </div> </div> </footer> ); } }
app/components/Header/index.js
sahilkhan99/PosApp
import React from 'react'; import NavLink from 'components/NavLink'; import Logo from './Logo'; import GitHubButton from '../GitHubButton'; import styles from './style.scss'; export default () => ( <div className={styles.header}> <NavLink to="/budget" label="Budget" styles={styles} /> <NavLink to="/reports" label="Reports" styles={styles} /> <GitHubButton className={styles.gitHubButton} type="Star" /> <GitHubButton className={styles.gitHubButton} type="Fork" /> <Logo /> </div> );
stories/fields/SimpleUserFieldsDemo.js
de44/kb-ui
import React from 'react' import kb from '../../src/kb-ui' import FieldsDemo from './FieldsDemo' const model = { id: "asdf-123", name: "John Deer", suspended: false, profile: { bio: '<h4 style="border-bottom: 1px dashed red;"><span style="color: blue">Hello, </span><span style="color: green">World!</span></h4>', website: { url: "https://github.com/de44", text: "de44 (github)" } } }; const fields = [ kb.field('id'), kb.field('name'), kb.field('suspended', 'bool'), kb.field('profile.bio', 'html').label('Bio'), kb.field('profile.website').render((val) => ( <span> Click Here: <a href={val.url} target="_blank">{val.text}</a> </span> )) ]; const fieldsDef = `const fields = [ kb.field('id'), kb.field('name'), kb.field('suspended', 'bool'), kb.field('profile.bio', 'html').label('Bio'), kb.field('profile.website').render((val) => ( <span> Click Here: <a href={val.url} target="_blank">{val.text}</a> </span> )) ];` const SimpleUserFieldsDemo = ({}) => { return ( <div className="ListViewDemo"> <FieldsDemo fields={fields} model={model} fieldsDef={fieldsDef} /> </div> ); } export default SimpleUserFieldsDemo
web/src/components/settings.js
frafra/is-osm-uptodate
import React from 'react'; function Settings({ setFilter }) { return ( <div className="input-group"> <div className="input-group-prepend"> <div className="input-group-text">Filter</div> </div> <input className="form-control" type="text" placeholder="example: amenity=*" onChange={(event) => setFilter(event.target.value)} /> </div> ); } export default Settings;
client/src/app/app.js
rajington/heartseekers
import React from 'react'; import injectTapEventPlugin from 'react-tap-event-plugin'; import { render } from 'react-dom'; import { Router, IndexRoute, Route } from 'react-router'; import App from './components/App'; import Main from './components/Main'; import Summoner from './components/Summoner'; import NoMatch from './components/NoMatch'; import history from './history'; // Needed for onTouchTap // Can go away when react 1.0 release // Check this repo: // https://github.com/zilverline/react-tap-event-plugin injectTapEventPlugin(); // useRouterHistory creates a composable higher-order function render(( <Router history={history}> <Route path="/" component={App}> <IndexRoute component={Main} /> <Route path="/summoners/:region/:name" component={Summoner} /> <Route path="*" component={NoMatch} /> </Route> </Router> ), document.getElementById('app'));
index.js
pedro-iago/rack-physics
import React from 'react'; import ReactDOM from 'react-dom'; import {App} from './src/apps'; ReactDOM.render( <App />, document.getElementById("root") ); window.onbeforeunload = () => ReactDOM.unmountComponentAtNode( document.getElementById("root") );
docs/app/Examples/collections/Table/Types/index.js
shengnian/shengnian-ui-react
import React from 'react' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' const Types = () => ( <ExampleSection title='Types'> <ComponentExample title='Types' description='A standard table.' examplePath='collections/Table/Types/TableExamplePagination' /> <ComponentExample examplePath='collections/Table/Types/TableExamplePadded' /> <ComponentExample examplePath='collections/Table/Types/TableExampleCollapsing' /> <ComponentExample examplePath='collections/Table/Types/TableExampleStriped' /> <ComponentExample title='Definition' description='A table may be formatted to emphasize a first column that defines a row content.' examplePath='collections/Table/Types/TableExampleDefinition' /> <ComponentExample examplePath='collections/Table/Types/TableExampleApprove' /> <ComponentExample title='Structured' description='A table can be formatted to display complex structured data.' examplePath='collections/Table/Types/TableExampleStructured' /> </ExampleSection> ) export default Types
src/scenes/Layout/components/Representation/components/Week/components/WeekCardVersion/WeekCardVersion.js
czonios/schedule-maker-app
import React from 'react'; import PropTypes from 'prop-types'; import DayCardVersion from '../../.././DayCardVersion/DayCardVersion.js' import HoverableIcon from '../../../../../../.././components/HoverableIcon/HoverableIcon'; import dateService from '../../../../../../../../services/dates/dateService'; import { Divider } from 'semantic-ui-react'; import './WeekCardVersion.css'; import DayHeader from './DayHeader/DayHeader'; const propTypes = { events: PropTypes.array.isRequired, displayEventModal: PropTypes.func.isRequired, deleteEvent: PropTypes.func.isRequired, displayYear: PropTypes.number.isRequired, displayMonth: PropTypes.number.isRequired, displayDay: PropTypes.number.isRequired, }; const defaultProps = {}; const WeekCardVersion = ({ events, displayEventModal, deleteEvent, displayYear, displayMonth, displayDay }) => { return ( <div className="weekViewWrapper"> {[1, 2, 3, 4].map(dayOfWeekVal => { const dayEvents = events.filter(event => event.date.dayOfWeek === dayOfWeekVal); return ( <div key={dayOfWeekVal} className="weekdayColumn"> <div className="dayHeader" > <DayHeader dayOfWeekVal={dayOfWeekVal} /> <Divider /> </div> <div className="add-event clickable"> <HoverableIcon className="add-event" name="add" onClickCb={displayEventModal} color='teal' show={true} inverted={false} cbArgs={{ year: displayYear, month: displayMonth, day: calculateDay(displayYear, displayMonth, displayDay, dayOfWeekVal) }} /> <Divider /> </div> <div> <DayCardVersion events={dayEvents} condensed={true} displayEventModal={displayEventModal} deleteEvent={deleteEvent} /> </div> </div> ) })} <div className="break"> <br /> </div> {[5, 6, 0].map(dayOfWeekVal => { const dayEvents = events.filter(event => event.date.dayOfWeek === dayOfWeekVal); return ( <div key={dayOfWeekVal} className="weekdayColumn"> <div className="dayHeader" > <DayHeader dayOfWeekVal={dayOfWeekVal} displayEventModal={displayEventModal} displayYear={displayYear} displayMonth={displayMonth} displayDay={displayDay} /> <Divider /> </div> <div className="add-event clickable"> <HoverableIcon className="add-event" name="add" onClickCb={displayEventModal} color='teal' show={true} inverted={false} cbArgs={{ year: displayYear, month: displayMonth, day: calculateDay(displayYear, displayMonth, displayDay, dayOfWeekVal) }} /> <Divider /> </div> <div> <DayCardVersion events={dayEvents} condensed={true} displayEventModal={displayEventModal} deleteEvent={deleteEvent} /> </div> </div> ) })} </div> ) } const calculateDay = (year, month, day, dayOfWeekVal) => { return dateService.getFirstMondayPreviousOrEqualToDay(year, month, day).day + (dayOfWeekVal === 0 ? 6 : dayOfWeekVal - 1); } WeekCardVersion.propTypes = propTypes; WeekCardVersion.defaultProps = defaultProps; export default WeekCardVersion;
ignite/DevScreens/FaqScreen.js
mohammadhendy/DriverApp
// An All Components Screen is a great way to dev and quick-test components import React from 'react' import { View, ScrollView, Text, Image, TouchableOpacity } from 'react-native' import { Images } from './DevTheme' import styles from './Styles/FaqScreenStyles' class ComponentExamplesScreen extends React.Component { render () { return ( <View style={[styles.container, styles.mainContainer]}> <Image source={Images.background} style={styles.backgroundImage} resizeMode='stretch' /> <TouchableOpacity onPress={() => this.props.navigation.goBack()} style={{ position: 'absolute', paddingTop: 30, paddingHorizontal: 5, zIndex: 10 }}> <Image source={Images.backButton} /> </TouchableOpacity> <ScrollView showsVerticalScrollIndicator={false} style={styles.container}> <View style={{alignItems: 'center', paddingTop: 60}}> <Image source={Images.faq} style={styles.logo} /> <Text style={styles.titleText}>FAQ</Text> </View> <View style={styles.description}> <Text style={styles.sectionText}> Have questions? We direct you to answers. This is a small taste of where to get more information depending on what it is that you want to know. </Text> </View> <View style={styles.sectionHeaderContainer}> <Text style={styles.sectionHeader}>What are these screens?</Text> <Text style={styles.sectionText}>We like to use these screens when we develop apps. They are optional and out of the way to help you along your app creation process. Each screen has an explanation of what it provides. More info can be found on our website http://infinite.red/ignite</Text> </View> <View style={styles.sectionHeaderContainer}> <Text style={styles.sectionHeader}>Got Docs?</Text> <Text style={styles.sectionText}>The GitHub page has a docs folder that can help you from beginner to expert! We'll be working to release some instructional video docs as well.</Text> </View> <View style={styles.sectionHeaderContainer}> <Text style={styles.sectionHeader}>I don't see the answer to my question in docs</Text> <Text style={styles.sectionText}>Besides our docs, we have a friendly community Slack. Get an invite from http://community.infinite.red and you'll find a community of people in the #ignite channel ready to help!</Text> </View> <View style={styles.sectionHeaderContainer}> <Text style={styles.sectionHeader}>What can I customize?</Text> <Text style={styles.sectionText}>Everything! We're open source with MIT license. We also make it easy to change whatever you like. Check on our guides for making your very own plugins and boilerplates with Ignite.</Text> </View> <View style={styles.sectionHeaderContainer}> <Text style={styles.sectionHeader}>I love you</Text> <Text style={styles.sectionText}> We love you, too. Don't forget to tweet us 😘 @infinite_red OR @ir_ignite </Text> </View> </ScrollView> </View> ) } } export default ComponentExamplesScreen
runoob-react-course/02-react-install/main.js
react-scott/react-learn
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render( <App />, document.getElementById('example') )
app/javascript/flavours/glitch/components/hashtag.js
im-in-space/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 'flavours/glitch/components/short_number'; import Skeleton from 'flavours/glitch/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} */ 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;
src/pure_components/WinnersList.react.js
Neil-G/ThinkQuick
import React, { Component } from 'react'; import moment from 'moment'; export class WinnersList extends Component { render(){ const { showWinnersColumn } = this.props return( <div className="winners-column" style={{ right: showWinnersColumn ? '0px' : '-200vw' }}> {/* Top Panel */} <div className='winners-top-panel'> <p style={{ textAlign: 'center' }}> Recent Leader: {this.props.leader} with {this.props.max} wins </p> <h3 style={{ marginTop: '10px'}}> Winners </h3> <span onClick={this.props.toggleWinnersColumnDisplay} className='close-winners-column' style={{ fontWeight: 'bold'}} > X </span> </div> {/* Scrollable Winner's Table */} <div className='winners-column-container'> <table className='winners-table'> <tbody> { this.props.winners.map( (winner, index) => { let timeStamp = new Date(winner.timeStamp); timeStamp = moment(timeStamp).fromNow(); var style = { height: '60px', background: index%2 == 0 ? "#FFEBEE" : "#FFEBEE" }; return( <tr key={winner.timeStamp} style={style}> {/* LAST WON INDEX */} <td class="hide-mobile" style={{ paddingLeft: '10px'}} className="hide-medium" > {index + 1}. </td> {/* GAME WINNER NAME */} <td style={{textAlign: 'left', paddingLeft: '6px'}}> {winner.email.split('@')[0] || "no split"} </td> {/* GAME NUMBER */} <td style={{textAlign: 'center', paddingRight: '4px' }}> game {winner.game[4]} </td> {/* GAME WIN DATE */} <td style={{textAlign: 'right', paddingRight: '6px'}} className="hide-large"> { timeStamp } </td> </tr> ); })} </tbody> </table> </div> </div> ); } }
modules/RouterContextMixin.js
jeffreywescott/react-router
import React from 'react'; import invariant from 'invariant'; import { stripLeadingSlashes, stringifyQuery } from './URLUtils'; var { func, object } = React.PropTypes; function pathnameIsActive(pathname, activePathname) { if (stripLeadingSlashes(activePathname).indexOf(stripLeadingSlashes(pathname)) === 0) return true; // This quick comparison satisfies most use cases. // TODO: Implement a more stringent comparison that checks // to see if the pathname matches any routes (and params) // in the currently active branch. return false; } function queryIsActive(query, activeQuery) { if (activeQuery == null) return query == null; if (query == null) return true; for (var p in query) if (query.hasOwnProperty(p) && String(query[p]) !== String(activeQuery[p])) return false; return true; } var RouterContextMixin = { propTypes: { stringifyQuery: func.isRequired }, getDefaultProps() { return { stringifyQuery }; }, childContextTypes: { router: object.isRequired }, getChildContext() { return { router: this }; }, /** * Returns a full URL path from the given pathname and query. */ makePath(pathname, query) { if (query) { if (typeof query !== 'string') query = this.props.stringifyQuery(query); if (query !== '') return pathname + '?' + query; } return pathname; }, /** * Returns a string that may safely be used to link to the given * pathname and query. */ makeHref(pathname, query) { var path = this.makePath(pathname, query); var { history } = this.props; if (history && history.makeHref) return history.makeHref(path); return path; }, /** * Pushes a new Location onto the history stack. */ transitionTo(pathname, query, state=null) { var { history } = this.props; invariant( history, 'Router#transitionTo is client-side only (needs history)' ); history.pushState(state, this.makePath(pathname, query)); }, /** * Replaces the current Location on the history stack. */ replaceWith(pathname, query, state=null) { var { history } = this.props; invariant( history, 'Router#replaceWith is client-side only (needs history)' ); history.replaceState(state, this.makePath(pathname, query)); }, /** * Navigates forward/backward n entries in the history stack. */ go(n) { var { history } = this.props; invariant( history, 'Router#go is client-side only (needs history)' ); history.go(n); }, /** * Navigates back one entry in the history stack. This is identical to * the user clicking the browser's back button. */ goBack() { this.go(-1); }, /** * Navigates forward one entry in the history stack. This is identical to * the user clicking the browser's forward button. */ goForward() { this.go(1); }, /** * Returns true if a <Link> to the given pathname/query combination is * currently active. */ isActive(pathname, query) { var { location } = this.state; if (location == null) return false; return pathnameIsActive(pathname, location.pathname) && queryIsActive(query, location.query); } }; export default RouterContextMixin;
src/routes/UIElement/dataTable/index.js
liuweiGL/eastcoal_mgr_react
import React from 'react' import { DataTable } from '../../../components' import { Table, Row, Col, Card, Select } from 'antd' class DataTablePage extends React.Component { constructor (props) { super(props) this.state = { filterCase: { gender: '', } } } handleSelectChange = (gender) => { this.setState({ filterCase: { gender, }, }) } render () { const { filterCase } = this.state const staticDataTableProps = { dataSource: [{ key: '1', name: 'John Brown', age: 24, address: 'New York' }, { key: '2', name: 'Jim Green', age: 23, address: 'London' }], columns: [{ title: 'name', dataIndex: 'name' }, { title: 'Age', dataIndex: 'age' }, { title: 'Address', dataIndex: 'address' }], pagination: false, } const fetchDataTableProps = { fetch: { url: 'https://randomuser.me/api', data: { results: 10, testPrams: 'test', }, dataKey: 'results', }, columns: [ { title: 'Name', dataIndex: 'name', render: (text) => `${text.first} ${text.last}` }, { title: 'Phone', dataIndex: 'phone' }, { title: 'Gender', dataIndex: 'gender' }, ], rowKey: 'registered', } const caseChangeDataTableProps = { fetch: { url: 'https://randomuser.me/api', data: { results: 10, testPrams: 'test', ...filterCase, }, dataKey: 'results', }, columns: [ { title: 'Name', dataIndex: 'name', render: (text) => `${text.first} ${text.last}` }, { title: 'Phone', dataIndex: 'phone' }, { title: 'Gender', dataIndex: 'gender' }, ], rowKey: 'registered', } return (<div className="content-inner"> <Row gutter={32}> <Col lg={12} md={24}> <Card title="默认"> <DataTable pagination={false} /> </Card> </Col> <Col lg={12} md={24}> <Card title="静态数据"> <DataTable {...staticDataTableProps} /> </Card> </Col> <Col lg={12} md={24}> <Card title="远程数据"> <DataTable {...fetchDataTableProps} /> </Card> </Col> <Col lg={12} md={24}> <Card title="参数变化"> <Select placeholder="Please select gender" allowClear onChange={this.handleSelectChange} style={{ width: 200, marginBottom: 16 }}> <Select.Option value="male">Male</Select.Option> <Select.Option value="female">Female</Select.Option> </Select> <DataTable {...caseChangeDataTableProps} /> </Card> </Col> </Row> <h2 style={{ margin: '16px 0' }}>Props</h2> <Row> <Col lg={18} md={24}> <Table rowKey={(record, key) => key} pagination={false} bordered scroll={{ x: 800 }} columns={[ { title: '参数', dataIndex: 'props', }, { title: '说明', dataIndex: 'desciption', }, { title: '类型', dataIndex: 'type', }, { title: '默认值', dataIndex: 'default', }, ]} dataSource={[ { props: 'fetch', desciption: '远程获取数据的参数', type: 'Object', default: '后面有空加上', }]} /> </Col> </Row> </div>) } } export default DataTablePage
assets/javascripts/kitten/components/form/field/stories.js
KissKissBankBank/kitten
import React from 'react' import { FieldInputExample, FieldPasswordExample, FieldRadioButtonSetExample, FieldRadioSetExample, FieldAutocompleteExample, } from './examples' import { DocsPage } from 'storybook/docs-page' export default { title: 'Form/Field', parameters: { docs: { page: () => ( <DocsPage filepath={__filename} filenames={[ 'index.js', 'components/autocomplete.js', 'components/checkbox.js', 'components/error.js', 'components/input.js', 'components/label.js', 'components/password.js', 'components/radio-set.js', 'components/radio-button-set.js', ]} importString="Field" /> ), }, }, decorators: [ story => ( <div className="story-Container story-Grid story-Grid--large"> <div>{story()}</div> </div> ), ], } export const WithInput = args => { return <FieldInputExample {...args} /> } WithInput.args = { id: 'input', size: 'medium', label: 'Label', tooltip: null, tooltipProps: { actionLabel: 'Learn more' }, tooltipId: 'tooltip', placeholder: 'Placeholder…', error: false, errorMessage: 'Error message…', limit: undefined, unit: undefined, noMargin: false, } WithInput.argTypes = { id: { control: 'text' }, size: { control: 'select', options: ['small', 'medium', 'large', 'huge', 'giant'], }, label: { control: 'text' }, tooltip: { control: 'text' }, tooltipProps: { control: 'object' }, tooltipId: { control: 'text' }, placeholder: { control: 'text' }, error: { control: 'boolean' }, errorMessage: { control: 'text' }, limit: { control: 'number' }, unit: { control: 'text' }, noMargin: { control: 'boolean' }, } export const WithPassword = args => { return <FieldPasswordExample {...args} /> } WithPassword.args = { id: 'input', size: 'medium', label: 'Label', tooltip: null, tooltipProps: { actionLabel: 'Learn more' }, tooltipId: 'tooltip', placeholder: 'Placeholder…', error: false, errorMessage: 'Error message…', } WithPassword.argTypes = { id: { control: 'text' }, size: { control: 'select', options: ['small', 'medium', 'large', 'huge', 'giant'], }, label: { control: 'text' }, tooltip: { control: 'text' }, tooltipProps: { control: 'object' }, tooltipId: { control: 'text' }, placeholder: { control: 'text' }, error: { control: 'boolean' }, errorMessage: { control: 'text' }, } export const WithRadioButtons = args => { return <FieldRadioButtonSetExample {...args} /> } WithRadioButtons.args = { id: 'option-a', size: 'medium', label: 'Label', tooltip: null, tooltipProps: { actionLabel: 'Learn more' }, tooltipId: 'tooltip', items: [ { text: 'Option A', id: 'option-a', defaultChecked: true, }, { text: 'Option B', id: 'option-b', }, { text: 'Option C', id: 'option-c', }, ], error: false, errorMessage: 'Error message…', } WithRadioButtons.argTypes = { id: { control: 'text' }, size: { control: 'select', options: ['small', 'medium', 'large'], }, label: { control: 'text' }, tooltip: { control: 'text' }, tooltipProps: { control: 'object' }, tooltipId: { control: 'text' }, items: { control: 'object' }, error: { control: 'boolean' }, errorMessage: { control: 'text' }, } export const WithRadio = args => { return <FieldRadioSetExample {...args} /> } WithRadio.args = { id: 'option-a', label: 'Label', tooltip: null, tooltipProps: { actionLabel: 'Learn more' }, tooltipId: 'tooltip', items: [ { text: 'Option A', id: 'option-a', defaultChecked: true, }, { text: 'Option B', id: 'option-b', }, { text: 'Option C', id: 'option-c', }, ], error: false, errorMessage: 'Error message…', } WithRadio.argTypes = { id: { control: 'text' }, label: { control: 'text' }, tooltip: { control: 'text' }, tooltipProps: { control: 'object' }, tooltipId: { control: 'text' }, items: { control: 'object' }, error: { control: 'boolean' }, errorMessage: { control: 'text' }, } export const WithAutocomplete = args => { return <FieldAutocompleteExample {...args} /> } WithAutocomplete.args = { id: 'select', size: 'medium', label: 'Label', tooltip: null, tooltipProps: { actionLabel: 'Learn more' }, tooltipId: 'tooltip', placeholder: 'Select…', items: [ 'Abyssin', 'Anatolien', 'Angora turc', 'Asian', 'Chartreux', 'Cymérien', 'Mandarin', 'Oriental shorthair', 'Persan', 'Sibérien', ], error: false, errorMessage: 'Error message…', } WithAutocomplete.argTypes = { id: { control: 'text' }, size: { control: 'select', options: ['small', 'medium', 'large', 'huge', 'giant'], }, label: { control: 'text' }, tooltip: { control: 'text' }, tooltipProps: { control: 'object' }, tooltipId: { control: 'text' }, placeholder: { control: 'text' }, items: { control: 'object' }, error: { control: 'boolean' }, errorMessage: { control: 'text' }, }
test/helpers.js
herojobs/react-bootstrap
import React from 'react'; import { cloneElement } from 'react'; export function shouldWarn(about) { console.warn.called.should.be.true; console.warn.calledWithMatch(about).should.be.true; console.warn.reset(); } /** * Helper for rendering and updating props for plain class Components * since `setProps` is deprecated. * @param {ReactElement} element Root element to render * @param {HTMLElement?} mountPoint Optional mount node, when empty it uses an unattached div like `renderIntoDocument()` * @return {ComponentInstance} The instance, with a new method `renderWithProps` which will return a new instance with updated props */ export function render(element, mountPoint){ let mount = mountPoint || document.createElement('div'); let instance = React.render(element, mount); if (!instance.renderWithProps) { instance.renderWithProps = function(newProps) { return render( cloneElement(element, newProps), mount); }; } return instance; }
cryptography/lab2/client/components/DataView.js
Drapegnik/bsu
import React from 'react'; import { Text, View, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ container: { position: 'absolute', top: 50, }, key: { fontSize: 17, fontFamily: 'Courier', textAlign: 'center', lineHeight: 25, }, }); export default ({ publicKey, privateKey, sessionKey }) => ( <View style={styles.container}> <Text style={styles.key}> Public: ({publicKey.e}, {publicKey.n}) </Text> <Text style={styles.key}> Private: ({privateKey.d}, {privateKey.n}) </Text> {sessionKey && <Text style={styles.key}>Session: {sessionKey}</Text>} </View> );
examples/async/index.js
aheuermann/redux
import 'babel-core/polyfill'; import React from 'react'; import Root from './containers/Root'; React.render( <Root />, document.getElementById('root') );
frontend/app_v2/src/components/DeleteButton/DeleteButtonContainer.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' // FPCC import DeleteButtonData from 'components/DeleteButton/DeleteButtonData' import DeleteButtonPresentation from 'components/DeleteButton/DeleteButtonPresentation' function DeleteButtonContainer({ id, label, styling }) { const { deleteHandler } = DeleteButtonData({ id }) return <DeleteButtonPresentation deleteHandler={deleteHandler} label={label} styling={styling} /> } // PROPTYPES const { string } = PropTypes DeleteButtonContainer.propTypes = { id: string, label: string, styling: string, } export default DeleteButtonContainer
src/routes.js
Anshul-HL/blitz-row
import React from 'react'; import {IndexRoute, Route, Router} from 'react-router'; import { BlitzApp, BlitzHome, BlitzAllProjects, BlitzSingleProject, BlitzApartment, BlitzRoomDesign, BlitzShowroomPage } from 'containers'; export default () => { /** * Please keep routes in alphabetical order */ return ( <Router> <Route path="/" component={BlitzApp}> <IndexRoute component={BlitzHome}/> <Route path="showroom" component={BlitzShowroomPage}/> <Route path="pastprojects" component={BlitzAllProjects}/> <Route path="pastprojects/:projectUrl" component={BlitzSingleProject}/> <Route path="homes/:projectid" component={BlitzApartment}/> <Route path="homes/:projectid/:roomtype" component={BlitzRoomDesign}/> </Route> </Router> ); };
app/src/components/Highlight.js
GlyphGryph/DarkerDaysAhead
import React from 'react' import PropTypes from 'prop-types' const Highlight = ( { color, backgroundColor, opacity, width, height, zIndex, xPosition, yPosition, borderWidth } ) => ( <div className={'highlight blink-to-transparent'} style={{ position: 'absolute', top: ''+yPosition+'px', left: ''+xPosition+'px', width: ''+width+'px', height: ''+height+'px', textAlign: 'center', verticalAlign: 'top', zIndex, color, backgroundColor, opacity, border: ''+borderWidth+'px dotted black', borderRadius: '15px' }} > X </div> ) Highlight.propTypes = { color: PropTypes.string.isRequired, backgroundColor: PropTypes.string.isRequired, opacity: PropTypes.number.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, zIndex: PropTypes.number.isRequired, xPosition: PropTypes.number.isRequired, yPosition: PropTypes.number.isRequired } export default Highlight
renderer/components/Form/LndConnectionStringInput.js
LN-Zap/zap-desktop
import React from 'react' import PropTypes from 'prop-types' import { injectIntl } from 'react-intl' import { isValidLndConnectUri, isValidBtcPayConfig } from '@zap/utils/connectionString' import TextArea from './TextArea' import messages from './messages' import { intlShape } from '@zap/i18n' const mask = value => value && value.trim() class LndConnectionStringInput extends React.Component { static displayName = 'LndConnectionStringInput' static propTypes = { initialValue: PropTypes.string, intl: intlShape.isRequired, } prettyPrint = json => { try { return JSON.stringify(JSON.parse(json), undefined, 4) } catch (e) { return json } } /** * validate - Check for a valid lndconnect uri or BtcPayServer connection string. * * @param {string} value String to validate. * @returns {boolean} Boolean indicating whether the string is a valid or not. */ validate = value => { const { intl } = this.props const isValid = isValidLndConnectUri(value) || isValidBtcPayConfig(value) if (!isValid) { return intl.formatMessage({ ...messages.invalid_lnd_connection_string }) } return undefined } render() { const { initialValue, intl, ...rest } = this.props const formattedInitialValue = initialValue ? this.prettyPrint(initialValue) : null return ( <TextArea css="word-break: break-all;" initialValue={formattedInitialValue} mask={mask} placeholder={intl.formatMessage({ ...messages.lnd_connection_string_placeholder })} rows={5} {...rest} spellCheck="false" validate={this.validate} /> ) } } export default injectIntl(LndConnectionStringInput)
pathfinder/vtables/applicationdataqualitycompleteness/src/common/Link.js
leanix/leanix-custom-reports
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class Link extends Component { constructor(props) { super(props); this._handleClick = this._handleClick.bind(this); } _handleClick(e) { e.preventDefault(); lx.openLink(this.props.link, this.props.target); } render() { if (!this.props.link || !this.props.target || !this.props.text) { return null; } switch (this.props.target) { case '_blank': return ( <a href={this.props.link} title='Opens a new tab/window.' target={this.props.target} onClick={this._handleClick} >{this.props.text}</a> ); default: return ( <a href={this.props.link} target={this.props.target} onClick={this._handleClick} >{this.props.text}</a> ); } } } Link.propTypes = { link: PropTypes.string.isRequired, target: PropTypes.string.isRequired, text: PropTypes.string.isRequired }; export default Link;
src/decorators/withViewport.js
Mobiletainment/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = {width: 1366, height: 768}; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = {width: window.innerWidth, height: window.innerHeight}; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on('resize', this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({viewport: value}); } }; } export default withViewport;
src/Parser/Shaman/Elemental/Modules/Items/TheDeceiversBloodPact.js
enragednuke/WoWAnalyzer
import React from 'react'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import ItemIcon from 'common/ItemIcon'; import ItemLink from 'common/ItemLink'; import { formatNumber } from 'common/format'; class TheDeceiversBloodPact extends Analyzer { static dependencies = { combatants: Combatants, }; extraMaelstrom = 0; on_initialized() { this.active = this.combatants.selected.hasBuff(SPELLS.THE_DECEIVERS_BLOOD_PACT_EQUIP.id); } on_byPlayer_energize(event) { if (event.ability.guid===SPELLS.THE_DECEIVERS_BLOOD_PACT_BUFF.id) { this.extraMaelstrom+=event.classResources[0].amount; } } item() { return { id: `item-${ITEMS.THE_DECEIVERS_BLOOD_PACT.id}`, icon: <ItemIcon id={ITEMS.THE_DECEIVERS_BLOOD_PACT.id} />, title: <ItemLink id={ITEMS.THE_DECEIVERS_BLOOD_PACT.id} />, result: `${formatNumber(this.extraMaelstrom)} Maelstrom refunded`, }; } } export default TheDeceiversBloodPact;
app/containers/Cloud.js
arixse/ReactNeteaseCloudMusic
import React, { Component } from 'react'; import { PropTypes } from 'react'; import { connect } from 'react-redux'; // import Header from './Header'; // import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import Play from './Play'; class Cloud extends Component { constructor(props) { super(props); this.onPlaying = this.onPlaying.bind(this); this.state = { progress: 0, currentTime: 0, duration: 0 }; } onPlaying(obj) { this.setState(obj); } render() { const {progress, currentTime, duration} = this.state; return ( <div> {React.Children.map(this.props.children, (child) => { return React.cloneElement(child, { progress: progress, currentTime: currentTime, duration }); })} <Play onPlaying={this.onPlaying} /> </div> ); } } Cloud.propTypes = { children: PropTypes.any }; export default connect()(Cloud);
jenkins-design-language/src/js/components/material-ui/svg-icons/av/add-to-queue.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const AvAddToQueue = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-7v2h-3v3h-2v-3H8v-2h3V7h2v3h3z"/> </SvgIcon> ); AvAddToQueue.displayName = 'AvAddToQueue'; AvAddToQueue.muiName = 'SvgIcon'; export default AvAddToQueue;
src/components/seasons/seasons-list.js
sunpietro/LeagueManager
import React, { Component } from 'react'; import DefaultLayout from '../layouts/default'; class SeasonsList extends Component { render() { return <DefaultLayout subtitle="Seasons" isLoading={false}></DefaultLayout>; } } export default SeasonsList;
src/TabbedArea.js
brynjagr/react-bootstrap
import React from 'react'; import Tabs from './Tabs'; import TabPane from './TabPane'; import ValidComponentChildren from './utils/ValidComponentChildren'; import deprecationWarning from './utils/deprecationWarning'; const TabbedArea = React.createClass({ componentWillMount() { deprecationWarning( 'TabbedArea', 'Tabs', 'https://github.com/react-bootstrap/react-bootstrap/pull/1091' ); }, render() { const {children, ...props} = this.props; const tabs = ValidComponentChildren.map(children, function(child) { const {tab: title, ...others} = child.props; return <TabPane title={title} {...others} />; }); return ( <Tabs {...props}>{tabs}</Tabs> ); } }); export default TabbedArea;
Cordial/app/containers/profile-container.js
AwesomePossum446/Cordial
import _ from 'lodash'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { View, Text, StyleSheet, StatusBar } from 'react-native'; import ConnectToModel from '../models/connect-to-model'; import {Card, User} from '../models/Model'; import CardContainer from '../containers/card-container'; import { Splash } from '../components/splash-screen'; //import StatusBarBackground from '../components/statusbar-background'; import {brightBlue, lightBlue} from '../consts/styles'; class ProfileContainer extends Component { render() { // TODO: This assumes user only has one card const cards = Card.myCards(); if (cards.length === 0) return <Splash/>; return ( <View style={{flex: 1}}> <StatusBar backgroundColor={brightBlue} /> <CardContainer readOnly={false} id={cards[0].id}/> </View> ); } } const styles = StyleSheet.create({ titleContainer: { backgroundColor: lightBlue, borderBottomColor: brightBlue, padding: 8, paddingLeft: 5, paddingRight: 15, flexDirection: 'row', justifyContent: 'space-between' }, titleText: { fontSize: 25, margin: 0, textDecorationLine: 'none', }, popUpContainer: { backgroundColor: brightBlue, padding: 8, paddingLeft: 20, paddingRight: 20, }, icon: { backgroundColor:lightBlue }, popUp: { backgroundColor: brightBlue, padding: 8, paddingLeft: 20, paddingRight: 20, flexDirection: 'column', justifyContent: 'space-between' }, }); export default ConnectToModel(ProfileContainer, Card);
website/src/containers/Relays.js
DTU-R3/ArloBot
import React, { Component } from 'react'; import { Collapse, Card, CardBody, CardHeader, CardTitle } from 'reactstrap'; import boolToOnOff from '../utils/boolToOnOff'; class Relays extends Component { constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.state = { isOpen: false }; } toggle() { this.setState({ isOpen: !this.state.isOpen }); } render() { const cardBody = this.props.relays.map((entry) => { let thisButtonClass = 'btn'; let thisButtonBadgeClass = 'badge badge-secondary'; if (entry.relayOn) { thisButtonClass = 'btn btn-success'; thisButtonBadgeClass = 'badge badge-light'; } return ( <span key={entry.number}> <button type="button" className={thisButtonClass} onClick={() => this.props.sendDataToRobot('toggleRelay', entry.number) } > {entry.fancyName}&nbsp; <span className={thisButtonBadgeClass}> {boolToOnOff(entry.relayOn)} </span> </button> </span> ); }); return ( <Card id="status-card" className="card-title"> <CardHeader onClick={this.toggle}> <CardTitle>Relays</CardTitle> </CardHeader> <Collapse isOpen={this.state.isOpen}> <CardBody>{cardBody}</CardBody> </Collapse> </Card> ); } } export default Relays;
app/user/profile/ModalSkillList.js
sagnikm95/internship-portal
import React from 'react'; import { Modal, Button, Icon, Divider } from 'semantic-ui-react'; import axios from 'axios'; import PropTypes from 'prop-types'; import Auth from '../../auth/modules/Auth'; import User from '../../auth/modules/User'; import AvailableSkillListItem from './AvailableSkillListItem'; import SelectedSkillListItem from './SelectedSkillListItem'; export default class ModalSkillList extends React.Component { constructor() { super(); this.state = { open: false }; this.open = () => { this.setState({ ...this.state, open: true }); }; this.close = () => { this.props.close(); this.setState({ ...this.state, open: false }); }; this.handleAdd = () => { this.props.handleAdd(); this.setState({ ...this.state, open: false }); }; } render() { const availableSkillItems = this.props.unselectedSkills.map(item => ( <AvailableSkillListItem key={item} skill={item} addSkill={this.props.addSkill} /> )); const selectedSkillItems = this.props.selectedSkills.map(item => ( <SelectedSkillListItem key={item} skill={item} removeSkill={this.props.removeSkill} /> )); return ( <div> <Button onClick={this.open} size="small" > <Icon name="add" /> Add a new skill </Button> <Modal closeIcon open={this.state.open} onClose={this.close} > <Modal.Header>Select a new skill</Modal.Header> <Modal.Content scrolling> <Modal.Description> {selectedSkillItems} <Divider section /> {availableSkillItems} <Divider section /> <Button primary onClick={this.handleAdd} floated="right"> Add </Button> </Modal.Description> </Modal.Content> </Modal> </div> ); } } ModalSkillList.propTypes = { handleAdd: PropTypes.func.isRequired, close: PropTypes.func.isRequired, selectedSkills: PropTypes.arrayOf(PropTypes.string).isRequired, unselectedSkills: PropTypes.arrayOf(PropTypes.string).isRequired, addSkill: PropTypes.func.isRequired, removeSkill: PropTypes.func.isRequired, };
src/index.js
durw4rd/curve-fever
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
docs/src/app/components/pages/components/Popover/ExampleConfigurable.js
pomerantsev/material-ui
import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import RadioButton from 'material-ui/RadioButton'; import Popover from 'material-ui/Popover/Popover'; import {Menu, MenuItem} from 'material-ui/Menu'; const styles = { h3: { marginTop: 20, fontWeight: 400, }, block: { display: 'flex', }, block2: { margin: 10, }, }; export default class PopoverExampleConfigurable extends React.Component { constructor(props) { super(props); this.state = { open: false, anchorOrigin: { horizontal: 'left', vertical: 'bottom', }, targetOrigin: { horizontal: 'left', vertical: 'top', }, }; } handleTouchTap = (event) => { // This prevents ghost click. event.preventDefault(); this.setState({ open: true, anchorEl: event.currentTarget, }); }; handleRequestClose = () => { this.setState({ open: false, }); }; setAnchor = (positionElement, position) => { const {anchorOrigin} = this.state; anchorOrigin[positionElement] = position; this.setState({ anchorOrigin: anchorOrigin, }); }; setTarget = (positionElement, position) => { const {targetOrigin} = this.state; targetOrigin[positionElement] = position; this.setState({ targetOrigin: targetOrigin, }); }; render() { return ( <div> <RaisedButton onTouchTap={this.handleTouchTap} label="Click me" /> <h3 style={styles.h3}>Current Settings</h3> <pre> anchorOrigin: {JSON.stringify(this.state.anchorOrigin)} <br /> targetOrigin: {JSON.stringify(this.state.targetOrigin)} </pre> <h3 style={styles.h3}>Position Options</h3> <p>Use the settings below to toggle the positioning of the popovers above</p> <h3 style={styles.h3}>Anchor Origin</h3> <div style={styles.block}> <div style={styles.block2}> <span>Vertical</span> <RadioButton onClick={this.setAnchor.bind(this, 'vertical', 'top')} label="Top" checked={this.state.anchorOrigin.vertical === 'top'} /> <RadioButton onClick={this.setAnchor.bind(this, 'vertical', 'center')} label="Center" checked={this.state.anchorOrigin.vertical === 'center'} /> <RadioButton onClick={this.setAnchor.bind(this, 'vertical', 'bottom')} label="Bottom" checked={this.state.anchorOrigin.vertical === 'bottom'} /> </div> <div style={styles.block2}> <span>Horizontal</span> <RadioButton onClick={this.setAnchor.bind(this, 'horizontal', 'left')} label="Left" checked={this.state.anchorOrigin.horizontal === 'left'} /> <RadioButton onClick={this.setAnchor.bind(this, 'horizontal', 'middle')} label="Middle" checked={this.state.anchorOrigin.horizontal === 'middle'} /> <RadioButton onClick={this.setAnchor.bind(this, 'horizontal', 'right')} label="Right" checked={this.state.anchorOrigin.horizontal === 'right'} /> </div> </div> <h3 style={styles.h3}>Target Origin</h3> <div style={styles.block}> <div style={styles.block2}> <span>Vertical</span> <RadioButton onClick={this.setTarget.bind(this, 'vertical', 'top')} label="Top" checked={this.state.targetOrigin.vertical === 'top'} /> <RadioButton onClick={this.setTarget.bind(this, 'vertical', 'center')} label="Center" checked={this.state.targetOrigin.vertical === 'center'} /> <RadioButton onClick={this.setTarget.bind(this, 'vertical', 'bottom')} label="Bottom" checked={this.state.targetOrigin.vertical === 'bottom'} /> </div> <div style={styles.block2}> <span>Horizontal</span> <RadioButton onClick={this.setTarget.bind(this, 'horizontal', 'left')} label="Left" checked={this.state.targetOrigin.horizontal === 'left'} /> <RadioButton onClick={this.setTarget.bind(this, 'horizontal', 'middle')} label="Middle" checked={this.state.targetOrigin.horizontal === 'middle'} /> <RadioButton onClick={this.setTarget.bind(this, 'horizontal', 'right')} label="Right" checked={this.state.targetOrigin.horizontal === 'right'} /> </div> </div> <Popover open={this.state.open} anchorEl={this.state.anchorEl} anchorOrigin={this.state.anchorOrigin} targetOrigin={this.state.targetOrigin} onRequestClose={this.handleRequestClose} > <Menu> <MenuItem primaryText="Refresh" /> <MenuItem primaryText="Help &amp; feedback" /> <MenuItem primaryText="Settings" /> <MenuItem primaryText="Sign out" /> </Menu> </Popover> </div> ); } }
src/svg-icons/maps/local-laundry-service.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalLaundryService = (props) => ( <SvgIcon {...props}> <path d="M9.17 16.83c1.56 1.56 4.1 1.56 5.66 0 1.56-1.56 1.56-4.1 0-5.66l-5.66 5.66zM18 2.01L6 2c-1.11 0-2 .89-2 2v16c0 1.11.89 2 2 2h12c1.11 0 2-.89 2-2V4c0-1.11-.89-1.99-2-1.99zM10 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM7 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm5 16c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z"/> </SvgIcon> ); MapsLocalLaundryService = pure(MapsLocalLaundryService); MapsLocalLaundryService.displayName = 'MapsLocalLaundryService'; MapsLocalLaundryService.muiName = 'SvgIcon'; export default MapsLocalLaundryService;
docs/src/sections/MediaSection.js
apkiernan/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function MediaSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="media-objects">Media objects</Anchor> <small>Media, Media.Left, Media.Right, Media.Heading, Media.List, Media.ListItem</small> </h2> <p>Abstract object styles for building various types of components (like blog comments, Tweets, etc) that feature a <code>left</code> or <code>right</code> aligned image alongside textual content.</p> <ReactPlayground codeText={Samples.MediaObject} /> <h3><Anchor id="media-alignment">Media Alignment</Anchor></h3> <p>The images or other media can be aligned top, middle, or bottom. The default is top aligned.</p> <ReactPlayground codeText={Samples.MediaAlignment} /> <h3> <Anchor id="media-list">Media list</Anchor> </h3> <p>You can use media inside list (useful for comment threads or articles lists).</p> <ReactPlayground codeText={Samples.MediaList} /> <h3><Anchor id="media-props">Props</Anchor></h3> <h4><Anchor id="media-media-props">Media</Anchor></h4> <PropTable component="Media"/> <h4><Anchor id="media-left-props">Media.Left</Anchor></h4> <PropTable component="Media.Left"/> <h4><Anchor id="media-right-props">Media.Right</Anchor></h4> <PropTable component="Media.Right"/> <h4><Anchor id="media-heading-props">Media.Heading</Anchor></h4> <PropTable component="Media.Heading"/> <h4><Anchor id="media-body-props">Media.Body</Anchor></h4> <PropTable component="Media.Body"/> </div> ); }
client/routes/polls.js
ncrmro/reango
import React from 'react' import Bundle from 'utils/bundleLoader' //import QuestionBrowser from 'modules/polls/QuestionBrowser'; import QuestionResultsPage from 'modules/polls/QuestionResults/QuestionResultsPage' import VotePage from 'modules/polls/VoteForm/VotePage' import NewPoll from 'modules/polls/NewPoll/NewPoll' import { authenticatedRoute } from 'modules/auth/utils' const QuestionBrowser = props => <Bundle load={() => import(/* webpackChunkName: "polls" */ 'modules/polls/QuestionBrowser/QuestionBrowser')} > { Component => <Component { ...props}/> } </Bundle> const pollRoutes = [ { path: '/polls', component: authenticatedRoute(QuestionBrowser) }, { path: '/polls/:id/results', component: authenticatedRoute(QuestionResultsPage) }, { path: '/polls/:id/vote', component: authenticatedRoute(VotePage) }, { path: '/polls/new', component: authenticatedRoute(NewPoll) } ] export default pollRoutes
src/task2/client/components/search-form.js
tormozz48/2do2go.ru
import React from 'react'; import { Form, Field, Control, Errors } from 'react-redux-form'; import { Button, FormGroup, ControlLabel, FormControl, HelpBlock } from 'react-bootstrap'; import * as actions from './actions'; const isValidUrl = (url) => /^https?:\/\/www\.reddit\.com\/r\/\w+\/\.json$/.test(url); function FieldGroup({ id, label, model, help, ...props }) { return ( <FormGroup controlId={id}> <ControlLabel>{label}</ControlLabel> <FormControl {...props} /> <Errors model="search.url" messages={{ isRequired: `Please provide an ${label}.`, isValidUrl: () => `Invalid ${label}.`, }} /> </FormGroup> ); } function SelectField({ id, label, model, options }) { options = options.map((option, index) => { return <option key={index} value={option}>{option}</option>; }); return ( <FormGroup controlId={id}> <ControlLabel>{label}</ControlLabel> <Control.select model={model} className="form-control"> {options} </Control.select> </FormGroup> ); } export default class SearchForm extends React.Component { handleSubmit(values) { actions.searchData(values); } render() { return ( <Form model="search" onSubmit={this.handleSubmit.bind(this)}> <Control.text model=".url" label="Url" component={FieldGroup} required validators={{isValidUrl}} validateOn="blur" /> <SelectField id="sortField" label="Sort Field" model=".sort.field" options={["domain", "count", "score"]} /> <FormGroup controlId="sortDirection"> <ControlLabel>Sort Direction</ControlLabel> <Field model=".sort.direction"> <label className="direction-label"> <input className="radio" type="radio" value="asc" /> Asc </label> <label className="direction-label"> <input className="radio" type="radio" value="desc" /> Desc </label> </Field> </FormGroup> <SelectField id="outputType" label="Output Type" model=".output.type" options={["csv", "json", "sql"]} /> <Button type="submit">Search</Button> </Form> ); } }
packages/react/src/components/FormLabel/FormLabel-story.js
carbon-design-system/carbon-components
/** * 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 React from 'react'; import FormLabel from './FormLabel'; import Tooltip from '../Tooltip'; import mdx from './FormLabel.mdx'; export default { title: 'Components/FormLabel', parameters: { component: FormLabel, docs: { page: mdx, }, }, }; export const _Default = () => <FormLabel>Form label</FormLabel>; _Default.story = { name: 'Form Label', }; export const WithTooltip = () => ( <FormLabel> <Tooltip triggerText="Form label"> This can be used to provide more information about a field. </Tooltip> </FormLabel> ); WithTooltip.story = { name: 'Form Label with Tooltip', };
src/parser/demonhunter/havoc/CONFIG.js
sMteX/WoWAnalyzer
import React from 'react'; import { Mamtooth, Yajinni } from 'CONTRIBUTORS'; import SPECS from 'game/SPECS'; import retryingPromise from 'common/retryingPromise'; import CHANGELOG from './CHANGELOG'; export default { // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion. contributors: [Mamtooth, Yajinni], // The WoW client patch this spec was last updated to be fully compatible with. patchCompatibility: '8.1.5', // If set to false`, the spec will show up as unsupported. isSupported: true, // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more. // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component. description: ( <> Welcome to the Havoc Demon Hunter analyzer! We hope you find these suggestions and statistics useful.<br /> <br />More resources for Havoc:<br /> <a href="https://discord.gg/zGGkNGC" target="_blank" rel="noopener noreferrer">Demon Hunter Class Discord</a> <br /> <a href="https://www.wowhead.com/havoc-demon-hunter-guide" target="_blank" rel="noopener noreferrer">Wowhead Guide</a> <br /> <a href="https://www.icy-veins.com/wow/havoc-demon-hunter-pve-dps-guide" target="_blank" rel="noopener noreferrer">Icy Veins Guide</a> <br /> </> ), // A recent example report to see interesting parts of the spec. Will be shown on the homepage. exampleReport: '/report/TGzmk4bXDZJndpj7/6-Heroic+Opulence+-+Kill+(8:12)/5-Tarke', // Don't change anything below this line; // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about. spec: SPECS.HAVOC_DEMON_HUNTER, // The contents of your changelog. changelog: CHANGELOG, // The CombatLogParser class for your spec. parser: () => retryingPromise(() => import('./CombatLogParser' /* webpackChunkName: "HavocDemonHunter" */).then(exports => exports.default)), // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code. path: __dirname, };
actor-apps/app-web/src/app/components/modals/create-group/ContactItem.react.js
hzy87email/actor-platform
import React from 'react'; import AvatarItem from 'components/common/AvatarItem.react'; class ContactItem extends React.Component { static propTypes = { contact: React.PropTypes.object, onToggle: React.PropTypes.func } constructor(props) { super(props); this.onToggle = this.onToggle.bind(this); this.state = { isSelected: false }; } onToggle() { const isSelected = !this.state.isSelected; this.setState({ isSelected: isSelected }); this.props.onToggle(this.props.contact, isSelected); } render() { let contact = this.props.contact; let icon; if (this.state.isSelected) { icon = 'check_box'; } else { icon = 'check_box_outline_blank'; } return ( <li className="contacts__list__item row"> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> <div className="controls"> <a className="material-icons" onClick={this.onToggle}>{icon}</a> </div> </li> ); } } export default ContactItem;
app/js/components/Snippets.js
jrschupak/trysnippets2.0
'use strict'; import React from 'react'; class Snippets extends React.Component { constructor () { super(); this.state = { snippet1: { snippetArr: [{id: 0, content: "contstructor () {"}, {id: 1, content: "super();"}, {id: 2, content: "this.state = {"}, {id: 3, content: "}"}, {id: 4, content: "}"} ]}, snippet2: { snippetArr: [{id:0, content: "<div>"}, {id: 2, content: "This is snippet 2"}, {id: 3, content: "</div>"}]} } } componentWillMount(){ console.log("Snippets.js ", this.props.snippets); } componentDidMount(){ console.log("snippet1", this.state.snippet1[1]); } snippetsContainer(){ var snipCont = document.querySelector('snippets-container'); console.log(snipCont); } render() { var displayNone = { display: "none" } var display = { } var lines = { color: "black", width: "90%", textAlign: "left", paddingLeft: "20px" } return ( <div id="snippets-cont"> <div className="snippets-container " id={0} style={displayNone}>{this.state.snippet1.snippetArr.map(function(line) { console.log(line); return <p key={line.id} style={lines}> {line.content} <br /> </p> })} </div> <div className="snippets-container " id={1} style={displayNone}>{this.state.snippet2.snippetArr.map(function(line) { console.log(line); return <p key={line.id} style={lines}> {line.content} <br /> </p> })} </div> </div> ); } } export default Snippets;
src/icons/font/PhotoIcon.js
skystebnicki/chamel
import React from 'react'; import PropTypes from 'prop-types'; import FontIcon from '../../FontIcon'; import ThemeService from '../../styles/ChamelThemeService'; /** * Photo button * * @param props * @param context * @returns {ReactDOM} * @constructor */ const PhotoIcon = (props, context) => { let theme = context.chamelTheme && context.chamelTheme.fontIcon ? context.chamelTheme.fontIcon : ThemeService.defaultTheme.fontIcon; return ( <FontIcon {...props} className={theme.iconPhoto}> {'photo'} </FontIcon> ); }; /** * An alternate theme may be passed down by a provider */ PhotoIcon.contextTypes = { chamelTheme: PropTypes.object, }; export default PhotoIcon;
src/containers/stationData/ShortCountVolumeForStation.js
availabs/avail_app_bootstrap
import React from 'react'; import { QueryRenderer, graphql } from 'react-relay'; import ShortCountVol from '../../components/counts/ShortCountVol'; import relay from '../../relay.js'; // https://github.com/facebook/relay/issues/1851 const q = graphql` query ShortCountVolumeForStationQuery( $condition: ShortCountVolumeCondition! ) { allShortCountVolumes(first: 10, condition: $condition) { edges { node { rcStation countId rg regionCode countyCode stat rcsta functionalClass factorGroup latitude longitude specificRecorderPlacement channelNotes dataType vehicleAxleCode year month day dayOfWeek federalDirection laneCode lanesInDirection collectionInterval interval11 interval12 interval13 interval14 interval21 interval22 interval23 interval24 interval31 interval32 interval33 interval34 interval41 interval42 interval43 interval44 interval51 interval52 interval53 interval54 interval61 interval62 interval63 interval64 interval71 interval72 interval73 interval74 interval81 interval82 interval83 interval84 interval91 interval92 interval93 interval94 interval101 interval102 interval103 interval104 interval111 interval112 interval113 interval114 interval121 interval122 interval123 interval124 interval131 interval132 interval133 interval134 interval141 interval142 interval143 interval144 interval151 interval152 interval153 interval154 interval161 interval162 interval163 interval164 interval171 interval172 interval173 interval174 interval181 interval182 interval183 interval184 interval191 interval192 interval193 interval194 interval201 interval202 interval203 interval204 interval211 interval212 interval213 interval214 interval221 interval222 interval223 interval224 interval231 interval232 interval233 interval234 interval241 interval242 interval243 interval244 total flagField batchId } } } } `; export default function ShortCountVolumeForStation(props) { let { stationId: rcStation } = props.match.params; return ( <div> <QueryRenderer environment={relay} query={q} variables={{ condition: { rcStation } }} render={({ error, props }) => { if (error) { return <div>{error.message}</div>; } else if (props) { let countObject = props.allShortCountVolumes.edges.reduce( (acc, { node: n }) => { let currentCount = acc[n.countId] ? acc[n.countId] : { rcStation: n.rcStation, rg: n.rg, regionCode: n.regionCode, countyCode: n.countyCode, stat: n.stat, rcsta: n.rcsta, functionalClass: n.functionalClass, factorGroup: n.factorGroup, latitude: n.latitude, longitude: n.longitude, specificRecorderPlacement: n.specificRecorderPlacement, channelNotes: n.channelNotes, dataType: n.dataType, vehicleAxleCode: n.vehicleAxleCode, year: n.year, month: n.month, dayOfFirstData: n.day, counts: {}, countId: n.countId, batchId: n.batchId }; let currentDate = `${n.month}/${n.day}/${n.year}`; if (!currentCount['counts'][currentDate]) { currentCount['counts'][currentDate] = {}; } currentCount['counts'][currentDate][n.federalDirection] = { federalDirection: n.federalDirection, total: n.total, year: n.year, month: n.month, date: currentDate, dayOfWeek: n.dayOfWeek, dayOfFirstData: n.day, data: Object.keys(n) .filter(key => key.indexOf('interval') !== -1) .sort( (a, b) => +a.split('interval')[1] - +b.split('interval')[1] ) .map(key => n[key] || 0) .filter((d, i) => i % (n.collectionInterval / 15) === 0) }; acc[n.countId] = currentCount; return acc; }, {} ); var countsGraphs = Object.keys(countObject) .sort((a, b) => +countObject[b].year - +countObject[a].year) .map(countId => <ShortCountVol data={countObject[countId]} />); return <div>{countsGraphs}</div>; // return ( // <div> // <pre>{JSON.stringify(countObject, null, 4)}</pre> // <pre>{JSON.stringify(props, null, 4)}</pre> // </div> // ); } return <div>Loading</div>; }} /> </div> ); }
src/js/components/icons/base/Robot.js
linde12/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-robot`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'robot'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M18.3482396,15.9535197 C18.7664592,15.0561341 19,14.0553403 19,13 C19,9.13400675 15.8659932,6 12,6 C8.13400675,6 5,9.13400675 5,13 C5,14.1167756 5.2615228,15.1724692 5.72666673,16.1091793 L5.72666673,16.1091793 M12,3 C12.5522847,3 13,2.55228475 13,2 C13,1.44771525 12.5522847,1 12,1 C11.4477153,1 11,1.44771525 11,2 C11,2.55228475 11.4477153,3 12,3 Z M12,23 C12.5522847,23 13,22.5522847 13,22 C13,21.4477153 12.5522847,21 12,21 C11.4477153,21 11,21.4477153 11,22 C11,22.5522847 11.4477153,23 12,23 Z M12,6 L12,3 M9,14 C9.55228475,14 10,13.5522847 10,13 C10,12.4477153 9.55228475,12 9,12 C8.44771525,12 8,12.4477153 8,13 C8,13.5522847 8.44771525,14 9,14 Z M15,14 C15.5522847,14 16,13.5522847 16,13 C16,12.4477153 15.5522847,12 15,12 C14.4477153,12 14,12.4477153 14,13 C14,13.5522847 14.4477153,14 15,14 Z M6,18.9876876 L5,16 C5,16 5.07242747,15.2283988 5.5,15.5 C6.43069361,16.0911921 8.57396448,17 12,17 C15.5536669,17 17.6181635,16.0844828 18.5,15.5 C18.8589052,15.262117 19,16 19,16 L18,18.9876876 C18,18.9876876 17.0049249,20.9999997 12,21 C6.99507512,21.0000003 6,18.9876876 6,18.9876876 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Robot'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/components/Checkbox/Checkbox.js
titon/toolkit
/** * @copyright 2010-2017, The Titon Project * @license http://opensource.org/licenses/BSD-3-Clause * @link http://titon.io * @flow */ import React from 'react'; import Input from '../Input/Input'; import combineClasses from '../Input/combineClasses'; import formatID from '../../utility/formatID'; import formatInputName from '../../utility/formatInputName'; import style from '../../styler'; import { inputDefaults, inputPropTypes } from '../../propTypes'; import type { CheckboxState } from './types'; import type { InputProps, ChangedData } from '../Input/types'; export class ToolkitCheckbox extends React.Component { props: InputProps; state: CheckboxState; static propTypes = { ...inputPropTypes, }; static defaultProps = { ...inputDefaults, }; state: CheckboxState = { checked: false, }; handleOnChanged = (data: ChangedData) => { this.setState({ checked: data.checked, }); this.props.onChanged(data); }; render() { const { children, ...props } = this.props; const state = this.state; const id = props.id || formatInputName(props.name); return ( <span id={formatID('checkbox', id)} className={combineClasses('checkbox', props, state)} aria-checked={state.checked} aria-disabled={props.disabled} > <Input {...props} id={id} type="checkbox" native={false} onChanged={this.handleOnChanged} /> <label htmlFor={id} className={props.classNames.checkbox_toggle} /> {children} </span> ); } } export default style({ checkbox: 'checkbox', checkbox_toggle: 'checkbox__toggle', checkbox__checked: 'is-checked', checkbox__disabled: 'is-disabled', checkbox__invalid: 'is-invalid', checkbox__multiple: 'is-multiple', checkbox__readOnly: 'is-read-only', checkbox__required: 'is-required', })(ToolkitCheckbox);
react-lessons/src/App.js
anderson-amorim/egghead-react
import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; class App extends React.Component { constructor() { super(); this.state = { txt: 'This is a State TXT' } } update(e) { this.setState({ txt: e.target.value }); } render() { return ( <div> <Title txt="Song of Silence" /> <hr /> <h2>Hello darkness my old friend!</h2> <p>Prop.txt: {this.props.txt}</p> <p>Prop.cat: {this.props.cat}</p> <p>State.txt: <Widget update={this.update.bind(this)} />{this.state.txt}</p> <hr /> <p><Button>I <Heart /> React</Button></p> <hr /> <TextArea /> <hr /> <MyInput /> <hr /> <Wrapper /> </div> ) } } App.propTypes = { txt: PropTypes.string, cat: PropTypes.number.isRequired } App.defaultProps = { txt: "Hello mate, i'm here!" } const Widget = (props) => <input type="text" onChange={props.update}></input>; const Button = (props) => <button>{props.children}</button>; class Heart extends React.Component { render() { return <span>&hearts;</span>; } } const Title = (props) => <h1>{props.txt}</h1>; Title.propTypes = { txt(props, propName, component) { if (!(propName in props)) { return new Error(`Missing ${propName} faggot!`); } if (props[propName].length < 6) { return new Error(`${propName} was too short... faggot!`); } } } class TextArea extends React.Component { constructor() { super(); this.state = { currentEvent: '------' }; this.update = this.update.bind(this); } update(e) { this.setState({ currentEvent: e.type }); } render() { return ( <div> <textArea cols="30" rows="10" onKeyPress={this.update} onCopy={this.update} onCut={this.update} onPaste={this.update} onFocus={this.update} onBlur={this.update} onDoubleClick={this.update} onTouchStart={this.update} onTouchMove={this.update} onTouchEnd={this.update} /> <h1>{this.state.currentEvent}</h1> </div> ); } } class MyInput extends React.Component { constructor() { super(); this.state = { a: '' } } update() { this.setState({ a: this.a.refs.input.value, b: this.refs.b.value }); } render() { return ( <div> <MyInputJunior ref={component => this.a = component} update={this.update.bind(this)}></MyInputJunior> {this.state.a} <br /> <input ref="b" type="text" onChange={this.update.bind(this)}></input> {this.state.b} </div> ); } } class MyInputJunior extends React.Component { render() { return <div><input ref="input" type="text" onChange={this.props.update}></input></div>; } } class LifecicleTest extends React.Component { constructor() { super(); this.state = { val: 0 } this.update = this.update.bind(this); } update() { this.setState({ val: this.state.val + 1 }); } componentWillMount() { console.log('componentWillMount'); } render() { console.log('Render'); return <button onClick={this.update}>{this.state.val * this.state.m}</button>; } componentDidMount() { console.log('componentDidMount'); this.inc = setInterval(this.update, 1000); } componentWillUnmount() { console.log('componentWillUnmount'); clearInterval(this.inc); } } class Wrapper extends React.Component { mount() { ReactDOM.render(<LifecicleTest />, document.getElementById('a')); } unmount() { ReactDOM.unmountComponentAtNode(document.getElementById('a')); } render() { return ( <div> <button onClick={this.mount.bind(this)}>Mount</button> <button onClick={this.unmount.bind(this)}>UnMount</button> <div id="a"></div> </div> ); } } export default App;
client/src/components/Login.js
bwuphan/raptor-ads
import React, { Component } from 'react'; import { Button, Form, Grid, Header, Icon } from 'semantic-ui-react'; import { connect } from 'react-redux'; import { changeLoginField, loginUser } from '../actions'; class Login extends Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.login = this.login.bind(this); } handleChange(e) { const { dispatch } = this.props; dispatch(changeLoginField(e.target.name, e.target.value)); } login(e) { e.preventDefault(); const { dispatch, email, password } = this.props; dispatch(loginUser({ email, password })); } render() { const { email, password, formErrors } = this.props; return ( <div> <Header textAlign="center"><Icon name="user" />Log In</Header> <Grid width={16}> <Grid.Column width={5} /> <Grid.Column width={11}> {formErrors.invalidPass && <span className="formError">{formErrors.invalidPass}</span>} <Form> <Form.Field width="8"> <label htmlFor="email">Email</label> <input name="email" placeholder="Email" value={email} onChange={e => this.handleChange(e)} /> </Form.Field> <Form.Field width="8"> <label htmlFor="email">Password</label> <input name="password" type="password" placeholder="Password" value={password} onChange={e => this.handleChange(e)} /> </Form.Field> <Form.Field width="8"> <Button type="submit" onClick={e => this.login(e)} > Login </Button> </Form.Field> </Form> </Grid.Column> </Grid> </div> ); } } Login.propTypes = { dispatch: React.PropTypes.func.isRequired, email: React.PropTypes.string.isRequired, password: React.PropTypes.string.isRequired, }; const mapStateToProps = (state) => { const { email, password } = state.auth.loginForm; const { formErrors } = state.auth; return { email, password, formErrors }; }; export default connect(mapStateToProps)(Login);
src/components/Logo.js
TarlyFM/tarlyfm_front
import React from 'react'; import { Image } from 'semantic-ui-react'; const Logo = () => ( <Image src='/logo.png' /> ) export default Logo;
app/routes/routes/Booking/components/Booking.view.js
bugknightyyp/leyizhu
import React from 'react' import {observer} from 'mobx-react' import {Route, Link, NavLink} from 'react-router-dom' import {IMAGE_DIR, TEST_IMAGE, GET_HOTEL_INFO, RESPONSE_CODE_SUCCESS} from 'macros' import {dateToZh} from 'utils' import './booking.less' export default observer( (props) => { let persons = [] for (let i = 0; i < props.store.payNum; i++) {//props.store.checkIns let checkIn = i < props.store.checkIns.length? props.store.checkIns[i] : {} persons.push( <Link to={`${props.match.url}/person/${i}`} key={i}> <span className="label">{`入住人(房间${i + 1})`}</span> <span className="input certificate"> <span placeholder="请选择入住人">{checkIn.name || '请选择入住人'}</span> <i>{checkIn.paperworkNum}</i> </span> <i className="iconfont icon-indent_icon_show1" /> </Link> ) } return ( <div className="layout-up-down"> <div className="booking-container"> <ul className="hotle-info"> <li className="hotle-name">{props.store.hotelName}</li> <li className="hotle-type"><span>{props.store.roomType.roomType}</span><span>{props.store.roomType.price}元/晚</span></li> </ul> <div className="check-in-time"> <Link className="check-in" to={`${props.match.url}/select-date`}> <span>入住</span> <p>{dateToZh(props.store.checkInDate)}</p> </Link> <Link className="check-out" to={`${props.match.url}/select-date`}> <span>退房</span> <p>{dateToZh(props.store.checkOutDate)}</p> </Link> </div> <div className="user-container"> <Link to={`${props.match.url}/select-room-num`} className="item-info"><span className="label">房间数量</span><span className="input">{`${props.store.payNum}间`}</span><i className="iconfont icon-indent_icon_show1" /></Link> <div className="user-wraper"> <div className="user-info"> {persons} </div> <Link to={`${props.match.url}/persons`} className="btn-add-person-input"><i className="iconfont icon-indent_icon_add_people1" /></Link> </div> <div className="item-info"> <span className="label">联系人电话</span> <input className="input" placeholder="请输入联系人电话号码" value={props.store.phone} onChange={(e) => { return props.store.phone = e.target.value.replace('[^\d]', '').substring(0, 11); }} /> <i /> </div> </div> <div className="friends">&nbsp;</div> <div className="bill"> <div className="need-bill"> <span className="label">发票</span> <div className="radio-group btn-need-invoice" data-type={0}><i className={props.store.invoiceType == 0? "iconfont icon-indent_icon_choose" : "iconfont icon-xuanze1"}/><span>不需要</span></div> <Link to={`${props.match.url}/type-in-invoice`} className="radio-group btn-need-invoice" data-type={1}><i className={props.store.invoiceType != 0? "iconfont icon-indent_icon_choose" : "iconfont icon-xuanze1"}/><span>需要</span></Link> { // <div className="radio-group btn-need-invoice" data-type={1}><i className={props.store.invoiceType != 0? "iconfont icon-indent_icon_choose" : "iconfont icon-xuanze1"}/><span>需要</span></div> } </div> { props.store.invoiceType == 0? '' : <div className="bill-info"> <span className="label">发票详情</span> <p className="bill-content">{ props.store.invoiceInfo.address? props.store.invoiceType == 1? `电子发表:发送到${props.store.invoiceInfo.address}` : `深圳市乐易住科技有限公司纸质发票预计10个工作日送达${props.store.invoiceInfo.address}` : '请填写发票信息'}</p> <Link to={`${props.match.url}/type-in-invoice`} ><i className="iconfont icon-indent_icon_show1" /></Link> </div> } </div> </div> <div className="book-foot-stack"> <div className="amount"> <p className="actual-payment"><span>总额</span><span>{props.store.priceInfo.actualPayment || 0}</span><span>元</span></p> <p className="deposit-sum"><span>含押金</span><span>{props.store.priceInfo.depositSum || 0}</span><span>元</span></p> </div> <div className="price-detial"> <NavLink to={`${props.match.url}/price-detial`}> <div className="describe"> <i className="iconfont icon-indent_icon_down1" /> <span>明细</span> </div> </NavLink> <div className="btn-close-price-panel" /> </div> <div className="btn-paying"><span>立即支付</span></div> </div> </div> ) } )
node_modules/react-bootstrap/es/Tooltip.js
okristian1/react-info
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import isRequiredForA11y from 'react-prop-types/lib/isRequiredForA11y'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string|number} * @required */ id: isRequiredForA11y(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number])), /** * Sets the direction the Tooltip is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Tooltip. */ positionTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Tooltip. */ positionLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "top" position value for the Tooltip arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Tooltip arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]) }; var defaultProps = { placement: 'right' }; var Tooltip = function (_React$Component) { _inherits(Tooltip, _React$Component); function Tooltip() { _classCallCheck(this, Tooltip); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Tooltip.prototype.render = function render() { var _extends2; var _props = this.props, placement = _props.placement, positionTop = _props.positionTop, positionLeft = _props.positionLeft, arrowOffsetTop = _props.arrowOffsetTop, arrowOffsetLeft = _props.arrowOffsetLeft, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = _extends({ top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return React.createElement( 'div', _extends({}, elementProps, { role: 'tooltip', className: classNames(className, classes), style: outerStyle }), React.createElement('div', { className: prefix(bsProps, 'arrow'), style: arrowStyle }), React.createElement( 'div', { className: prefix(bsProps, 'inner') }, children ) ); }; return Tooltip; }(React.Component); Tooltip.propTypes = propTypes; Tooltip.defaultProps = defaultProps; export default bsClass('tooltip', Tooltip);
src/encoded/static/components/lib/matrix-viz/Matrix.js
4dn-dcic/fourfront
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { extend } from 'underscore'; import { matrixStyle, cellStyle } from './Styles.js'; import { randomData } from './Util.js'; import Column from './Column.js'; import Cell from './Cell.js'; export default class Matrix extends Component { getCellStyle(data) { var { setStyle, setHoverStyle } = this.props; var style = extend({}, cellStyle); if(setStyle) style = extend(style, setStyle(data)); if(setHoverStyle) style = extend(style, {':hover': setHoverStyle(data)}); return style; } generateCells(data) { var { setData, cellClass, tooltipDataFor, onClick, onMouseOver, onMouseOut} = this.props; return data.map((col, i) => col.map((cell, j) => { var curData = setData(cell, i, j) // Using i and j to denote col and row respectively var style = this.getCellStyle(curData); return (<Cell key={`col${i}row${j}`} className={cellClass} data={curData} style={style} tooltipDataFor={tooltipDataFor} onClick={onClick} onMouseOver={onMouseOver} onMouseOut={onMouseOut} />); })); } render() { var { columnClass, matrixClass, data, random } = this.props; // If data exists, use it. Otherwise, use our random prop. var cells = this.generateCells((data || randomData(random[0], random[1]))); return ( <div className={matrixClass} style={matrixStyle}> {cells.map((col, i) => <Column key={`col${i}`} className={columnClass} cells={col} />)} </div> ); } } Matrix.propTypes = { data: PropTypes.array, // A 2d array of values or objects setData: PropTypes.func, // A function that determines what the cell's value will be setStyle: PropTypes.func, // A function that determines the cell's style setHoverStyle: PropTypes.func, // A function that determines the cell's style onClick: PropTypes.func, // An event handler, triggered when cell is clicked onMouseOver: PropTypes.func, // An event handler, triggered when mouse enters cell onMouseOut: PropTypes.func, // An event handler, triggered when mouse exits cell, random: PropTypes.array, // [10, 5] would result in a 10 column, 5 row grid with random values between 1-100 cellClass: PropTypes.string, columnClass: PropTypes.string, matrixClass: PropTypes.string, }; Matrix.defaultProps = { setData: (cell, col, row) => cell, // Returns the value at data[col][row] cellClass: 'rm-cell', // Default cell class name to 'rm-cell' columnClass: 'rm-column', // Default column class name to 'rm-column' matrixClass: 'rm-matrix', // Default matrix class name to 'rm-matrix' };
app/components/Prodimg/index.js
Rohitbels/KolheshwariIndustries
/** * * Prodimg * */ import React from 'react'; import {Col,Thumbnail} from 'react-bootstrap'; class Prodimg extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <Col md={2}> <Thumbnail src={this.props.path} alt="242x200"/> </Col> ); } } export default Prodimg;
src/components/Toggle/Toggle.Skeleton.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 React from 'react'; import { settings } from 'carbon-components'; const { prefix } = settings; export default class ToggleSkeleton extends React.Component { render() { const { id } = this.props; return ( <div className={`${prefix}--form-item`}> <input type="checkbox" id={id} className={`${prefix}--toggle ${prefix}--skeleton`} /> <label className={`${prefix}--toggle__label ${prefix}--skeleton`} htmlFor={id}> <span className={`${prefix}--toggle__text--left`} /> <span className={`${prefix}--toggle__appearance`} /> <span className={`${prefix}--toggle__text--right`} /> </label> </div> ); } }
src/component/ChatRoom.js
im-js/im.js
/** * <plusmancn@gmail.com> created at 2017 * * Copyright (c) 2017 plusmancn, all rights * reserved. * * @flow * 聊天室 * * TODO: 聊天室有两次渲染问题 */ import { observer } from 'mobx-react/native'; import uuid from 'uuid'; import React, { Component } from 'react'; import { KeyboardAvoidingView, RefreshControl, StyleSheet, ListView, Image, Text, TextInput, Platform, View } from 'react-native'; import { FontSize, Color, Button } from '../../UiLibrary'; import { socketStore, profileStore } from '../storeSingleton.js'; @observer class ChatRoom extends Component { // 接收者 ID toInfo: Object; firstEnter: number; ds: Object; rows: Object[]; state: Object; currentMaxRowId: number = 0; chatListView: Object; // 判断用户是否输入过 _userHasBeenInputed: boolean = false; _userAtPage = 0; _userReachEnd = true; constructor(props: Object) { super(props); this.toInfo = props.toInfo; this.firstEnter = 0; this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => { return r1.uuid !== r2.uuid; } }); this.state = { textInputHeight: 40, inputValue: '', refreshing: false }; } componentWillUnmount() { socketStore.clearUnReadMessageCount(socketStore.currentChatKey); socketStore.currentChatKey = null; } // 不要和动画效果抢系统资源 componentDidMount() { socketStore.currentChatKey = `${profileStore.userInfo.userId}-${this.toInfo.userId}`; socketStore.fillCurrentChatRoomHistory(); } _scrollToBottom () { let scrollProperties = this.chatListView.scrollProperties; // 如果组件没有挂载完全,则不进行内容偏移 if (!scrollProperties.visibleLength) { return; } // 如果是刷新操作,则不进行滑动 if (!this._userReachEnd) { return; } // 如果组件内元素还没渲染完全,则不进行底部偏移 if (socketStore.currentChatRoomHistory.length - this.currentMaxRowId > 11) { return; } // 这里是一个大坑,在测试环境的时候,由于运行速度较慢,scrollProperties.contentLength 总能 // 获取到正确的值,生产环境需要加个延时,用来保证 `renderRow` 执行完毕 // 这里设置了 130ms 的延时 setTimeout(() => { let offsetY = scrollProperties.contentLength - scrollProperties.visibleLength; this.chatListView.scrollTo({ y: offsetY > 0 ? offsetY : 0, animated: this._userHasBeenInputed }); }, this._userHasBeenInputed ? 0 : 130); } _onSubmitEditing = () => { this._userHasBeenInputed = true; // 数据组装 let { userInfo } = profileStore; let payload = { from: userInfo.userId, to: this.toInfo.userId, uuid: uuid.v4(), msg: { type: 'txt', content: this.state.inputValue }, ext: { avatar: userInfo.avatar, name: userInfo.name } }; this.setState({ inputValue: '' }); // 远程发送 socketStore.socket.emit('message', [payload]); // 本地会话列表更新 socketStore.pushLocalePayload(Object.assign({ localeExt: { toInfo: this.toInfo } }, payload)); } _renderRow = (row, sectionID, rowId) => { this.currentMaxRowId = +rowId; return ( <MessageCell key={`cell-${rowId}`} currentUser={profileStore.userInfo.userId} message={row} /> ); } _onPullMessage = async () => { this._userReachEnd = false; this.setState({ refreshing: true }); // 历史消息推入 await socketStore.fillCurrentChatRoomHistory(++this._userAtPage, 8); this.setState({ refreshing: false }); } render() { let content = ( <View style={styles.container} > <ListView refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onPullMessage} /> } onEndReached={() => { this._userReachEnd = true; }} onEndReachedThreshold={10} ref={(reference) => { this.chatListView = reference; }} dataSource={this.ds.cloneWithRows(socketStore.currentChatRoomHistory.slice())} enableEmptySections={true} onLayout={ (event) => { this._scrollToBottom(); } } onContentSizeChange={ (event) => { this._scrollToBottom(); } } renderRow={this._renderRow} /> <View style={styles.bottomToolBar} > <TextInput style={[styles.input, { height: Math.max(40, this.state.textInputHeight < 180 ? this.state.textInputHeight : 180 ) }]} multiline={true} controlled={true} underlineColorAndroid="transparent" returnKeyType="default" value={this.state.inputValue} placeholder="Type here to send message" // ios only enablesReturnKeyAutomatically={true} onContentSizeChange={ (event) => { this.setState({textInputHeight: event.nativeEvent.contentSize.height}); } } onChangeText={ (text) => { this.setState({ inputValue: text }); }} /> <Button style={styles.sendButton} textStyle={styles.sendButtonText} disabled={!this.state.inputValue} onPress={this._onSubmitEditing} > 发送 </Button> </View> </View> ); if (Platform.OS === 'ios') { return ( <KeyboardAvoidingView behavior="padding" style={styles.KeyboardAvoidingView} keyboardVerticalOffset={this.props.keyboardVerticalOffset || 64} > {content} </KeyboardAvoidingView> ); } else { return content; } } } class MessageCell extends Component { render() { let { currentUser, message } = this.props; let differentStyle = {}; if (message.from === currentUser) { differentStyle = { flexDirection: 'row-reverse', backgroundColor: '#92E649' }; } else { differentStyle = { flexDirection: 'row', backgroundColor: '#FFFFFF' }; } return ( <View style={[styles.messageCell, {flexDirection: differentStyle.flexDirection}]} > <Image source={{ uri: message.ext.avatar }} style={styles.avatar} /> <View style={[styles.contentView, {backgroundColor: differentStyle.backgroundColor}]} > <Text style={styles.messageCellText}>{message.msg.content}</Text> </View> <View style={styles.endBlankBlock} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'flex-start', alignItems: 'stretch', backgroundColor: Color.BackgroundGrey }, KeyboardAvoidingView: { flex: 1 }, bottomToolBar: { flexDirection: 'row', alignItems: 'center', borderTopWidth: 1, borderTopColor: Color.LittleGrey }, sendButton: { marginHorizontal: 10, backgroundColor: Color.WechatGreen, borderColor: Color.WechatGreen }, sendButtonText: { color: Color.White }, input: { flex: 1, color: Color.Black, fontSize: FontSize.Main, padding: 10 }, messageCell: { marginTop: 5, marginBottom: 5, }, messageCellText: { fontSize: FontSize.Content }, avatar: { borderRadius: 4, margin: 5, width: 40, height: 40 }, contentView: { borderRadius: 4, padding: 4, paddingHorizontal: 8, overflow: 'hidden', flex: 1, margin: 5, justifyContent: 'center' }, endBlankBlock: { margin: 5, width: 50, height: 40 } }); export default ChatRoom;
client/src/app/routes/dashboard/containers/Dashboard.js
zraees/sms-project
/** * Created by griga on 11/30/15. */ import React from 'react' import WidgetGrid from '../../../components/widgets/WidgetGrid' import Stats from '../../../components/common/Stats' import BigBreadcrumbs from '../../../components/navigation/components/BigBreadcrumbs' import BirdEyeWidget from '../components/BirdEyeWidget' import LiveFeeds from '../components/LiveFeeds' import ChatWidget from '../../../components/chat/components/ChatWidget' import FullCalendarWidget from '../../../components/calendar/components/FullCalendarWidget' import TodoWidget from '../../../components/todo/components/TodoWidget' export default class Dashboard extends React.Component { render() { return ( <div id="content"> <div className="row"> <BigBreadcrumbs items={['Dashboard', 'My Dashboard']} className="col-xs-12 col-sm-7 col-md-7 col-lg-4"/> <Stats /> </div> <WidgetGrid> <div className="row"> <article className="col-sm-12"> <LiveFeeds /> </article> </div> <div className="row"> <article className="col-sm-12 col-md-12 col-lg-6"> <ChatWidget /> <FullCalendarWidget /> </article> <article className="col-sm-12 col-md-12 col-lg-6"> <BirdEyeWidget /> <TodoWidget /> </article> </div> </WidgetGrid> </div> ) } }
client/components/FlassCommon/Video/VideoButton/VideoButtonComponent.js
Nexters/flass
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import './VideoButtonStyle.scss'; const { func, string, number, oneOfType, arrayOf } = PropTypes; const propTypes = { onButtonClick: func.isRequired, onButtonMouseOver: func, onButtonMouseLeave: func, buttonClass: oneOfType([string, arrayOf(string)]), value: oneOfType([ string, number ]), srcSet: string }; const defaultProps = { onButtonMouseOver: null, onButtonMouseLeave: null, buttonTitle: '', buttonClass: '', value: '', srcSet: null }; const VideoButtonComponent = props => { const { onButtonClick, onButtonMouseOver, onButtonMouseLeave, buttonClass, value, srcSet } = props; return ( <button className={ classNames(buttonClass) } onClick={ onButtonClick } onMouseOver={ onButtonMouseOver } onMouseLeave={ onButtonMouseLeave } value={ value }> <img srcSet={ `${srcSet}` } className="video-btn__icon" alt="Video controller button" /> </button> ); }; VideoButtonComponent.propTypes = propTypes; VideoButtonComponent.defaultProps = defaultProps; export { VideoButtonComponent };
src/components/slider/Slider.js
casesandberg/react-color
import React from 'react' import PropTypes from 'prop-types' import reactCSS from 'reactcss' import merge from 'lodash/merge' import { ColorWrap, Hue } from '../common' import SliderSwatches from './SliderSwatches' import SliderPointer from './SliderPointer' export const Slider = ({ hsl, onChange, pointer, styles: passedStyles = {}, className = '' }) => { const styles = reactCSS(merge({ 'default': { hue: { height: '12px', position: 'relative', }, Hue: { radius: '2px', }, }, }, passedStyles)) return ( <div style={ styles.wrap || {} } className={ `slider-picker ${ className }` }> <div style={ styles.hue }> <Hue style={ styles.Hue } hsl={ hsl } pointer={ pointer } onChange={ onChange } /> </div> <div style={ styles.swatches }> <SliderSwatches hsl={ hsl } onClick={ onChange } /> </div> </div> ) } Slider.propTypes = { styles: PropTypes.object, } Slider.defaultProps = { pointer: SliderPointer, styles: {}, } export default ColorWrap(Slider)
es/Paper/Paper.js
uplevel-technology/material-ui-next
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import classNames from 'classnames'; import warning from 'warning'; import withStyles from '../styles/withStyles'; export const styles = theme => { const shadows = {}; theme.shadows.forEach((shadow, index) => { shadows[`shadow${index}`] = { boxShadow: shadow }; }); return _extends({ root: { backgroundColor: theme.palette.background.paper }, rounded: { borderRadius: 2 } }, shadows); }; class Paper extends React.Component { render() { const _props = this.props, { classes, className: classNameProp, component: ComponentProp, square, elevation } = _props, other = _objectWithoutProperties(_props, ['classes', 'className', 'component', 'square', 'elevation']); warning(elevation >= 0 && elevation < 25, `Material-UI: this elevation \`${elevation}\` is not implemented.`); const className = classNames(classes.root, classes[`shadow${elevation >= 0 ? elevation : 0}`], { [classes.rounded]: !square }, classNameProp); return React.createElement(ComponentProp, _extends({ className: className }, other)); } } Paper.defaultProps = { component: 'div', elevation: 2, square: false }; export default withStyles(styles, { name: 'MuiPaper' })(Paper);
app/javascript/mastodon/features/public_timeline/index.js
tootsuite/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { expandPublicTimeline } from '../../actions/timelines'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import ColumnSettingsContainer from './containers/column_settings_container'; import { connectPublicStream } from '../../actions/streaming'; const messages = defineMessages({ title: { id: 'column.public', defaultMessage: 'Federated timeline' }, }); const mapStateToProps = (state, { columnId }) => { const uuid = columnId; const columns = state.getIn(['settings', 'columns']); const index = columns.findIndex(c => c.get('uuid') === uuid); const onlyMedia = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyMedia']) : state.getIn(['settings', 'public', 'other', 'onlyMedia']); const onlyRemote = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyRemote']) : state.getIn(['settings', 'public', 'other', 'onlyRemote']); const timelineState = state.getIn(['timelines', `public${onlyMedia ? ':media' : ''}`]); return { hasUnread: !!timelineState && timelineState.get('unread') > 0, onlyMedia, onlyRemote, }; }; export default @connect(mapStateToProps) @injectIntl class PublicTimeline extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static defaultProps = { onlyMedia: false, }; static propTypes = { dispatch: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, columnId: PropTypes.string, multiColumn: PropTypes.bool, hasUnread: PropTypes.bool, onlyMedia: PropTypes.bool, onlyRemote: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch, onlyMedia, onlyRemote } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn(onlyRemote ? 'REMOTE' : 'PUBLIC', { other: { onlyMedia, onlyRemote } })); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } componentDidMount () { const { dispatch, onlyMedia, onlyRemote } = this.props; dispatch(expandPublicTimeline({ onlyMedia, onlyRemote })); this.disconnect = dispatch(connectPublicStream({ onlyMedia, onlyRemote })); } componentDidUpdate (prevProps) { if (prevProps.onlyMedia !== this.props.onlyMedia || prevProps.onlyRemote !== this.props.onlyRemote) { const { dispatch, onlyMedia, onlyRemote } = this.props; this.disconnect(); dispatch(expandPublicTimeline({ onlyMedia, onlyRemote })); this.disconnect = dispatch(connectPublicStream({ onlyMedia, onlyRemote })); } } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } setRef = c => { this.column = c; } handleLoadMore = maxId => { const { dispatch, onlyMedia, onlyRemote } = this.props; dispatch(expandPublicTimeline({ maxId, onlyMedia, onlyRemote })); } render () { const { intl, columnId, hasUnread, multiColumn, onlyMedia, onlyRemote } = this.props; const pinned = !!columnId; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='globe' active={hasUnread} title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} > <ColumnSettingsContainer columnId={columnId} /> </ColumnHeader> <StatusListContainer timelineId={`public${onlyRemote ? ':remote' : ''}${onlyMedia ? ':media' : ''}`} onLoadMore={this.handleLoadMore} trackScroll={!pinned} scrollKey={`public_timeline-${columnId}`} emptyMessage={<FormattedMessage id='empty_column.public' defaultMessage='There is nothing here! Write something publicly, or manually follow users from other servers to fill it up' />} bindToDocument={!multiColumn} /> </Column> ); } }
frontend/src/components/public_group/PublicGroupJoinUs.js
carlosascari/opencollective-website
import React from 'react'; import AmountPicker from '../../components/public_group/AmountPicker'; export default class PublicGroupJoinUs extends React.Component { _showTier(tier, index) { const { donateToGroup, i18n } = this.props; return ( <div className='md-col-6 col-12 px3 pb4 mb4 border-box flex' key={`${tier.name}_${index}`}> <div className='PublicGroupJoinUs-tier-box-inner -border-green border mt3 relative col-12'> <h3 className='PublicGroupJoinUs-tier-box-title h3 mt0'> <span className='bg-light-gray px2 -fw-ultra-bold'>{i18n.getString('becomeA')} {tier.name}</span> </h3> <p className='PublicGroupJoinUs-tier-box-description h5 mt0 mb3 px3 flex justify-center items-center'> {tier.description} </p> <AmountPicker tier={tier} onToken={donateToGroup.bind(this)} {...this.props}/> </div> </div> ); } render() { const { group, i18n } = this.props; return ( <section id='join-us'> <div id='support'></div> <div className='PublicGroupJoin-container container center'> <h2 className='PublicGroup-title m0 pb2 -ff-sec -fw-bold'>{i18n.getString('joinAndFulfil')}</h2> <p className='PublicGroup-font-17 m0 pb2'>{i18n.getString('helpUsContinueOurActivities')}</p> <div className='flex flex-wrap justify-center clearfix max-width-4 mx-auto pt3'> {group.tiers.map(::this._showTier)} </div> </div> </section> ); } };
node/node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
onezens/HtmlCSSJavaScriptPractiseRepo
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
src/svg-icons/editor/border-style.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderStyle = (props) => ( <SvgIcon {...props}> <path d="M15 21h2v-2h-2v2zm4 0h2v-2h-2v2zM7 21h2v-2H7v2zm4 0h2v-2h-2v2zm8-4h2v-2h-2v2zm0-4h2v-2h-2v2zM3 3v18h2V5h16V3H3zm16 6h2V7h-2v2z"/> </SvgIcon> ); EditorBorderStyle = pure(EditorBorderStyle); EditorBorderStyle.displayName = 'EditorBorderStyle'; EditorBorderStyle.muiName = 'SvgIcon'; export default EditorBorderStyle;
src/svg-icons/image/filter-6.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter6 = (props) => ( <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zm-8-2h2c1.1 0 2-.89 2-2v-2c0-1.11-.9-2-2-2h-2V7h4V5h-4c-1.1 0-2 .89-2 2v6c0 1.11.9 2 2 2zm0-4h2v2h-2v-2z"/> </SvgIcon> ); ImageFilter6 = pure(ImageFilter6); ImageFilter6.displayName = 'ImageFilter6'; ImageFilter6.muiName = 'SvgIcon'; export default ImageFilter6;
src/i18n.js
HsuTing/cat-components
'use strict'; import 'fetch-everywhere'; import React from 'react'; import PropTypes from 'prop-types'; export const language = Component => class extends React.Component { // eslint-disable-line react/display-name static contextTypes = { translate: PropTypes.object.isRequired, changeLanguage: PropTypes.func.isRequired } render() { return ( <Component {...this.state} {...this.props} {...this.context} /> ); } }; export default class I18n extends React.Component { static propTypes = { lang: PropTypes.string.isRequired, defaultData: PropTypes.object.isRequired, basename: PropTypes.string, children: PropTypes.element.isRequired } static defaultProps = { basename: '/public/i18n/' } static childContextTypes = { translate: PropTypes.object.isRequired, changeLanguage: PropTypes.func.isRequired }; constructor(props) { super(props); const {lang, basename, defaultData} = props; const state = { lang, basename }; state[lang] = defaultData; this.state = state; this.changeLanguage = this.changeLanguage.bind(this); } getChildContext() { const {lang, ...data} = this.state; return { translate: data[lang], changeLanguage: this.changeLanguage }; } render() { const {children} = this.props; return React.Children.only(children); } changeLanguage(lang) { return () => { const {basename, ...data} = this.state; if(data[lang]) { this.setState({lang}); return; } /* istanbul ignore next */ fetch(`${basename.slice(-1) === '/' ? basename : `${basename}/`}${lang}.json`) .then(response => response.json()) .then(languageData => { data[lang] = languageData; this.setState({ ...data, lang }); }) .catch(e => console.log('parsing failed', e)); }; } }
docs/src/app/components/pages/components/Popover/ExampleConfigurable.js
hai-cea/material-ui
import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import RadioButton from 'material-ui/RadioButton'; import Popover from 'material-ui/Popover/Popover'; import {Menu, MenuItem} from 'material-ui/Menu'; const styles = { h3: { marginTop: 20, fontWeight: 400, }, block: { display: 'flex', }, block2: { margin: 10, }, pre: { overflow: 'hidden', // Fix a scrolling issue on iOS. }, }; export default class PopoverExampleConfigurable extends React.Component { constructor(props) { super(props); this.state = { open: false, anchorOrigin: { horizontal: 'left', vertical: 'bottom', }, targetOrigin: { horizontal: 'left', vertical: 'top', }, }; } handleClick = (event) => { // This prevents ghost click. event.preventDefault(); this.setState({ open: true, anchorEl: event.currentTarget, }); }; handleRequestClose = () => { this.setState({ open: false, }); }; setAnchor = (positionElement, position) => { const {anchorOrigin} = this.state; anchorOrigin[positionElement] = position; this.setState({ anchorOrigin: anchorOrigin, }); }; setTarget = (positionElement, position) => { const {targetOrigin} = this.state; targetOrigin[positionElement] = position; this.setState({ targetOrigin: targetOrigin, }); }; render() { return ( <div> <RaisedButton onClick={this.handleClick} label="Click me" /> <h3 style={styles.h3}>Current Settings</h3> <pre style={styles.pre}> anchorOrigin: {JSON.stringify(this.state.anchorOrigin)} <br /> targetOrigin: {JSON.stringify(this.state.targetOrigin)} </pre> <h3 style={styles.h3}>Position Options</h3> <p>Use the settings below to toggle the positioning of the popovers above</p> <h3 style={styles.h3}>Anchor Origin</h3> <div style={styles.block}> <div style={styles.block2}> <span>Vertical</span> <RadioButton onClick={this.setAnchor.bind(this, 'vertical', 'top')} label="Top" checked={this.state.anchorOrigin.vertical === 'top'} /> <RadioButton onClick={this.setAnchor.bind(this, 'vertical', 'center')} label="Center" checked={this.state.anchorOrigin.vertical === 'center'} /> <RadioButton onClick={this.setAnchor.bind(this, 'vertical', 'bottom')} label="Bottom" checked={this.state.anchorOrigin.vertical === 'bottom'} /> </div> <div style={styles.block2}> <span>Horizontal</span> <RadioButton onClick={this.setAnchor.bind(this, 'horizontal', 'left')} label="Left" checked={this.state.anchorOrigin.horizontal === 'left'} /> <RadioButton onClick={this.setAnchor.bind(this, 'horizontal', 'middle')} label="Middle" checked={this.state.anchorOrigin.horizontal === 'middle'} /> <RadioButton onClick={this.setAnchor.bind(this, 'horizontal', 'right')} label="Right" checked={this.state.anchorOrigin.horizontal === 'right'} /> </div> </div> <h3 style={styles.h3}>Target Origin</h3> <div style={styles.block}> <div style={styles.block2}> <span>Vertical</span> <RadioButton onClick={this.setTarget.bind(this, 'vertical', 'top')} label="Top" checked={this.state.targetOrigin.vertical === 'top'} /> <RadioButton onClick={this.setTarget.bind(this, 'vertical', 'center')} label="Center" checked={this.state.targetOrigin.vertical === 'center'} /> <RadioButton onClick={this.setTarget.bind(this, 'vertical', 'bottom')} label="Bottom" checked={this.state.targetOrigin.vertical === 'bottom'} /> </div> <div style={styles.block2}> <span>Horizontal</span> <RadioButton onClick={this.setTarget.bind(this, 'horizontal', 'left')} label="Left" checked={this.state.targetOrigin.horizontal === 'left'} /> <RadioButton onClick={this.setTarget.bind(this, 'horizontal', 'middle')} label="Middle" checked={this.state.targetOrigin.horizontal === 'middle'} /> <RadioButton onClick={this.setTarget.bind(this, 'horizontal', 'right')} label="Right" checked={this.state.targetOrigin.horizontal === 'right'} /> </div> </div> <Popover open={this.state.open} anchorEl={this.state.anchorEl} anchorOrigin={this.state.anchorOrigin} targetOrigin={this.state.targetOrigin} onRequestClose={this.handleRequestClose} > <Menu> <MenuItem primaryText="Refresh" /> <MenuItem primaryText="Help &amp; feedback" /> <MenuItem primaryText="Settings" /> <MenuItem primaryText="Sign out" /> </Menu> </Popover> </div> ); } }
boilerplates/project/mobileWeb/src/components/PageNotFound/PageNotFound.js
FuluUE/vd-generator
import React from 'react'; import PropTypes from 'prop-types'; import Placeholder from '../Placeholder'; import './less/pageNotFound.less'; const PageNotFound = (props) => { return ( <Placeholder className='placeholder-404' slogan='蛇精出来捣乱啦! 快跑呀!!' extra={ <a href="/">返回首页</a> } /> ); }; export default PageNotFound;
app/javascript/mastodon/features/video/index.js
hugogameiro/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { fromJS } from 'immutable'; import { throttle } from 'lodash'; import classNames from 'classnames'; import { isFullscreen, requestFullscreen, exitFullscreen } from '../ui/util/fullscreen'; import { displayMedia } from '../../initial_state'; const messages = defineMessages({ play: { id: 'video.play', defaultMessage: 'Play' }, pause: { id: 'video.pause', defaultMessage: 'Pause' }, mute: { id: 'video.mute', defaultMessage: 'Mute sound' }, unmute: { id: 'video.unmute', defaultMessage: 'Unmute sound' }, hide: { id: 'video.hide', defaultMessage: 'Hide video' }, expand: { id: 'video.expand', defaultMessage: 'Expand video' }, close: { id: 'video.close', defaultMessage: 'Close video' }, fullscreen: { id: 'video.fullscreen', defaultMessage: 'Full screen' }, exit_fullscreen: { id: 'video.exit_fullscreen', defaultMessage: 'Exit full screen' }, }); const formatTime = secondsNum => { let hours = Math.floor(secondsNum / 3600); let minutes = Math.floor((secondsNum - (hours * 3600)) / 60); let seconds = secondsNum - (hours * 3600) - (minutes * 60); if (hours < 10) hours = '0' + hours; if (minutes < 10) minutes = '0' + minutes; if (seconds < 10) seconds = '0' + seconds; return (hours === '00' ? '' : `${hours}:`) + `${minutes}:${seconds}`; }; export const findElementPosition = el => { let box; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0, }; } const docEl = document.documentElement; const body = document.body; const clientLeft = docEl.clientLeft || body.clientLeft || 0; const scrollLeft = window.pageXOffset || body.scrollLeft; const left = (box.left + scrollLeft) - clientLeft; const clientTop = docEl.clientTop || body.clientTop || 0; const scrollTop = window.pageYOffset || body.scrollTop; const top = (box.top + scrollTop) - clientTop; return { left: Math.round(left), top: Math.round(top), }; }; export const getPointerPosition = (el, event) => { const position = {}; const box = findElementPosition(el); const boxW = el.offsetWidth; const boxH = el.offsetHeight; const boxY = box.top; const boxX = box.left; let pageY = event.pageY; let pageX = event.pageX; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; pageY = event.changedTouches[0].pageY; } position.y = Math.max(0, Math.min(1, (pageY - boxY) / boxH)); position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW)); return position; }; export default @injectIntl class Video extends React.PureComponent { static propTypes = { preview: PropTypes.string, src: PropTypes.string.isRequired, alt: PropTypes.string, width: PropTypes.number, height: PropTypes.number, sensitive: PropTypes.bool, startTime: PropTypes.number, onOpenVideo: PropTypes.func, onCloseVideo: PropTypes.func, detailed: PropTypes.bool, inline: PropTypes.bool, intl: PropTypes.object.isRequired, }; state = { currentTime: 0, duration: 0, paused: true, dragging: false, containerWidth: false, fullscreen: false, hovered: false, muted: false, revealed: displayMedia !== 'hide_all' && !this.props.sensitive || displayMedia === 'show_all', }; setPlayerRef = c => { this.player = c; if (c) { this.setState({ containerWidth: c.offsetWidth, }); } } setVideoRef = c => { this.video = c; } setSeekRef = c => { this.seek = c; } handleClickRoot = e => e.stopPropagation(); handlePlay = () => { this.setState({ paused: false }); } handlePause = () => { this.setState({ paused: true }); } handleTimeUpdate = () => { this.setState({ currentTime: Math.floor(this.video.currentTime), duration: Math.floor(this.video.duration), }); } handleMouseDown = e => { document.addEventListener('mousemove', this.handleMouseMove, true); document.addEventListener('mouseup', this.handleMouseUp, true); document.addEventListener('touchmove', this.handleMouseMove, true); document.addEventListener('touchend', this.handleMouseUp, true); this.setState({ dragging: true }); this.video.pause(); this.handleMouseMove(e); e.preventDefault(); e.stopPropagation(); } handleMouseUp = () => { document.removeEventListener('mousemove', this.handleMouseMove, true); document.removeEventListener('mouseup', this.handleMouseUp, true); document.removeEventListener('touchmove', this.handleMouseMove, true); document.removeEventListener('touchend', this.handleMouseUp, true); this.setState({ dragging: false }); this.video.play(); } handleMouseMove = throttle(e => { const { x } = getPointerPosition(this.seek, e); const currentTime = Math.floor(this.video.duration * x); if (!isNaN(currentTime)) { this.video.currentTime = currentTime; this.setState({ currentTime }); } }, 60); togglePlay = () => { if (this.state.paused) { this.video.play(); } else { this.video.pause(); } } toggleFullscreen = () => { if (isFullscreen()) { exitFullscreen(); } else { requestFullscreen(this.player); } } componentDidMount () { document.addEventListener('fullscreenchange', this.handleFullscreenChange, true); document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange, true); document.addEventListener('mozfullscreenchange', this.handleFullscreenChange, true); document.addEventListener('MSFullscreenChange', this.handleFullscreenChange, true); } componentWillUnmount () { document.removeEventListener('fullscreenchange', this.handleFullscreenChange, true); document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange, true); document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange, true); document.removeEventListener('MSFullscreenChange', this.handleFullscreenChange, true); } handleFullscreenChange = () => { this.setState({ fullscreen: isFullscreen() }); } handleMouseEnter = () => { this.setState({ hovered: true }); } handleMouseLeave = () => { this.setState({ hovered: false }); } toggleMute = () => { this.video.muted = !this.video.muted; this.setState({ muted: this.video.muted }); } toggleReveal = () => { if (this.state.revealed) { this.video.pause(); } this.setState({ revealed: !this.state.revealed }); } handleLoadedData = () => { if (this.props.startTime) { this.video.currentTime = this.props.startTime; this.video.play(); } } handleProgress = () => { if (this.video.buffered.length > 0) { this.setState({ buffer: this.video.buffered.end(0) / this.video.duration * 100 }); } } handleOpenVideo = () => { const { src, preview, width, height, alt } = this.props; const media = fromJS({ type: 'video', url: src, preview_url: preview, description: alt, width, height, }); this.video.pause(); this.props.onOpenVideo(media, this.video.currentTime); } handleCloseVideo = () => { this.video.pause(); this.props.onCloseVideo(); } render () { const { preview, src, inline, startTime, onOpenVideo, onCloseVideo, intl, alt, detailed, sensitive } = this.props; const { containerWidth, currentTime, duration, buffer, dragging, paused, fullscreen, hovered, muted, revealed } = this.state; const progress = (currentTime / duration) * 100; const playerStyle = {}; let { width, height } = this.props; if (inline && containerWidth) { width = containerWidth; height = containerWidth / (16/9); playerStyle.width = width; playerStyle.height = height; } let preload; if (startTime || fullscreen || dragging) { preload = 'auto'; } else if (detailed) { preload = 'metadata'; } else { preload = 'none'; } let warning; if (sensitive) { warning = <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' />; } else { warning = <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />; } return ( <div role='menuitem' className={classNames('video-player', { inactive: !revealed, detailed, inline: inline && !fullscreen, fullscreen })} style={playerStyle} ref={this.setPlayerRef} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} onClick={this.handleClickRoot} tabIndex={0} > <video ref={this.setVideoRef} src={src} poster={preview} preload={preload} loop role='button' tabIndex='0' aria-label={alt} title={alt} width={width} height={height} onClick={this.togglePlay} onPlay={this.handlePlay} onPause={this.handlePause} onTimeUpdate={this.handleTimeUpdate} onLoadedData={this.handleLoadedData} onProgress={this.handleProgress} /> <button type='button' className={classNames('video-player__spoiler', { active: !revealed })} onClick={this.toggleReveal}> <span className='video-player__spoiler__title'>{warning}</span> <span className='video-player__spoiler__subtitle'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span> </button> <div className={classNames('video-player__controls', { active: paused || hovered })}> <div className='video-player__seek' onMouseDown={this.handleMouseDown} ref={this.setSeekRef}> <div className='video-player__seek__buffer' style={{ width: `${buffer}%` }} /> <div className='video-player__seek__progress' style={{ width: `${progress}%` }} /> <span className={classNames('video-player__seek__handle', { active: dragging })} tabIndex='0' style={{ left: `${progress}%` }} /> </div> <div className='video-player__buttons-bar'> <div className='video-player__buttons left'> <button type='button' aria-label={intl.formatMessage(paused ? messages.play : messages.pause)} onClick={this.togglePlay}><i className={classNames('fa fa-fw', { 'fa-play': paused, 'fa-pause': !paused })} /></button> <button type='button' aria-label={intl.formatMessage(muted ? messages.unmute : messages.mute)} onClick={this.toggleMute}><i className={classNames('fa fa-fw', { 'fa-volume-off': muted, 'fa-volume-up': !muted })} /></button> {!onCloseVideo && <button type='button' aria-label={intl.formatMessage(messages.hide)} onClick={this.toggleReveal}><i className='fa fa-fw fa-eye' /></button>} {(detailed || fullscreen) && <span> <span className='video-player__time-current'>{formatTime(currentTime)}</span> <span className='video-player__time-sep'>/</span> <span className='video-player__time-total'>{formatTime(duration)}</span> </span> } </div> <div className='video-player__buttons right'> {(!fullscreen && onOpenVideo) && <button type='button' aria-label={intl.formatMessage(messages.expand)} onClick={this.handleOpenVideo}><i className='fa fa-fw fa-expand' /></button>} {onCloseVideo && <button type='button' aria-label={intl.formatMessage(messages.close)} onClick={this.handleCloseVideo}><i className='fa fa-fw fa-compress' /></button>} <button type='button' aria-label={intl.formatMessage(fullscreen ? messages.exit_fullscreen : messages.fullscreen)} onClick={this.toggleFullscreen}><i className={classNames('fa fa-fw', { 'fa-arrows-alt': !fullscreen, 'fa-compress': fullscreen })} /></button> </div> </div> </div> </div> ); } }
src/Container.js
ericyd/surfplotjs
/** * This component serves two purposes: * 1. Provide a container for the navigation and the routes served through the router * 2. Save the state of the Plotter component when it unmounts and send that state back to the Plotter * when it remounts. */ 'use strict'; import React, { Component } from 'react'; import Header from './header/Header'; export default class Container extends Component { constructor () { super(); this.state = {}; this.handlePlotterUnmount = this.handlePlotterUnmount.bind(this); } handlePlotterUnmount (state) { this.setState(state); } render () { const self = this; const children = React.Children.map(self.props.children, function (child) { return React.cloneElement(child, { initialState: self.state, handleUnmount: self.handlePlotterUnmount, page: child.props.route.page }); }); return ( <div> <Header /> {children} </div> ); } }
demo/BackEndApp/src/components/ProductList.js
JianmingXia/StudyTest
import React from 'react'; import PropTypes from 'prop-types'; import { Table, Popconfirm, Button } from 'antd'; const ProductList = ({ onDelete, products }) => { const columns = [{ title: 'Name', dataIndex: 'name', }, { title: 'Actions', render: (text, record) => { return ( <Popconfirm title="Delete?" onConfirm={() => onDelete(record.id)}> <Button>Delete</Button> </Popconfirm> ); }, }]; return ( <Table dataSource={products} columns={columns} /> ); }; ProductList.propTypes = { onDelete: PropTypes.func.isRequired, products: PropTypes.array.isRequired, }; export default ProductList;
application/components/ProjectTile.js
Kifial/CoinKeeper
import React from 'react' import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card' import FlatButton from 'material-ui/FlatButton' import moment from 'moment' import LinearProgress from 'material-ui/LinearProgress' export default props => ( <Card style={{ width: 'calc(50% - 40px)', margin: '20px' }}> <CardMedia style={{ width: '100%', height: '400px', background: 'url("http://www.euneighbours.eu/sites/default/files/2017-01/placeholder.png") no-repeat 50% 50%', backgroundSize: '100% 100%' }} onClick={() => props.goToProject(props._id)} /> <CardTitle title={props.name} subtitle={moment(props.createdDate).format('DD/MM/YYYY')} onClick={() => props.goToProject(props._id)} /> <CardText> {props.description} <div style={{ margin: '10px 0' }}> Money Collected: {props.amount}/{props.limit} </div> <LinearProgress mode="determinate" value={(props.amount / props.limit) * 100} /> </CardText> <CardActions> <FlatButton label="Donate" onClick={() => props.openTransactionModal(props._id)} /> <FlatButton label="Expand" onClick={() => props.goToProject(props._id)} /> </CardActions> </Card> )
public/js/components/DetailsIdentificationChronicPainB.js
Vabrins/CadernetaDoIdoso
import React from 'react'; import $ from 'jquery'; import { Link } from 'react-router-dom'; class DetailsIdentificationChronicPainB extends React.Component { constructor (props) { super(props); this.state = {date_2_10_b:'', place_of_pain_2_10_b:'', intensity_2_10_b:'', created_at:'', list : []}; } componentWillMount() { $.ajax({ url: "/api/v1/idenchronicpainsintensity", dataType: "json", method: "GET", success:function(response){ if (response != "") { this.buildData(response[0]); } }.bind(this) }); $.ajax({ url: "/api/v1/idenchronicpainsintensity/getTrashed", dataType: "json", method: "GET", success:function(response){ if (response != "") { this.setState({list:response}); } }.bind(this) }); } buildData(data) { if (data.date_2_10_b != null) { this.setState({date_2_10_b: data.date_2_10_b}); } if (data.place_of_pain_2_10_b != null) { this.setState({place_of_pain_2_10_b: data.place_of_pain_2_10_b}); } if (data.intensity_2_10_b != null) { this.setState({intensity_2_10_b: data.intensity_2_10_b}); } if (data.created_at != null) { this.setState({created_at: data.created_at}); } } render () { return ( <div className="container" > <div className="card mb-3"> <div className="card-header"> <i className="fa fa-table"></i> Itensidade da dor </div> <div className="card-body"> <div className="table-responsive"> <table className="table table-bordered" id="dataTable" width="100%" cellSpacing="0"> <thead> <tr> <th>Data</th> <th>Local da dor</th> <th>Intensidade da dor</th> <th>Avaliado em</th> <th>Profissional</th> </tr> </thead> <tbody> { this.state.list.map(function(data){ return ( <tr key={data.id}> <td>{data.date_2_10_b}</td> <td>{data.place_of_pain_2_10_b}</td> <td>{data.intensity_2_10_b}</td> <td>{data.created_at}</td> <td>{data.history.user.name}</td> </tr> ) }) } <tr> <td>{this.state.date_2_10_b}</td> <td>{this.state.place_of_pain_2_10_b}</td> <td>{this.state.intensity_2_10_b}</td> <td>{this.state.created_at}</td> </tr> </tbody> </table> </div> </div> </div> <nav aria-label=""> <ul className="pagination justify-content-center"> <li className="page-item"> <Link className="page-link" to="/listings" tabIndex="-1">Retornar</Link> </li> </ul> </nav> </div> ) } } export default DetailsIdentificationChronicPainB
components/TextInput/TextInput.js
zendesk/linksf
import React from 'react' import s from './TextInput.css' const TextInput = (props) => ( <input className={s.input} {...props} type="text" /> ) export default TextInput
views/blocks/Search/search.js
AlSoEdit/team5
import React from 'react'; import SearchBar from './../SearchBar/SearchBar'; import SearchResult from './../SearchResult/SearchResult'; import SearchResultItem from './../SearchResult/ResultItem'; import Card from './../QuestCard/questCard'; import constants from './../../constants/defaultStates'; const Searcher = require('./Searcher.js'); function getParameterByName(name) { const url = window.location.href; name = name.replace(/[[]]/g, '\\$&'); const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'); const results = regex.exec(url); if (!results || !results[2]) { return null; } return decodeURIComponent(results[2].replace(/\+/g, ' ')); } function modifySearchState(state) { const searchType = getParameterByName('type'); if (searchType === 'tag') { state.searchByField = 'tags'; state.searchString = getParameterByName('tag'); } else if (searchType === 'string') { state.searchString = getParameterByName('string'); } } class Search extends React.Component { constructor(props) { super(props); this.handleResultChange = this.handleResultChange.bind(this); this.handleInputChange = this.handleInputChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.search = this.search.bind(this); let state = constants.defaultState; if (getParameterByName('type')) { modifySearchState(state); } this.state = state; } componentDidMount() { this.search(this.state.currentPage); } handleSubmit() { this.search(1); this.setState({ loading: true }); } search(newPageNumber) { var params = Searcher.getSearchParameters(this.state, newPageNumber); Searcher.searchRequest(params) .then(function (response) { return response.json(); }) .then(this.handleResultChange) .catch(() => {}); } handleResultChange(data) { this.setState({ result: data.quests, currentPage: data.pageNumber, pageCount: data.maxPageNumber, loading: false }); } handleInputChange(name, value) { this.setState({ [name]: value }); } renderResult() { return ( <SearchResult currentPage={this.state.currentPage} pageCount={this.state.pageCount} onPageChange={this.search}> {this.state.result.map(card => <SearchResultItem key={card.slug.toString()}> <Card card={card} /> </SearchResultItem>)} </SearchResult>); } render() { return ( <div className="Search"> <SearchBar handleSubmit={this.handleSubmit} onInputChange={this.handleInputChange} params={this.state}/> {(this.state.result.length > 0) ? this.renderResult() : !this.state.loading && <div>Таких квестов нет :(</div>} </div> ); } } export default Search;
src/parser/mage/fire/modules/features/HotStreakWastedCrits.js
FaideWW/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { formatNumber } from 'common/format'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import HIT_TYPES from 'game/HIT_TYPES'; import EnemyInstances, { encodeTargetString } from 'parser/shared/modules/EnemyInstances'; const debug = false; const PROC_WINDOW_MS = 200; const HOT_STREAK_CONTRIBUTORS = [ SPELLS.FIREBALL.id, SPELLS.PYROBLAST.id, SPELLS.FIRE_BLAST.id, SPELLS.SCORCH.id, SPELLS.PHOENIX_FLAMES_TALENT.id, ]; class HotStreakWastedCrits extends Analyzer { static dependencies = { enemies: EnemyInstances, }; lastCastEvent = 0; wastedCrits = 0; hasPyromaniacProc = false; constructor(...args) { super(...args); this.hasPyromaniac = this.selectedCombatant.hasTalent(SPELLS.PYROMANIAC_TALENT.id); this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(HOT_STREAK_CONTRIBUTORS), this._onCast); this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(HOT_STREAK_CONTRIBUTORS), this._onDamage); this.addEventListener(Events.applybuff.to(SELECTED_PLAYER).spell(SPELLS.HOT_STREAK), this.checkForPyromaniacProc); } //When a spell that contributes towards Hot Streak is cast, get the event info to use for excluding the cleaves from Phoenix Flames on the damage event. //If a Hot Streak Contributor was cast then Pyromaniac didnt proc, so set it to false (Pyromaniac procs when Hot Streak is used, so if something was cast, then it didnt proc) _onCast(event) { this.lastCastEvent = event; this.pyromaniacProc = false; } //When a spell that contributes towards Hot Streak crits the target while Hot Streak is active, count it as a wasted crit. //Excludes the cleave from Phoenix Flames (the cleave doesnt contribute towards Hot Streak) and excludes crits immediately after Pyromaniac procs, cause the player cant do anything to prevent that. _onDamage(event) { const spellId = event.ability.guid; const castTarget = encodeTargetString(this.lastCastEvent.targetID, event.targetInstance); const damageTarget = encodeTargetString(event.targetID, event.targetInstance); if (event.hitType !== HIT_TYPES.CRIT || !this.selectedCombatant.hasBuff(SPELLS.HOT_STREAK.id,null,-50) || (spellId === SPELLS.PHOENIX_FLAMES_TALENT.id && castTarget !== damageTarget)) { return; } if (this.hasPyromaniacProc) { debug && this.log("Wasted Crit Ignored"); } else { this.wastedCrits += 1; this.lastCastEvent.meta = this.lastCastEvent.meta || {}; this.lastCastEvent.meta.isInefficientCast = true; this.lastCastEvent.meta.inefficientCastReason = "This cast crit while you already had Hot Streak and could have contributed towards your next Heating Up or Hot Streak. To avoid this, make sure you use your Hot Streak procs as soon as possible."; debug && this.log("Wasted Crit"); } } //Pyromaniac doesnt trigger an event, so we need to check to see if the player immediately got a new Hot Streak immediately after using a Hot Streak checkForPyromaniacProc(event) { if (this.hasPyromaniac && event.timestamp - this.hotStreakRemoved < PROC_WINDOW_MS) { this.hasPyromaniacProc = true; } } get wastedCritsPerMinute() { return this.wastedCrits / (this.owner.fightDuration / 60000); } get wastedCritsThresholds() { return { actual: this.wastedCritsPerMinute, isGreaterThan: { minor: 0, average: 1, major: 3, }, style: 'number', }; } suggestions(when) { when(this.wastedCritsThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>You crit with {formatNumber(this.wastedCrits)} ({formatNumber(this.wastedCritsPerMinute)} Per Minute) direct damage abilities while <SpellLink id={SPELLS.HOT_STREAK.id} /> was active. This is a waste since those crits could have contibuted towards your next Hot Streak. Try to use your procs as soon as possible to avoid this.</>) .icon(SPELLS.HOT_STREAK.icon) .actual(`${formatNumber(this.wastedCrits)} crits wasted`) .recommended(`${formatNumber(recommended)} is recommended`); }); } } export default HotStreakWastedCrits;
client/components/ThemeSelect.js
GO345724/pair-programming
import React, { Component } from 'react'; import {FormGroup, ControlLabel, FormControl} from 'react-bootstrap'; import PropTypes from 'prop-types'; class ThemeSelect extends Component { constructor(props) { super(props); this.state = { themes : ['monokai', 'github', 'tomorrow', 'kuroir', 'twilight', 'xcode', 'textmate', 'solarized_dark', 'solarized_light', 'terminal'] } this.triggerChangeTheme = this.triggerChangeTheme.bind(this); } triggerChangeTheme(e) { this.props.changeTheme(e.target.value); } render() { const { themes } = this.state; const selectTheme = themes.map((theme, index) => { if (theme == this.props.theme) { return <option key={index} value={theme} selected>{theme}</option> } else { return <option key={index} value={theme}>{theme}</option> } }) return( <FormGroup controlId="formControlsSelect" onChange={this.triggerChangeTheme}> <ControlLabel>change theme</ControlLabel> <FormControl componentClass="select"> {selectTheme} </FormControl> </FormGroup> ) } } ThemeSelect.propTypes = { theme: PropTypes.string.isRequired, changeTheme: PropTypes.func.isRequired } export default ThemeSelect;
components/EmailMultiInput/EmailMultiInput.js
tomgatzgates/loggins
import React, { Component } from 'react'; import TagInput from 'react-tagsinput'; import { backspace, tab, enter, del, comma } from '../../util/keyCodes'; import s from './EmailMultiInput.css'; const MATCHER = /[^\s@,]+@[^\s,@]+\.[^\s@,]+/; export default class EmailMultiInput extends Component { constructor(props) { super(props); this.validateEmail = this.validateEmail.bind(this); this.handleContainerClick = this.handleContainerClick.bind(this); this.handleChange = this.handleChange.bind(this); } validateEmail(input) { return MATCHER.test(input); } handleChange(tags, addedOrRemovedTag) { if (tags.indexOf(addedOrRemovedTag) !== -1) { // Tag was added const validEmails = addedOrRemovedTag .split(',') .map(tag => tag.trim()) .filter(tag => this.props.emails.indexOf(tag) === -1) .sort() .filter((tag, pos, ary) => !pos || tag !== ary[pos - 1]) .filter(tag => MATCHER.test(tag)); this.props.onChange( this.props.emails.concat(validEmails) ); } else { // Tag was removed this.props.onChange( tags.filter(email => email !== addedOrRemovedTag) ); } } handleContainerClick(e) { if (!e.target.classList.contains('react-tagsinput-remove')) { this.refs.input.focus(); } } render() { return ( <div className={s.root} onClick={this.handleContainerClick}> <TagInput ref="input" value={this.props.emails} placeholder={this.props.placeholder} validate={this.validateEmail} addKeys={[tab, enter, comma]} removeKeys={[backspace, del]} onChange={this.handleChange} /> </div> ); } } EmailMultiInput.propTypes = { emails: React.PropTypes.array.isRequired, placeholder: React.PropTypes.string.isRequired, onChange: React.PropTypes.func.isRequired, };
react-app/src/components/Legends.js
tanykim/swimmers-network
import React, { Component } from 'react'; class LegendsComponent extends Component { render() { const { type } = this.props; return (<div className="legends"> <div className="legend-wrapper"> <span className="cursor-icon" /> <span className="legend"> <div className="legend-item"> { type === 'network' && <span className="legend-network"/> } { type === 'country' && <span className="legend-country"> <span className="r-general r-1 r-first"/> <span className="r-general r-2 r-btw"/> <span className="r-general r-3 r-btw"/> <span className="r-general r-last"/> </span> } { type === 'races' && <span className="legend-races"/> } <span className="legend-label">Swimmer</span> </div> </span> </div> <div className="medals"> <span className="gold"/><span className="medal-label">Gold</span> <span className="silver"/><span className="medal-label">Silver</span> <span className="bronze"/><span className="medal-label">Bronze</span> </div> </div>); } } export default LegendsComponent;
src/index.js
MarcAtrapalo/redux-formation
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
stories/AutoComplete/index.js
skyiea/wix-style-react
import React from 'react'; import {storiesOf} from '@storybook/react'; import Markdown from '../utils/Components/Markdown'; import TabbedView from '../utils/Components/TabbedView'; import CodeExample from '../utils/Components/CodeExample'; import Readme from '../../src/AutoComplete/README.md'; import ReadmeTestKit from '../../src/AutoComplete/README.TESTKIT.md'; import ExampleStandard from './ExampleStandard'; import ExampleStandardRaw from '!raw-loader!./ExampleStandard'; import ExampleControlled from './ExampleControlled'; import ExampleControlledRaw from '!raw-loader!./ExampleControlled'; import ExampleComplex from './ExampleComplex'; import ExampleComplexRaw from '!raw-loader!./ExampleComplex'; storiesOf('Core', module) .add('AutoComplete', () => ( <TabbedView tabs={['API', 'TestKits']}> <div> <Markdown source={Readme}/> <h1>Usage examples</h1> <CodeExample title="Standard" code={ExampleStandardRaw}> <ExampleStandard/> </CodeExample> <CodeExample title="Controlled input" code={ExampleControlledRaw}> <ExampleControlled/> </CodeExample> <CodeExample title="Complex input" code={ExampleComplexRaw}> <ExampleComplex/> </CodeExample> </div> <Markdown source={ReadmeTestKit}/> </TabbedView> ));
src/hooks/useColumnVisibility.js
react-tools/react-table
import React from 'react' import { actions, functionalUpdate, useGetLatest, makePropGetter, useMountedLayoutEffect, } from '../publicUtils' actions.resetHiddenColumns = 'resetHiddenColumns' actions.toggleHideColumn = 'toggleHideColumn' actions.setHiddenColumns = 'setHiddenColumns' actions.toggleHideAllColumns = 'toggleHideAllColumns' export const useColumnVisibility = hooks => { hooks.getToggleHiddenProps = [defaultGetToggleHiddenProps] hooks.getToggleHideAllColumnsProps = [defaultGetToggleHideAllColumnsProps] hooks.stateReducers.push(reducer) hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions) hooks.headerGroupsDeps.push((deps, { instance }) => [ ...deps, instance.state.hiddenColumns, ]) hooks.useInstance.push(useInstance) } useColumnVisibility.pluginName = 'useColumnVisibility' const defaultGetToggleHiddenProps = (props, { column }) => [ props, { onChange: e => { column.toggleHidden(!e.target.checked) }, style: { cursor: 'pointer', }, checked: column.isVisible, title: 'Toggle Column Visible', }, ] const defaultGetToggleHideAllColumnsProps = (props, { instance }) => [ props, { onChange: e => { instance.toggleHideAllColumns(!e.target.checked) }, style: { cursor: 'pointer', }, checked: !instance.allColumnsHidden && !instance.state.hiddenColumns.length, title: 'Toggle All Columns Hidden', indeterminate: !instance.allColumnsHidden && instance.state.hiddenColumns.length, }, ] function reducer(state, action, previousState, instance) { if (action.type === actions.init) { return { hiddenColumns: [], ...state, } } if (action.type === actions.resetHiddenColumns) { return { ...state, hiddenColumns: instance.initialState.hiddenColumns || [], } } if (action.type === actions.toggleHideColumn) { const should = typeof action.value !== 'undefined' ? action.value : !state.hiddenColumns.includes(action.columnId) const hiddenColumns = should ? [...state.hiddenColumns, action.columnId] : state.hiddenColumns.filter(d => d !== action.columnId) return { ...state, hiddenColumns, } } if (action.type === actions.setHiddenColumns) { return { ...state, hiddenColumns: functionalUpdate(action.value, state.hiddenColumns), } } if (action.type === actions.toggleHideAllColumns) { const shouldAll = typeof action.value !== 'undefined' ? action.value : !state.hiddenColumns.length return { ...state, hiddenColumns: shouldAll ? instance.allColumns.map(d => d.id) : [], } } } function useInstanceBeforeDimensions(instance) { const { headers, state: { hiddenColumns }, } = instance const isMountedRef = React.useRef(false) if (!isMountedRef.current) { } const handleColumn = (column, parentVisible) => { column.isVisible = parentVisible && !hiddenColumns.includes(column.id) let totalVisibleHeaderCount = 0 if (column.headers && column.headers.length) { column.headers.forEach( subColumn => (totalVisibleHeaderCount += handleColumn(subColumn, column.isVisible)) ) } else { totalVisibleHeaderCount = column.isVisible ? 1 : 0 } column.totalVisibleHeaderCount = totalVisibleHeaderCount return totalVisibleHeaderCount } let totalVisibleHeaderCount = 0 headers.forEach( subHeader => (totalVisibleHeaderCount += handleColumn(subHeader, true)) ) } function useInstance(instance) { const { columns, flatHeaders, dispatch, allColumns, getHooks, state: { hiddenColumns }, autoResetHiddenColumns = true, } = instance const getInstance = useGetLatest(instance) const allColumnsHidden = allColumns.length === hiddenColumns.length const toggleHideColumn = React.useCallback( (columnId, value) => dispatch({ type: actions.toggleHideColumn, columnId, value }), [dispatch] ) const setHiddenColumns = React.useCallback( value => dispatch({ type: actions.setHiddenColumns, value }), [dispatch] ) const toggleHideAllColumns = React.useCallback( value => dispatch({ type: actions.toggleHideAllColumns, value }), [dispatch] ) const getToggleHideAllColumnsProps = makePropGetter( getHooks().getToggleHideAllColumnsProps, { instance: getInstance() } ) flatHeaders.forEach(column => { column.toggleHidden = value => { dispatch({ type: actions.toggleHideColumn, columnId: column.id, value, }) } column.getToggleHiddenProps = makePropGetter( getHooks().getToggleHiddenProps, { instance: getInstance(), column, } ) }) const getAutoResetHiddenColumns = useGetLatest(autoResetHiddenColumns) useMountedLayoutEffect(() => { if (getAutoResetHiddenColumns()) { dispatch({ type: actions.resetHiddenColumns }) } }, [dispatch, columns]) Object.assign(instance, { allColumnsHidden, toggleHideColumn, setHiddenColumns, toggleHideAllColumns, getToggleHideAllColumnsProps, }) }
src/components/RadarController.js
TorinoMeteo/tm-realtime-map
import React from 'react' import PropTypes from 'prop-types' import ReactSlider from 'react-slider' import Switch from 'react-switch' class RadarController extends React.Component { static propTypes = { changeRadarStatus: PropTypes.func.isRequired, changeRadarPause: PropTypes.func.isRequired, changeRadarFrequency: PropTypes.func.isRequired, images: PropTypes.array.isRequired, status: PropTypes.shape({ active: PropTypes.bool, preloading: PropTypes.bool, image: PropTypes.object, pause: PropTypes.bool, frequency: PropTypes.number }) }; constructor (props) { super(props) this.state = { frequency: props.status.frequency } } render () { // no images? no controller if (!this.props.images.length) { return <span>N.D.</span> } let controllers = null if (this.props.status.active) { controllers = ( <div className='radar-controllers'> <div className='radar-controller-slider'> <i className='ion-minus' /> <ReactSlider min={100} max={2000} step={100} invert defaultValue={this.state.frequency} onChange={value => { this.setState({ frequency: value }) }} onAfterChange={value => { this.setState({ frequency: value }) this.props.changeRadarFrequency(value) }} > <div className='handle'>{this.state.frequency / 1000 + 's'}</div> </ReactSlider> <i className='ion-plus-round' /> </div> <div> <i onClick={() => this.props.changeRadarPause(!this.props.status.pause) } className={this.props.status.pause ? 'ion-play' : 'ion-pause'} /> </div> </div> ) } return ( <div> <div className='switch-wrapper'> <span>OFF</span> <Switch name={'switch-radar'} defaultChecked={this.props.status.active} checked={this.props.status.active} onChange={() => this.props.changeRadarStatus(!this.props.status.active) } /> <span>ON</span> </div> {controllers} </div> ) } } export default RadarController
src/components/Main.js
RxKotlin/techradar-reactjs
// require('normalize.css/normalize.css'); require('styles/App.css'); import React from 'react'; import RadarItemListPageComponent from './page/RadarItemListPageComponent'; import RadarHomePageComponent from './page/RadarHomePageComponent'; import Radar from './svg/RadarComponent'; import ListComponent from './Radar/ListComponent'; import {Button, Image, Grid, Row, Col} from 'react-bootstrap'; var UUID = require('uuid-js'); class AppComponent extends React.Component { constructor() { super(); this.state = {page: 'create', radius: 300, arr: []}; this.screen2Cartesian = this.screen2Cartesian.bind(this); } navigateToRadarPage() { this.setState({page: 'create', radius: 300, arr:[]}); } render() { if (this.state.page == 'create') { let items = this.state.arr.map(this.points2Items.bind(this)) let items1st = items.filter((item) => { return item.x > 0 && item.y > 0 }).map(this.cartesian2Screen.bind(this)); let items2nd = items.filter((item) => { return item.x < 0 && item.y > 0 }).map(this.cartesian2Screen.bind(this)); let items3rd = items.filter((item) => { return item.x < 0 && item.y < 0 }).map(this.cartesian2Screen.bind(this)); let items4th = items.filter((item) => { return item.x > 0 && item.y < 0 }).map(this.cartesian2Screen.bind(this)); let points = this.state.arr; return ( <div className="container"> <div className="row"> <div className="col-md-4"> <ListComponent title="Techniques" items={items2nd} key={`${UUID.create().toString()}`}/> </div> <div className="col-md-4 col-md-offset-4"> <ListComponent title="Tools" items={items1st} key={`${UUID.create().toString()}`}/> </div> </div> <div className="row"> <div className="col-md-12"> <Radar radius={this.state.radius} points={points} didChangedPoints={this.didChangedPoints.bind(this)}/> </div> </div> <div className="row"> <div className="col-md-4"> <ListComponent title="Platforms" items={items3rd} key={`${UUID.create().toString()}`}/> </div> <div className="col-md-4 col-md-offset-4"> <ListComponent title="Languages & Frameworks" items={items4th} key={`${UUID.create().toString()}`}/> </div> </div> </div> ); } return ( <RadarHomePageComponent showRadar={this.navigateToRadarPage.bind(this)}/> ); } cartesian2Screen(point) { return { x: (1 + point.x) * this.state.radius, y: (1 - point.y) * this.state.radius, type: point.type, id: point.id, name: point.name, index: point.index } } screen2Cartesian(point) { return { x: point.x / this.state.radius - 1, y: 1 - point.y / this.state.radius, type: point.type, id: point.id, name: point.name, index: point.index } } didChangedPoints(points) { this.setState({page: 'create', margin: 60, radius: 250, arr: points}); } points2Items(point) { let item = point; item.index = this.state.arr.indexOf(item) + 1; return item; } } AppComponent.defaultProps = {}; export default AppComponent;
packages/material-ui-icons/src/ArrowDownward.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8 8-8z" /></g> , 'ArrowDownward');
components/Quote.js
tendotosystems/lunchblast-client
import React from 'react' import { View, Text, StyleSheet } from 'react-native' import fontStyles from '../styles/fonts'; const Quote = ({quote}) => ( <View> <Text style={styles.quoteStyle}>{quote}</Text> <Text style={styles.quoteStyle}> - Guy Fieri</Text> </View> ) const styles = StyleSheet.create({ quoteStyle: { ...fontStyles, color: '#fff', fontSize: 14, paddingLeft: 5, paddingRight: 5, textAlign: 'center' } }) export default Quote
src/components/Header/Header.js
yurikrupnik/meaner
/** * 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 React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Header.scss'; import Link from '../Link'; import Navigation from '../Navigation'; function Header() { return ( <div className={s.root}> <div className={s.container}> <Navigation className={s.nav}/> <Link className={s.brand} to="/"> <img src={require('./logo-small.png')} width="38" height="38" alt="React"/> <span className={s.brandTxt}>Your Company</span> </Link> <div className={s.banner}> <h1 className={s.bannerTitle}>React</h1> <p className={s.bannerDesc}>Complex web apps made easy</p> </div> </div> </div> ); } export default withStyles(Header, s);
src/svg-icons/maps/my-location.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsMyLocation = (props) => ( <SvgIcon {...props}> <path d="M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm8.94 3c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06C6.83 3.52 3.52 6.83 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c4.17-.46 7.48-3.77 7.94-7.94H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/> </SvgIcon> ); MapsMyLocation = pure(MapsMyLocation); MapsMyLocation.displayName = 'MapsMyLocation'; MapsMyLocation.muiName = 'SvgIcon'; export default MapsMyLocation;
src/svg-icons/action/trending-up.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTrendingUp = (props) => ( <SvgIcon {...props}> <path d="M16 6l2.29 2.29-4.88 4.88-4-4L2 16.59 3.41 18l6-6 4 4 6.3-6.29L22 12V6z"/> </SvgIcon> ); ActionTrendingUp = pure(ActionTrendingUp); ActionTrendingUp.displayName = 'ActionTrendingUp'; export default ActionTrendingUp;
js/ShowCard.js
enrique7mc/vidflix
import React from 'react' import { Link } from 'react-router' const { string } = React.PropTypes const ShowCard = React.createClass({ propTypes: { poster: string.isRequired, title: string.isRequired, year: string.isRequired, imdbID: string.isRequired, description: string.isRequired }, render: function () { const { poster, title, year, description, imdbID } = this.props return ( <Link to={`/details/${imdbID}`}> <div className='show-card'> <img src={`/public/img/posters/${poster}`} alt={`${poster} poster`} /> <div> <h3>{title}</h3> <h4>({year})</h4> <p>{description}</p> </div> </div> </Link> ) } }) export default ShowCard
src/components/Form/Select/SelectView.js
Kalcode/Gatsby-Boilerplate
import React from 'react' import PropTypes from 'prop-types' import baseStyles from '../Inputs/styles.module.scss' import styles from './styles.module.scss' export default function SelectView({ children, error, inputProps, options, width }) { return ( <div className={baseStyles.wrapper} style={{ width }}> <div className={baseStyles.container}> <label htmlFor={inputProps.id} className={error ? baseStyles.labelInvalid : baseStyles.label}> {children} <select className={[baseStyles.input, styles.select].join(' ')} size={inputProps.multiple && options.length} {...inputProps} > {!inputProps.multiple && <option value='' disabled defaultValue>Choose your option</option>} {options} </select> </label> </div> </div> ) } SelectView.propTypes = { children: PropTypes.any, error: PropTypes.any, inputProps: PropTypes.object.isRequired, options: PropTypes.any, width: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ]), }
src/components/Help.js
stevenlaidlaw/Phorg
import React from 'react'; import styles from './Help.css'; const Help = ({display, toggleDisplay}) => ( <div className={`${styles.box} ${display ? styles.shown : ''}`} onClick={toggleDisplay}> <div className={styles.Help}> <h3>Rules</h3> <div className={styles.key}> <div>$Y</div> <div>Full Year</div> <div>$y</div> <div>Year</div> <div>$M</div> <div>Month</div> <div>$D</div> <div>Day</div> <div>$H</div> <div>Hours</div> <div>$m</div> <div>$Minutes</div> <div>$S</div> <div>Seconds</div> </div> <div className={styles.folderInfo}>Use / to create subfolders. For example, given the datetime '2015-05-16 16:46:22', the pattern '$Y/$M/' will create subfolders named '2015/05/'</div> <div className={styles.notAllowed}>The following characters are not allowed in file names and will be replaced with underscores &lt;, &gt;, :, ", \, |, ?, *</div> </div> </div> ); export default Help;
test/helpers.js
AlexKVal/react-overlays
import React from 'react'; import { cloneElement } from 'react'; export function shouldWarn(about) { console.warn.called.should.be.true; console.warn.calledWithMatch(about).should.be.true; console.warn.reset(); } /** * Helper for rendering and updating props for plain class Components * since `setProps` is deprecated. * @param {ReactElement} element Root element to render * @param {HTMLElement?} mountPoint Optional mount node, when empty it uses an unattached div like `renderIntoDocument()` * @return {ComponentInstance} The instance, with a new method `renderWithProps` which will return a new instance with updated props */ export function render(element, mountPoint){ let mount = mountPoint || document.createElement('div'); let instance = React.render(element, mount); if (!instance.renderWithProps) { instance.renderWithProps = function(newProps) { return render( cloneElement(element, newProps), mount); }; } return instance; } let style; let seen = []; export function injectCss(rules){ if ( seen.indexOf(rules) !== -1 ){ return; } style = style || (function() { let _style = document.createElement('style'); _style.appendChild(document.createTextNode('')); document.head.appendChild(_style); return _style; })(); seen.push(rules); style.innerHTML += '\n' + rules; } injectCss.reset = function(){ if ( style ) { document.head.removeChild(style); } style = null; seen = []; };
examples/isomorphic-react/client/render.js
d-oliveros/isomorphine
import React from 'react'; import App from './App.jsx'; let state = window.__STATE__; /** * Renders the app in the container */ let container = document.getElementById('app-container'); React.render(<App state={ state }/>, container);
index.android.js
nuttyboysoftware/ReactNativeDemo
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ 'use strict'; import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, Image, View, TouchableHighlight, TouchableOpacity, TouchableNativeFeedback, Dimensions, GeoLocation, Navigator } from 'react-native'; var width = Dimensions.get('window').width; var height = Dimensions.get('window').height; var location; var rootPage = require('./root.android') export default class InvoDay extends Component { _renderScene (route, navigator) { return <route.component {...route.passProps} navigator={navigator} /> } _pop (route, navigator) { console.log('_pop'); navigator.pop } render() { return ( <Navigator style={{flex: 1}} renderScene={this._renderScene.bind(this)} initialRoute={{component: rootPage, title:'Home Page'}} navigationBar={ <Navigator.NavigationBar routeMapper={{ LeftButton: (route, navigator, index, navState) => { return ( <View style={{ justifyContent: 'center', flex: 1 }}> <TouchableOpacity onPress={navigator.pop}> <Image style={{width: 50, height: 50}} source={require('./images/back.png')} /> </TouchableOpacity> </View>); }, RightButton: (route, navigator, index, navState) => { return null; }, Title: (route, navigator, index, navState) => { return (<View style={{ justifyContent: 'center', flex: 1 }}><Text>{route.title}</Text></View>); }, }} style={styles.nav_bar} /> }/> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', backgroundColor: '#F5FCFF', marginTop:54 }, container1: { flex: 1, justifyContent: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, button: { width: width * 0.8, height: 40, backgroundColor: 'red', marginTop: 5, marginBottom: 5 }, button_text: { textAlign: 'center', marginTop: 10 }, nav_bar: { alignItems: 'center', backgroundColor: 'gray', } }); AppRegistry.registerComponent('InvoDay', () => InvoDay);
blueocean-material-icons/src/js/components/svg-icons/image/dehaze.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageDehaze = (props) => ( <SvgIcon {...props}> <path d="M2 15.5v2h20v-2H2zm0-5v2h20v-2H2zm0-5v2h20v-2H2z"/> </SvgIcon> ); ImageDehaze.displayName = 'ImageDehaze'; ImageDehaze.muiName = 'SvgIcon'; export default ImageDehaze;
dva/wd/src/components/Layouts/BuyBarLayout.js
imuntil/React
import React from 'react'; import QueueAnim from 'rc-queue-anim' import styles from './BuyBarLayout.css'; function BuyBarLayout({ children, location }) { return ( <QueueAnim type={'right'} style={{ height: '100%', width: '100%', display: 'block' }}> <div key="l2" className={styles.normal}> <QueueAnim type={'bottom'} style={{ position: 'relative', width: '100%', height: '100%' }}> <div key={location.pathname} style={{ position: 'absolute', width: '100%', height: '100%', overflow: 'hidden' }}> {children} </div> </QueueAnim> <div className={styles.tabbar}> <a className={styles.cart} href="javascript:;">加入购物车</a> <a className={styles.buy} href="javascript:;">立即购买</a> </div> </div> </QueueAnim> ); } export default BuyBarLayout;
src/components/Resume/JobPage.js
angeloocana/angeloocana
import React from 'react'; import PropTypes from 'prop-types'; import H1 from '../H1'; import { injectIntl, FormattedMessage } from 'react-intl'; import Helmet from 'react-helmet'; import JobDates from './JobDates'; import styled from 'styled-components'; import Technologies from './Technologies'; import Projects from './Projects'; import ResumeContainer from './ResumeContainer'; const Header = styled.header` padding-bottom: ${({ theme }) => theme.scale(1)}; `; const getBreadCrumb = (langKey) => [ { link: `/${langKey}/resume/jobs-and-clients/`, label: 'resume.jobsAndClients' } ]; const Job = (props) => { const {job} = props.pathContext; const {menu} = props.data.site.siteMetadata.resume; const description = job.description; const langKey = props.intl.locale; return ( <ResumeContainer menu={menu} selectedPage="/resume/jobs-and-clients/" breadCrumb={getBreadCrumb(langKey)} > <FormattedMessage id="resume"> {(resume) => ( <Helmet title={`${resume} - ${job.name}`} meta={[{ name: 'description', content: description }]} /> )} </FormattedMessage> <Header> <H1>{job.name}</H1> </Header> <JobDates {...job.date} /> <Projects projects={job.projects} langKey={langKey} job={job} /> <Technologies technologies={job.technologies} /> </ResumeContainer> ); }; Job.propTypes = { intl: PropTypes.object.isRequired, pathContext: PropTypes.shape({ job: PropTypes.shape({ name: PropTypes.string, description: PropTypes.string, date: PropTypes.shape({ start: PropTypes.string, end: PropTypes.string }), projects: PropTypes.array, technologies: PropTypes.array }) }).isRequired, data: PropTypes.object.isRequired }; export default injectIntl(Job);
app/components/myCloudSdkDialog.js
JustinBeckwith/trebuchet
import React from 'react'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import RaisedButton from 'material-ui/RaisedButton'; import {remote, shell} from 'electron'; export default class myCloudSdkDialog extends React.Component { constructor(props) { super(props); this.state = { open: false, messageType: "install", }; let manager = this.props.manager; manager.isCloudSdkInstalled().then((installed) => { if (!installed) { this.setState({ open: true, messsageType: "install", }); } else { manager.checkDeps(); manager.isUserLoggedIn().then((loggedIn) => { if (!loggedIn) { this.setState({ open: true, messageType: "login", }); manager.attemptUserLogin().then((result) => { if (result) { this.setState({ open: false, }); } }); } }); } }); } handleClose = () => { remote.app.quit(); }; linkClick = (e) => { e.preventDefault(); shell.openExternal('https://cloud.google.com/sdk/'); }; render() { const actions = [ <FlatButton label="Ok" primary={true} onTouchTap={this.handleClose} keyboardFocused={true} /> ]; let dialog = <div></div>; switch(this.state.messageType) { case "install": dialog = ( <Dialog title="Install the Google Cloud SDK" actions={actions} modal={true} open={this.state.open} onRequestClose={this.handleClose}> The App Engine Trebuchet requires the Google Cloud SDK. Visit <a href='#' onClick={this.linkClick}>https://cloud.google.com/sdk/</a> to get started, and then restart the application. </Dialog> ); break; case "login": dialog = ( <Dialog title="Log into Google Cloud" actions={actions} modal={true} open={this.state.open} onRequestClose={this.handleClose}> To continue, please log into your Google account. </Dialog> ); break; } return dialog; } }