path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
src/js/components/input-ssn.js
training4developers/react_redux_12122016
import React from 'react'; export class InputSSN extends React.Component { static propTypes = { onChange: React.PropTypes.func, value: React.PropTypes.string, name: React.PropTypes.string }; onChange = (e) => { e.target.value = e.target.value.replace('-', ''); e.target.value = e.target.value.replace('-', ''); e.target.value = e.target.value.slice(0, 9); this.props.onChange(e); } render() { let ssn = this.props.value; if (ssn.length > 2) { ssn = ssn.slice(0,3) + '-' + ssn.slice(3); } if (ssn.length > 5) { ssn = ssn.slice(0,6) + '-' + ssn.slice(6); } return <input type="text" name={this.props.name} value={ssn} onChange={this.onChange} />; } }
src/components/migration/Migrate2.js
safex/safex_wallet
import React from 'react'; import {createSafexAddress, verify_safex_address, structureSafexKeys} from '../../utils/migration'; import {openMigrationAlert, closeMigrationAlert} from '../../utils/modals'; const fs = window.require('fs'); import {encrypt} from "../../utils/utils"; import MigrationAlert from "../migration//partials/MigrationAlert"; var swg = window.require('safex-addressjs'); const fileDownload = require('react-file-download'); //Set the Safex Address export default class Migrate2 extends React.Component { constructor(props) { super(props); this.state = { loading: true, status_text: "", create_address: false, safex_address: "", safex_spend_pub: "", safex_spend_sec: "", safex_view_pub: "", safex_view_sec: "", safex_checksum: "", safex_key: {}, safex_keys: {}, migration_alert: false, migration_alert_text: '', all_field_filled: false, used_addresses: false, existing_addresses: false, }; this.setSafexAddress = this.setSafexAddress.bind(this); this.createSafexKey = this.createSafexKey.bind(this); this.saveSafexKeys = this.saveSafexKeys.bind(this); this.setYourKeys = this.setYourKeys.bind(this); this.selectKey = this.selectKey.bind(this); this.setOpenMigrationAlert = this.setOpenMigrationAlert.bind(this); this.setCloseMigrationAlert = this.setCloseMigrationAlert.bind(this); this.startOver = this.startOver.bind(this); this.checkFields = this.checkFields.bind(this); this.usedAddresses = this.usedAddresses.bind(this); this.existingAddresses = this.existingAddresses.bind(this); this.exportNewWalletAddress = this.exportNewWalletAddress.bind(this); } componentDidMount() { try { var json = JSON.parse(localStorage.getItem('wallet')); } catch (e) { this.setOpenMigrationAlert('Error parsing the wallet data.'); } this.setState({ safex_keys: json.safex_keys, loading: false }) } setSafexAddress(e) { e.preventDefault(); } //generates a new random safex key set createSafexKey() { this.setState({create_address: true, loading: true}); const safex_keys = createSafexAddress(); localStorage.setItem('new_wallet_address', JSON.stringify(safex_keys)); this.setState({ safex_key: safex_keys, safex_address: safex_keys.public_addr, safex_spend_pub: safex_keys.spend.pub, safex_spend_sec: safex_keys.spend.sec, safex_view_pub: safex_keys.view.pub, safex_view_sec: safex_keys.view.sec, loading: false, }); } //use this after safex keys were generated saveSafexKeys() { //in here do the logic for modifying the wallet file data info try { var json = JSON.parse(localStorage.getItem('wallet')); } catch (e) { this.setOpenMigrationAlert('Error parsing the wallet data.'); } if (json.hasOwnProperty('safex_keys')) { json['safex_keys'].push(this.state.safex_key); } else { json['safex_keys'] = []; json['safex_keys'].push(this.state.safex_key); } var index = -1; for (var key in json.keys) { if (json.keys[key].public_key === this.props.data.address) { index = key; json.keys[key]['migration_data'] = {}; json.keys[key]['migration_data'].safex_keys = this.state.safex_key; json.keys[key].migration_progress = 2; } } var algorithm = 'aes-256-ctr'; var password = localStorage.getItem('password'); var cipher_text = encrypt(JSON.stringify(json), algorithm, password); fs.writeFile(localStorage.getItem('wallet_path'), cipher_text, (err) => { if (err) { console.log('Problem communicating to the wallet file.'); this.setOpenMigrationAlert('Problem communicating to the wallet file.'); } else { try { localStorage.setItem('wallet', JSON.stringify(json)); var json2 = JSON.parse(localStorage.getItem('wallet')); console.log(json2.keys[index].migration_data); this.exportNewWalletAddress(); this.props.setMigrationProgress(2); } catch (e) { console.log(e); this.setOpenMigrationAlert('An error adding a key to the wallet. Please contact [email protected]'); } } }); } //use this if the keys are provided by the user setYourKeys(e) { e.preventDefault(); if (e.target.spend_key.value === '' || e.target.view_key.value === '' || e.target.safex_address.value === '') { this.setOpenMigrationAlert('Fill out all the fields'); } else { let duplicate = false; //here check for duplicates for (var key in this.state.safex_keys) { console.log(this.state.safex_keys[key].spend.sec) if (this.state.safex_keys[key].spend.sec === e.target.spend_key.value && this.state.safex_keys[key].view.sec === e.target.view_key.value && this.state.safex_keys[key].public_addr === e.target.safex_address.value) { duplicate = true; console.log("duplicate detected") } } if (verify_safex_address(e.target.spend_key.value, e.target.view_key.value, e.target.safex_address.value)) { const safex_keys = structureSafexKeys(e.target.spend_key.value, e.target.view_key.value); try { var json = JSON.parse(localStorage.getItem('wallet')); } catch (e) { console.log('Error parsing the wallet data.'); this.setOpenMigrationAlert('Error parsing the wallet data.'); } if (json.hasOwnProperty('safex_keys') && duplicate === false) { json['safex_keys'].push(safex_keys); } else if (duplicate === false) { json['safex_keys'] = []; json['safex_keys'].push(safex_keys); } var index = -1; for (var key in json.keys) { if (json.keys[key].public_key === this.props.data.address) { index = key; json.keys[key]['migration_data'] = {}; json.keys[key]['migration_data'].safex_keys = safex_keys; json.keys[key].migration_progress = 2; } } var algorithm = 'aes-256-ctr'; var password = localStorage.getItem('password'); var cipher_text = encrypt(JSON.stringify(json), algorithm, password); fs.writeFile(localStorage.getItem('wallet_path'), cipher_text, (err) => { if (err) { console.log('Problem communicating to the wallet file.'); this.setOpenMigrationAlert('Problem communicating to the wallet file.'); } else { try { localStorage.setItem('wallet', JSON.stringify(json)); this.setState({ safex_key: safex_keys, safex_address: safex_keys.public_addr, safex_spend_pub: safex_keys.spend.pub, safex_spend_sec: safex_keys.spend.sec, safex_view_pub: safex_keys.view.pub, safex_view_sec: safex_keys.view.sec, loading: false, }); this.props.setMigrationProgress(2); } catch (e) { console.log(e); this.setOpenMigrationAlert('An error adding a key to the wallet. Please contact [email protected]'); } } }); } else { console.log('Incorrect keys'); this.setOpenMigrationAlert('Incorrect keys or duplicate'); } } } //use this for selected key from dropdown menu selectKey(e) { e.preventDefault(); if (e.target.address_selection.value.length > 0) { try { var json = JSON.parse(localStorage.getItem('wallet')); } catch (e) { console.log('Error parsing the wallet data.'); this.setOpenMigrationAlert('Error parsing the wallet data.'); } var key_index = -1; var x_index = -1; for (var key in json.keys) { if (json.keys[key].public_key === this.props.data.address) { key_index = key; for (var x_key in json.safex_keys) { if (json.safex_keys[x_key].public_addr === e.target.address_selection.value) { x_index = x_key; json.keys[key_index]['migration_data'] = {}; json.keys[key_index]['migration_data'].safex_keys = json.safex_keys[x_index]; json.keys[key_index].migration_progress = 2; } } } } if (x_index != -1 && key_index != -1) { var algorithm = 'aes-256-ctr'; var password = localStorage.getItem('password'); var cipher_text = encrypt(JSON.stringify(json), algorithm, password); fs.writeFile(localStorage.getItem('wallet_path'), cipher_text, (err) => { if (err) { this.setOpenMigrationAlert('Problem communicating to the wallet file.'); } else { try { localStorage.setItem('wallet', JSON.stringify(json)); var json2 = JSON.parse(localStorage.getItem('wallet')); this.setState({ safex_key: json2.safex_keys[x_index], safex_address: json2.safex_keys[x_index].public_addr, safex_spend_pub: json2.safex_keys[x_index].spend.pub, safex_spend_sec: json2.safex_keys[x_index].spend.sec, safex_view_pub: json2.safex_keys[x_index].view.pub, safex_view_sec: json2.safex_keys[x_index].view.sec, loading: false, }); this.props.setMigrationProgress(2); } catch (e) { console.log(e); this.setOpenMigrationAlert('An error adding a key to the wallet. Please contact [email protected]'); } } }); } else { console.log('Key does not exist'); this.setOpenMigrationAlert('Key does not exist'); } } else { console.log('No key from your list has been selected'); this.setOpenMigrationAlert('No key from your list has been selected'); } } startOver() { this.setState({ create_address: false, used_addresses: false, existing_addresses: false, all_field_filled: false, }) } setOpenMigrationAlert(message) { openMigrationAlert(this, message); } setCloseMigrationAlert() { closeMigrationAlert(this); } checkFields() { var safex_address = document.getElementById('safex_address').value; var spend_key = document.getElementById('spend_key').value; var view_key = document.getElementById('view_key').value; if (safex_address !== '' && spend_key !== '' && view_key !== '') { this.setState({ all_field_filled: true }) } else { this.setState({ all_field_filled: false }) } } usedAddresses() { this.setState({ used_addresses: true }) } existingAddresses() { this.setState({ existing_addresses: true }) } exportNewWalletAddress() { var wallet_data = JSON.parse(localStorage.getItem('new_wallet_address')); var new_wallet = ""; new_wallet += "Public address: " + wallet_data.public_addr + '\n'; new_wallet += "Spendkey " + '\n'; new_wallet += "pub: " + wallet_data.spend.pub + '\n'; new_wallet += "sec: " + wallet_data.spend.sec + '\n'; new_wallet += "Viewkey " + '\n'; new_wallet += "pub: " + wallet_data.view.pub + '\n'; new_wallet += "sec: " + wallet_data.view.sec + '\n'; var date = Date.now(); fileDownload(new_wallet, date + 'new_wallet_address.txt'); } render() { var options = []; if (this.state.safex_keys) { Object.keys(this.state.safex_keys).map(key => { options.push( <option key={key} value={this.state.safex_keys[key].public_addr}> {this.state.safex_keys[key].public_addr} </option>) }); } return ( <div> <p>Step 2/4 - Selecting The Safex Key</p> { this.state.create_address ? <div> <div className="set-your-key-head"> <div className="set-your-key-left"> <img src="images/migration/cube.png" alt="New Key"/> </div> <div className="set-your-key-right"> <h3 className="green-text">Migrate to new Safex address</h3> </div> </div> <p className="red-text"> The following wallet information is to control your coins, do not share it. <br/> Sharing this information can and will result in total loss of your Safex Tokens and Safex Cash.<br/> Keep this information safe at all times! </p> <p>Wallet Address</p> <input type="text" className="new-address-input" defaultValue={this.state.safex_address} /> {/* <p>{this.state.safex_address}</p> */} <p>Spend Key</p> <p>public: {this.state.safex_spend_pub}</p> <p>secret: {this.state.safex_spend_sec}</p> <p>View key</p> <p>public: {this.state.safex_view_pub}</p> <p>secret: {this.state.safex_view_sec}</p> <button className="button-shine" onClick={this.startOver}>Go back</button> <button className="button-shine green-btn" onClick={this.saveSafexKeys}>Back up my Safex Keys and continue </button> </div> : <div> { this.state.used_addresses ? <div> <div className="set-your-key-head"> <div className="set-your-key-left"> <img src="images/migration/my-keys.png" alt="My Keys"/> </div> <div className="set-your-key-right"> <h3 className="purple-text">Your previously used Safex addresses</h3> </div> </div> <form className="previuously-used-form" onSubmit={this.selectKey}> <select name="address_selection"> {options} </select> <button className="button-shine green-btn">Set address</button> </form> <button className="button-shine" onClick={this.startOver}>Go back</button> </div> : <div> { this.state.existing_addresses ? <div> <div className="set-your-key-head"> <div className="set-your-key-left"> <img src="images/migration/enter-key.png" alt="Enter Key"/> </div> <div className="set-your-key-right"> <h3 className="blue-text">Migration using my existing Safex address</h3> </div> </div> <form onSubmit={this.setYourKeys}> <div className="form-group"> <input className="col-xs-8" name="safex_address" placeholder="Safex address" id="safex_address" onChange={this.checkFields}/> <label className="col-xs-4 col-form-label" htmlFor="safex_address">If you already have Safex address, enter it here</label> </div> <div className="form-group"> <input className="col-xs-8" name="spend_key" placeholder="Secret spend key" id="spend_key" onChange={this.checkFields}/> <label className="col-xs-4 col-form-label" htmlFor="spend_key">Enter your Safex address secret spend key here</label> </div> <div className="form-group"> <input className="col-xs-8" name="view_key" placeholder="Secret view key" id="view_key" onChange={this.checkFields}/> <label className="col-xs-4 col-form-label" htmlFor="view_key">Enter your Safex address secret view key here</label> </div> <button className={this.state.all_field_filled ? "button-shine green-btn" : "button-shine"}>Set your address </button> </form> <button className="button-shine" onClick={this.startOver}>Go back </button> </div> : <div className="address-wrap-inner"> <div className="migrate-btns-wrap"> <div className="col-xs-4 btn-wrap"> <button className={this.state.create_address ? "active" : ""} onClick={this.createSafexKey}> <img src="images/migration/cube.png" alt="Cube"/> <span>New Address</span> </button> <p>Create new address</p> </div> <div className="col-xs-4 btn-wrap"> <button className={this.state.my_address ? "active" : ""} onClick={this.usedAddresses}> <img src="images/migration/my-keys.png" alt="My Keys"/> <span>Previously Used</span> </button> <p>Previously used address</p> </div> <div className="col-xs-4 btn-wrap"> <button className={this.state.enter_address ? "active" : ""} onClick={this.existingAddresses}> <img src="images/migration/enter-key.png" alt="Enter Key"/> <span>My Address</span> </button> <p>Use My Safex address</p> </div> </div> </div> } </div> } </div> } <MigrationAlert migrationAlert={this.state.migration_alert} migrationAlertText={this.state.migration_alert_text} closeMigrationAlert={this.setCloseMigrationAlert} /> </div> ) } }
app/routes.js
ideal-life-generator/react-full-stack-starter
import React from 'react'; import { IndexRoute, Route } from 'react-router'; import { routerActions } from 'react-router-redux'; import { UserAuthWrapper } from 'redux-auth-wrapper'; import Root from './containers/Root'; import Home from './containers/Home'; import Users from './containers/Users'; import Login from './containers/Login'; import Signup from './containers/Signup'; import Profile from './containers/Profile'; const UserIsAuthenticated = UserAuthWrapper({ authSelector: ({ user }) => user, predicate: ({ isAuthenticated }) => isAuthenticated, redirectAction: routerActions.replace, wrapperDisplayName: 'UserIsAuthenticated', }); const UserIsNotAuthenticated = UserAuthWrapper({ authSelector: ({ user }) => user, predicate: ({ isAuthenticated }) => !isAuthenticated, redirectAction: routerActions.replace, wrapperDisplayName: 'UserIsNotAuthenticated', failureRedirectPath: (state, ownProps) => ownProps.location.query.redirect || '/', allowRedirectBack: false, }); export default ( <Route path="/" component={Root}> <IndexRoute component={Home} /> <Route path="/users" component={Users} /> <Route path="/login" component={UserIsNotAuthenticated((Login))} /> <Route path="/signup" component={UserIsNotAuthenticated(Signup)} /> <Route path="/profile" component={UserIsAuthenticated(Profile)} /> </Route> ); // https://github.com/acdlite/redux-router
lib/components/ErrorPage.js
hanford/filepizza
import ErrorStore from '../stores/ErrorStore' import React from 'react' import Spinner from './Spinner' export default class ErrorPage extends React.Component { constructor() { super() this.state = ErrorStore.getState() this._onChange = () => { this.setState(ErrorStore.getState()) } } componentDidMount() { ErrorStore.listen(this._onChange) } componentDidUnmount() { ErrorStore.unlisten(this._onChange) } render() { return <div className="page"> <Spinner dir="up" /> <h1 className="with-subtitle">FilePizza</h1> <p className="subtitle"> <strong>{this.state.status}:</strong> {this.state.message} </p> {this.state.stack ? <pre>{this.state.stack}</pre> : null} </div> } }
imports/ui/components/resident-details/accounts/private-account/edit-pa-bill/continuation.js
gagpmr/app-met
import React from 'react'; import ReactDOM from 'react-dom'; import { browserHistory } from 'react-router'; import * as Styles from '/imports/modules/styles.js'; import { UpdateResident } from '/imports/api/residents/methods.js'; var DatePicker = require('react-datepicker'); var moment = require('moment'); require('/imports/ui/layouts/react-datepicker.css'); export class ContinuationTableBody extends React.Component { constructor(props) { super(props); this.keyPressed = this.keyPressed.bind(this); this.alterPaid = this.alterPaid.bind(this); this.submitForm = this.submitForm.bind(this); this.changeStartDate = this.changeStartDate.bind(this); this.changeEndDate = this.changeEndDate.bind(this); this.state = { IsPaid: null, StartDate: null, EndDate: null }; } keyPressed(event) { if (event.key === "Enter") { this.submitForm(event); } } submitForm(e) { e.preventDefault(); var startdate = moment.utc().utcOffset(+ 5.5).format('DD-MM-YYYY'); var enddate = moment.utc().utcOffset(+ 5.5).format('DD-MM-YYYY'); if (this.state.StartDate !== null) { startdate = this.state.StartDate.format('DD-MM-YYYY'); } else { startdate = moment(this.props.bill.StartDate).format('DD-MM-YYYY'); } if (this.state.EndDate !== null) { enddate = this.state.EndDate.format('DD-MM-YYYY'); } else { enddate = moment(this.props.bill.EndDate).format('DD-MM-YYYY'); } var paid = $('#IsPaid').is(":checked"); if (this.props.resident && this.props.bill) { var residentId = this.props.resident._id; var data = { ResidentId: residentId, PaBillId: this.props.bill._id, StartDate: startdate, EndDate: enddate, EditPaContinuationBill: true, IsPaid: paid } UpdateResident.call({ data: data }); browserHistory.push('/resident-details/' + residentId); } } alterPaid(e) { if (e.target.checked) { this.setState({ IsPaid: true }); } if (!e.target.checked) { this.setState({ IsPaid: false }); } } changeStartDate(date) { this.setState({ StartDate: date }); } changeEndDate(date) { this.setState({ EndDate: date }); } render() { var startdate = null; var enddate = null; var ispaid = null; if (this.props.bill !== undefined) { ispaid = this.props.bill.IsPaid; } if (this.state.StartDate !== null) { startdate = this.state.StartDate; } else { startdate = moment.utc().utcOffset(+ 5.5); } if (this.state.EndDate !== null) { enddate = this.state.EndDate; } else { enddate = moment.utc().utcOffset(+ 5.5); } return ( <tbody> <tr> <th>Start Date</th> <td> <DatePicker autoFocus="autofocus" tabIndex={ 1 } dateFormat="DD-MM-YYYY" selected={ startdate } onChange={ this.changeStartDate }/> </td> </tr> <tr> <th>End Date</th> <td> <DatePicker tabIndex={ 1 } dateFormat="DD-MM-YYYY" selected={ enddate } onChange={ this.changeEndDate }/> </td> </tr> <tr> <th>Is Paid</th> <td style={ Styles.PaddingThreeLeft }> <input style={ Styles.WidthEightyPaddingZeroLeft } type="checkbox" id="IsPaid" onKeyDown={ this.keyPressed } onChange={ this.alterPaid } defaultChecked={ ispaid }/> </td> </tr> <tr> <th className="text-center" colSpan="2"> <a onClick={ this.submitForm } onKeyDown={ this.keyPressed } href="">Save</a> </th> </tr> </tbody> ) } } ContinuationTableBody.propTypes = { bill: React.PropTypes.object, resident: React.PropTypes.object };
public/js/components/user_instructor.js
AC287/wdi_final_arrowlense2.0_FE
import React from 'react' import {Link} from 'react-router' import Firebase from 'firebase' import EditImgUrl from './user_img_edit.js' import CreateClass from './class_new.js' export default React.createClass({ contextTypes: { user: React.PropTypes.string, userid: React.PropTypes.string, userinfo: React.PropTypes.object, classes: React.PropTypes.object, router: React.PropTypes.object.isRequired, }, renderClasses: function(key) { return( <Classes key={key} details={this.context.classes[key]} router={this.context.router}/> ) }, filterActive: function(key){ return this.context.classes[key].active===true }, filterInactive: function(key){ return this.context.classes[key].active===false }, render: function(){ return( <div className="container-fluid"> <div className="row"> <div className="col-md-3 imgdiv"> <img src={this.context.userinfo.imgurl} className="profileimage"/> <br/> <br/> <EditImgUrl /> </div> <div className="col-md-4"> <p>Name: <strong>{this.context.userinfo.firstname} {this.context.userinfo.lastname}</strong></p> <p>Email: {this.context.userinfo.email}</p> <p>Instructor ID: {this.context.userinfo.instructorid}</p> </div> <div className="col-md-5"> <button type="button" className="btn btn-default btn-lg btn-block"> Create A Blog </button> <CreateClass /> </div> </div> <hr/> <div> <div className="container title"> <h3>My Classes</h3> </div> <div className="row"> <div className="col-md-6"> <h4>Active</h4> <div className="renderclasses"> {Object.keys(this.context.classes) .filter(this.filterActive) .map(this.renderClasses)} </div> </div> <div className="col-md-6"> <h4>Inactive</h4> <div className="renderclasses"> {Object.keys(this.context.classes) .filter(this.filterInactive) .map(this.renderClasses)} </div> </div> </div> </div> </div> ) } }) const Classes = React.createClass({ render: function(){ return( <Link to={`/class/${this.props.details.id}`}> <div className="row container-fluid"> <div className="col-sm-3 borderline"> <p><strong>{this.props.details.name}</strong></p> </div> <div className="col-sm-3 borderline"> <p>{this.props.details.semester} {this.props.details.year}</p> </div> <div className="col-sm-6 borderline"> <p>{this.props.details.description}</p> </div> </div> </Link> ) } })
test/test_helper.js
Eleutherado/ReactBasicBlog
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
packages/mineral-ui-icons/src/IconVerticalAlignTop.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconVerticalAlignTop(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M8 11h3v10h2V11h3l-4-4-4 4zM4 3v2h16V3H4z"/> </g> </Icon> ); } IconVerticalAlignTop.displayName = 'IconVerticalAlignTop'; IconVerticalAlignTop.category = 'editor';
example/app/src/index.js
aurbano/react-ds
import React from 'react'; import ReactDOM from 'react-dom'; import './example.css'; import './react-ds.css'; import Examples from './Examples'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<Examples />, document.getElementById('root')); registerServiceWorker();
src/components/photoshop/spec.js
casesandberg/react-color
/* global test, jest, expect */ import React from 'react' import renderer from 'react-test-renderer' import { red } from '../../helpers/color' import Photoshop from './Photoshop' import PhotoshopButton from './PhotoshopButton' import PhotoshopFields from './PhotoshopFields' import PhotoshopPointer from './PhotoshopPointer' import PhotoshopPointerCircle from './PhotoshopPointerCircle' import PhotoshopPreviews from './PhotoshopPreviews' test('Photoshop renders correctly', () => { const tree = renderer.create( <Photoshop { ...red } onAccept={ () => {} } onCancel={ () => {} } />, ).toJSON() expect(tree).toMatchSnapshot() }) test('Photoshop renders custom styles correctly', () => { const tree = renderer.create( <Photoshop { ...red } styles={{ default: { picker: { boxShadow: '0 0 10px red' } } }} />, ).toJSON() expect(tree.props.style.boxShadow).toBe('0 0 10px red') }) test('PhotoshopButton renders correctly', () => { const tree = renderer.create( <PhotoshopButton label="accept" onClick={ () => {} } />, ).toJSON() expect(tree).toMatchSnapshot() }) test('PhotoshopFields renders correctly', () => { const tree = renderer.create( <PhotoshopFields { ...red } />, ).toJSON() expect(tree).toMatchSnapshot() }) test('PhotoshopPointer renders correctly', () => { const tree = renderer.create( <PhotoshopPointer />, ).toJSON() expect(tree).toMatchSnapshot() }) test('PhotoshopPointerCircle renders correctly', () => { const tree = renderer.create( <PhotoshopPointerCircle { ...red } />, ).toJSON() expect(tree).toMatchSnapshot() }) test('PhotoshopPreviews renders correctly', () => { const tree = renderer.create( <PhotoshopPreviews { ...red } currencColor="#aeee00" />, ).toJSON() expect(tree).toMatchSnapshot() })
src/components/Main1.js
chris-deng/gallery-by-react
/** * Created by dengbingyu on 2016/10/28. */ require('normalize.css/normalize.css'); require('styles/App.scss'); import React from 'react'; import ReactDOM from 'react-dom'; //获取图片相关的数据 let imageDatas = require('json!../data/imageDatas.json'); imageDatas = ((imageDatasArr)=>{ // 将图片的url加入的图片object数组中 for(var i=0,len=imageDatasArr.length;i<len;i++){ let singleImgDate = imageDatasArr[i]; singleImgDate.imageURL= require('../images/' + singleImgDate.fileName); imageDatasArr[i] = singleImgDate; } return imageDatasArr; })(imageDatas); // 拿到一个范围内的随机值 var getRandomPos = (low,high) => Math.floor(Math.random()*(high-low)+low); // 拿到0-30度角里面的随机角度值 var getRandomRotate = ()=> { return (Math.random()>0.5?'':'-') + Math.ceil(Math.random()*30); }; // 创建单个图片组件 class SingleImgComp extends React.Component { constructor(props){ super(props); this.handleClick=this.handleClick.bind(this); // 坑,为什么呢? } // 图片翻转点击事件 handleClick(e){ this.props.inverse(); // 执行翻转动作 e.stopPropagation(); e.preventDefault(); } render(){ let styleObj = {}; // 样式对象 if(this.props.arragneStyle.pos){ styleObj = this.props.arragneStyle.pos; } if(this.props.arragneStyle.rotate){ // ['-webkit-','-moz-','-o-',''].forEach((value)=>{ // styleObj[value+'transform'] = 'rotate(' + this.props.arragneStyle.rotate + 'deg)'; // }); styleObj['transform'] = 'rotate(' + this.props.arragneStyle.rotate + 'deg)'; } var figureClassName = 'img-figure'; figureClassName += this.props.arragneStyle.isInverse?' is-Inverse':''; return ( <figure className={ figureClassName } style={styleObj} onClick={this.handleClick}> <img src={this.props.data.imageURL} alt={this.props.data.title} /> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> <div className="img-back" onClick={this.handleClick}> <p>{this.props.data.desc}</p> </div> </figcaption> </figure> ); } } class GalleryByReactApp extends React.Component { constructor(props){ super(props); this.Constant = { // 初始化每张图片的坐标范围,用于盛放各个分区的坐标范围 centerPos: { left:0, top:0 }, hsec:{ // 水平区域坐标 hLeftSecX:[0,0], // 水平区域左分区x轴的坐标范围 hRightSecX:[0,0], // 水平区域右分区x轴的坐标范围 hY: [0,0] // 水平区域y的取值相同 }, vsec:{ // 垂直方向只有上分区 leftX: [0,0], topY: [0,0] } }; this.state = { // 真正的图片坐标 imgsArrangeArr: [ // 图片坐标数组 // { // pos:{ // top:0, // left:0 // }, // rotate:0, // isInverse: false // 是否翻转 // } ] }; } inverse(index){ // 翻转图片的函数 return () => { let imgsArrangeArr = this.state.imgsArrangeArr; imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse; this.setState({ imgsArrangeArr: imgsArrangeArr }); } } // 布局页面图片的坐标 rearrange(centerIndex){ let arrangeImgArr = this.state.imgsArrangeArr, Constant = this.Constant, centerPos = Constant.centerPos, hLeftSecRangeX = Constant.hsec.hLeftSecX, hRightSecRangeX = Constant.hsec.hRightSecX, hY = Constant.hsec.hY, vLeftX = Constant.vsec.leftX, // 上分区 vTopY = Constant.vsec.topY; // 根据居中图片的下标,插入中心图片的坐标 let centerImgPosArr = arrangeImgArr.splice(centerIndex,1); // 取出了中心图片的元素 centerImgPosArr[0] = { pos : centerPos // 将中心图片的坐标插入,居中的图片不需要旋转 }; // 上分区图片位置 let imgTopArr = [], //用于放置上分区图片 topNum = Math.floor(Math.random()*2); // 上分区图片的个数,0或者1 let topImgIndex = Math.floor(Math.random()*(arrangeImgArr.length - topNum)); // 随机取出放置在上分区图片的下标 imgTopArr = arrangeImgArr.splice(topImgIndex,topNum); // 位于上分区的图片数组 imgTopArr && imgTopArr.forEach((value,index)=>{ // 填充上分区图片的位置信息 imgTopArr[index] = { pos:{ top: getRandomPos(vTopY[0],vTopY[1]), left: getRandomPos(vLeftX[0],vLeftX[1]) }, rotate: getRandomRotate() } }); // 左分区和右分区图片位置信息 for (let i=0,len=arrangeImgArr.length,k=len/2;i<len;i++){ let secLOR = null; // 存放左分区或者右分区x的坐标 if(i<k){ // 左分区 secLOR = hLeftSecRangeX; }else { secLOR = hRightSecRangeX; } arrangeImgArr[i]={ pos : { top: getRandomPos(hY[0],hY[1]), left: getRandomPos(secLOR[0],secLOR[1]) }, rotate: getRandomRotate() } } //前面分割了arrangeImgArr,取居中和上分区图片元素出来,现在合并进去 if(imgTopArr && imgTopArr){ // 填充上分区图片位置信息 arrangeImgArr.splice(topImgIndex,0,imgTopArr[0]); } arrangeImgArr.splice(centerIndex,0,centerImgPosArr[0]); // 填充居中图片的位置信息 this.setState({ imgsArrangeArr: arrangeImgArr }); } componentDidMount(){ // 给初始化的变量赋值 let stageDom = ReactDOM.findDOMNode(this.refs.stage), // 舞台dom元素 stageWidth = stageDom.scrollWidth, // 舞台宽度 stageHeight = stageDom.scrollHeight, // 舞台高度 halfStageW = Math.ceil(stageWidth / 2), // 舞台宽一半 halfStageH = Math.ceil(stageHeight/2); // 舞台高一半 let imgFigDom = ReactDOM.findDOMNode(this.refs.imgFigure0), // 图片的dom元素,因为每张图片的宽高相同,所以这里取imgFigure0 imgFigWidth = imgFigDom.scrollWidth, // 图片宽 imgFigHeight = imgFigDom.scrollHeight, halfImgW = Math.ceil(imgFigWidth/2), halfImgH = Math.ceil(imgFigHeight/2); let centerPos = { // 中心图片的坐标 left: halfStageW - halfImgW, top: halfStageH - halfImgH }; this.Constant.centerPos = centerPos; // 水平方向--左侧分区x的坐标范围 this.Constant.hsec.hLeftSecX[0] = - halfImgW; this.Constant.hsec.hLeftSecX[1] = halfStageW - halfImgW*3; // 水平方向--右侧分区x的坐标范围 this.Constant.hsec.hRightSecX[0] = halfStageW + halfImgW; this.Constant.hsec.hRightSecX[1] = stageWidth - halfImgW; // 水平方向--y的取值方位 this.Constant.hsec.hY[0] = - halfImgH; this.Constant.hsec.hY[1] = stageHeight - halfImgH; // 垂直方向--上分区x的取值范围 this.Constant.vsec.leftX[0] = halfStageW - halfImgW; this.Constant.vsec.leftX[1] = halfStageW; // 垂直方向--上分区y的取值范围 this.Constant.vsec.topY[0] = -halfImgH; this.Constant.vsec.topY[1] = halfStageH - halfImgH*3; this.rearrange(0); // 将第0张图片作为中心图片布局页面 } render(){ let controllerUtils = []; let imgFigures = []; imageDatas.forEach((value,index)=>{ if(!this.state.imgsArrangeArr[index]){ // 如果对应下标中午位置信息,则填充 this.state.imgsArrangeArr[index] = { pos: { left:0, top:0 }, rotate:0, isInverse: false // 默认为正面 } } imgFigures.push(<SingleImgComp data={value} arragneStyle={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} ref={'imgFigure'+index} />) }); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigures} </section> <nav className="controller-nav"> {controllerUtils} </nav> </section> ); } } GalleryByReactApp.defaultProps = {}; export default GalleryByReactApp;
src/javascript/index.js
knowbody/redux-react-router-example-app
import 'babel/polyfill'; import React from 'react'; import { render } from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; import createHashHistory from 'history/lib/createHashHistory'; import Root from './Root'; /* Needed for onTouchTap Can go away when react 1.0 release Check this repo: https://github.com/zilverline/react-tap-event-plugin */ injectTapEventPlugin(); render(<Root />, document.getElementById('root'));
src/index.js
tavofigse/flip-the-reactomster
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { Router, browserHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import routes from './routes' import configureStore from './store/configureStore' import './styles/app.scss' const store = configureStore() const history = syncHistoryWithStore(browserHistory, store) ReactDOM.render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('root') )
src/js/components/icons/base/Sync.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-sync`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'sync'); 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="M5,19 L16,19 C19.866,19 23,15.866 23,12 L23,9 M8,15 L4,19 L8,23 M19,5 L8,5 C4.134,5 1,8.134 1,12 L1,15 M16,1 L20,5 L16,9"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Sync'; 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/LoginForm/LoginForm.js
TackleboxBeta/betabox-seed
import React, { Component } from 'react'; import { reduxForm, Field, propTypes } from 'redux-form'; import loginValidation from './loginValidation'; import ValidationInput from '../ValidationInput/ValidationInput'; @reduxForm({ form: 'login', validate: loginValidation }) export default class LoginForm extends Component { static propTypes = { ...propTypes }; render() { const { handleSubmit, error } = this.props; return ( <form className="form-horizontal" onSubmit={handleSubmit}> <Field name="email" type="text" component={ValidationInput} label="Email" /> <Field name="password" type="password" component={ValidationInput} label="Password" /> {error && <p className="text-danger"><strong>{error}</strong></p>} <div className="row"> <div className="col-xs-2"> <button className="btn btn-success" type="submit"> <i className="fa fa-sign-in" />{' '}Log In </button> </div> <div className="col-xs-10"> <a className="btn btn-warning" href="/forgotpassword"> Forgot Password </a> </div> </div> </form> ); } }
test/FadeSpec.js
collinwu/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Fade from '../src/Fade'; describe('Fade', function () { let Component, instance; beforeEach(function(){ Component = React.createClass({ render(){ let { children, ...props } = this.props; return ( <Fade ref={r => this.fade = r} {...props} > <div> {children} </div> </Fade> ); } }); }); it('Should default to hidden', function () { instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); assert.ok( instance.fade.props.in === false); }); it('Should always have the "fade" class', () => { instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); assert.ok( instance.fade.props.in === false); assert.equal( React.findDOMNode(instance).className, 'fade'); }); it('Should add "in" class when entering', done => { instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); function onEntering(){ assert.equal(React.findDOMNode(instance).className, 'fade in'); done(); } assert.ok( instance.fade.props.in === false); instance.setProps({ in: true, onEntering }); }); it('Should remove "in" class when exiting', done => { instance = ReactTestUtils.renderIntoDocument( <Component in>Panel content</Component> ); function onExiting(){ assert.equal(React.findDOMNode(instance).className, 'fade'); done(); } assert.equal( React.findDOMNode(instance).className, 'fade in'); instance.setProps({ in: false, onExiting }); }); });
js/react/catch-of-the-day/node_modules/re-base/examples/github-notetaker/app/components/Notes/Notes.js
austinjalexander/sandbox
import React from 'react'; import NotesList from './NotesList'; import AddNote from './AddNote'; class Notes extends React.Component{ render(){ return ( <div> <h3> Notes for {this.props.username} </h3> <AddNote username={this.props.username} addNote={this.props.addNote} /> <NotesList notes={this.props.notes} /> </div> ) } }; Notes.propTypes = { username: React.PropTypes.string.isRequired, notes: React.PropTypes.array.isRequired, addNote: React.PropTypes.func.isRequired }; export default Notes;
src/components/app.js
fab1o/YouTube-Viewer
import React, { Component } from 'react'; export default class App extends Component { render() { return ( <div>React simple starter</div> ); } }
src/containers/CSM/CSM.js
UncleYee/crm-ui
import React from 'react'; import ReduxTableSelect from 'components/Form/NoLabel/ReduxTableSelect'; import MonthRangePicker from 'components/DatePicker/MonthRangePicker'; import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; import moment from 'moment'; import Modal from 'react-bootstrap/lib/Modal'; import Button from 'react-bootstrap/lib/Button'; import {connect} from 'react-redux'; import {getCSMInfo} from 'redux/modules/csm'; const styles = { header: { height: 34, position: 'relative' }, Menu: { left: 20, width: 210, float: 'left', position: 'relative' }, time: { width: 200, float: 'left' }, div: { float: 'none', position: 'relative', top: 20, width: 1200 }, root: { backgroundColor: 'white', width: '100%', minHeight: '660px', position: 'absolute' } }; @connect((state) => ({ csmInfo: state.csm.csmInfo || {}, }), { getCSMInfo, }) export default class CSM extends React.Component { static propTypes = { name: React.PropTypes.string, csmInfo: React.PropTypes.object, getCSMInfo: React.PropTypes.func, }; constructor(props) { super(props); this.state = { showTips: false, startDate: null, endDate: null, type: 0, defaultStart: null, defaultEnd: null, tableData: [], userNumStart: null, // 规模起始值 userNumEnd: null // 规模最大值 }; } componentWillMount() { const nowdays = new Date(); let year = nowdays.getFullYear(); let month = nowdays.getMonth(); if ( month === 0) { month = 12; year = year - 1; } if (month < 10) { month = '0' + month; } const myDate = new Date(year, month, 0); const lastDay = year + '-' + month + '-' + myDate.getDate(); const end = moment(new Date(lastDay)); const start = moment(new Date(lastDay)).add(-6, 'months').add(5, 'days'); const startDate = moment(start).format('YYYY-MM'); const endDate = moment(end).format('YYYY-MM'); this.setState({defaultStart: start, defaultEnd: end, startDate: startDate, endDate: endDate}); this.props.getCSMInfo(this.state.type, startDate, endDate); } // 时间段变化进行查询 CSMInfo = (start, end) => { this.setState({startDate: start, endDate: end}); this.props.getCSMInfo(this.state.type, this.state.startDate, this.state.endDate, this.state.userNumStart, this.state.userNumEnd); } // type 变化进行查询 changeValue = (type) => { this.setState({type: type}); this.props.getCSMInfo(type, this.state.startDate, this.state.endDate, this.state.userNumStart, this.state.userNumEnd); } // 规模变化查询 changeScale = (value) => { const getCsmInfo = () => this.props.getCSMInfo(this.state.type, this.state.startDate, this.state.endDate, this.state.userNumStart, this.state.userNumEnd); switch (value) { case '0': this.setState({userNumStart: 1, userNumEnd: 20}); break; case '1': this.setState({userNumStart: 21, userNumEnd: 100}); break; case '2': this.setState({userNumStart: 101, userNumEnd: 999999}); break; default: break; } // 事件队列 加入最后 等待上面的 setState 完成再执行 不需要使用异步 setTimeout(getCsmInfo); } defaultMonthRange = () => { return { start: this.state.defaultStart, end: this.state.defaultEnd }; } close = () => { this.setState({showTips: false}); } render() { const headConfig = this.props.csmInfo.titles || []; const tableData = this.props.csmInfo.rows || []; const tableOption = { noDataText: '无数据' }; const options = [ {value: '0', label: '客户总使用次数'}, {value: '1', label: '客户当月活跃人数'}, {value: '2', label: '人均使用次数'} ]; const scaleOptions = [ {value: '0', label: '1 ~ 20人'}, {value: '1', label: '21 ~ 100人'}, {value: '2', label: '100人以上'} ]; return ( <div style={styles.root}> <div style={styles.header}> <div style={styles.Menu}> <ReduxTableSelect getInfo={this.changeValue} name="csm" options={options} defaultValue="0"/> </div> { <div style={styles.Menu}> <ReduxTableSelect getInfo={this.changeScale} name="scale" options={scaleOptions} placeholder="请选择客户规模"/> </div> } <div style={styles.Menu}> <MonthRangePicker onSelect={this.CSMInfo} defaultValue={this.defaultMonthRange()}/> </div> </div> <div style={styles.div}> <BootstrapTable options={tableOption} bodyStyle={{height: 530, overflow: 'auto'}} data={tableData} headerStyle={{background: '#e6e7e8'}}> <TableHeaderColumn dataField="support_mananger_name" isKey width="100">客成经理</TableHeaderColumn> { headConfig.map((item, index) => <TableHeaderColumn key={index} dataField={item.title} dataSort width="100">{item.title}</TableHeaderColumn>) } </BootstrapTable> </div> <Modal show={this.state.showTips} onHide={this.close}> <Modal.Header closeButton> <Modal.Title>请选择结单状态</Modal.Title> </Modal.Header> <Modal.Body > 您选择的时间范围有误,时间范围必须在6-12个月之间,请重新选择! </Modal.Body> <Modal.Footer> <Button onClick={this.close}>关闭</Button> </Modal.Footer> </Modal> </div> ); } }
app/components/FormMessages/index.js
acebusters/ab-web
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { baseColor, black, } from '../../variables'; const FormError = styled.span` margin: 0; padding: 0.5em 1em; font-size: 0.8em; font-family: $text-font-stack; float: left; color: ${baseColor}; width: 100%; `; const FormWarning = styled.span` margin: 0; padding: 0.5em 1em; font-size: 0.8em; font-family: $text-font-stack; float: left; color: ${black}; width: 100%; `; export function ErrorMessage(props) { return ( <FormError> <strong>{props.error}</strong> </FormError> ); } ErrorMessage.propTypes = { error: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), }; export function WarningMessage(props) { return ( <FormWarning> <strong>{props.warning}</strong> </FormWarning> ); } WarningMessage.propTypes = { warning: PropTypes.string, };
test/components/icon-spec.js
nordsoftware/react-foundation
import React from 'react'; import { render } from 'enzyme'; import { expect } from 'chai'; import { Icon } from '../../src/components/icon'; describe('Icon component', () => { it('sets tag name', () => { const component = render(<Icon name="ok"/>); expect(component).to.have.tagName('i'); }); it('sets icon', () => { const component = render(<Icon name="ok"/>); expect(component).to.have.className('ok'); expect(component).to.not.have.attr('icon'); }); it('sets prefix', () => { const component = render(<Icon prefix="fa" name="ok"/>); expect(component).to.have.className('fa'); expect(component).to.not.have.attr('prefix'); }); it('adds prefix to name', () => { const component = render(<Icon prefix="fa" name="ok"/>); expect(component).to.have.className('fa'); expect(component).to.have.className('fa-ok'); }); });
todo/src/index.js
iamwangxupeng/react-reflux-webpack-es6
import React from 'react'; import ReactDOM from 'react-dom'; import Todo from './components/todo'; import csss from './style/main.css'; ReactDOM.render( <Todo> </Todo>, document.querySelector('#app') );
src/svg-icons/notification/more.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationMore = (props) => ( <SvgIcon {...props}> <path d="M22 3H7c-.69 0-1.23.35-1.59.88L0 12l5.41 8.11c.36.53.97.89 1.66.89H22c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 13.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm5 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm5 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/> </SvgIcon> ); NotificationMore = pure(NotificationMore); NotificationMore.displayName = 'NotificationMore'; NotificationMore.muiName = 'SvgIcon'; export default NotificationMore;
src/views/PointerEventsContainer.js
half-shell/react-navigation
/* @flow */ import React from 'react'; import invariant from 'fbjs/lib/invariant'; import AnimatedValueSubscription from './AnimatedValueSubscription'; import type { NavigationSceneRendererProps, } from '../TypeDefinition'; type Props = NavigationSceneRendererProps; const MIN_POSITION_OFFSET = 0.01; /** * Create a higher-order component that automatically computes the * `pointerEvents` property for a component whenever navigation position * changes. */ export default function create( Component: ReactClass<*>, ): ReactClass<*> { class Container extends React.Component<any, Props, any> { _component: any; _onComponentRef: (view: any) => void; _onPositionChange: (data: {value: number}) => void; _pointerEvents: string; _positionListener: ?AnimatedValueSubscription; props: Props; constructor(props: Props, context: any) { super(props, context); this._pointerEvents = this._computePointerEvents(); } componentWillMount(): void { this._onPositionChange = this._onPositionChange.bind(this); this._onComponentRef = this._onComponentRef.bind(this); } componentDidMount(): void { this._bindPosition(this.props); } componentWillUnmount(): void { this._positionListener && this._positionListener.remove(); } componentWillReceiveProps(nextProps: Props): void { this._bindPosition(nextProps); } render() { this._pointerEvents = this._computePointerEvents(); return ( <Component {...this.props} pointerEvents={this._pointerEvents} onComponentRef={this._onComponentRef} /> ); } _onComponentRef(component: any): void { this._component = component; if (component) { invariant( typeof component.setNativeProps === 'function', 'component must implement method `setNativeProps`', ); } } _bindPosition(props: NavigationSceneRendererProps): void { this._positionListener && this._positionListener.remove(); this._positionListener = new AnimatedValueSubscription( props.position, this._onPositionChange, ); } _onPositionChange(): void { if (this._component) { const pointerEvents = this._computePointerEvents(); if (this._pointerEvents !== pointerEvents) { this._pointerEvents = pointerEvents; this._component.setNativeProps({ pointerEvents }); } } } _computePointerEvents(): string { const { navigationState, position, scene, } = this.props; if (scene.isStale || navigationState.index !== scene.index) { // The scene isn't focused. return scene.index > navigationState.index ? 'box-only' : 'none'; } const offset = position.__getAnimatedValue() - navigationState.index; if (Math.abs(offset) > MIN_POSITION_OFFSET) { // The positon is still away from scene's index. // Scene's children should not receive touches until the position // is close enough to scene's index. return 'box-only'; } return 'auto'; } } return Container; }
src/components/Schedule.js
MathMesquita/conf
import React from 'react'; import { css } from 'glamor'; import Text from './Text'; const styles = { container: css({ background: '#fff', width: '100vw', paddingBottom: '2em', alignItems: 'center', '@media(max-width: 720px)': { alignSelf: 'auto', }, }), list: css({ listStyle: 'none', padding: 0, maxWidth: '1000px', margin: '0 auto', }), disclaimer: css({ padding: 0, maxWidth: '1000px', margin: '30px auto', textAlign: 'right', }), event: css({ display: 'flex', borderTop: '1px solid #333', padding: '1em 0 0.5em', justifyContent: 'space-around', ' div': {}, ' h2': { margin: '0 0 0.3em 0', ' span': { fontSize: '0.7em', }, }, ' h3': { fontWeight: 'lighter', fontSize: '1.3em', margin: 0, }, }), time: css({ fontSize: '1.7em', paddingLeft: '1.3em', whiteSpace: 'nowrap', }), desc: css({ width: '100%', padding: '0.2em 1.3em', }), }; const eventsList = [ { title: 'Abertura do Teatro e Credenciamento', time: '8:00 am', }, { title: 'Welcome Coffee', time: '8:30 am', }, { title: 'Abertura React Brasil', time: '9:00 am', }, { title: 'Raphael Amorim', description: 'Scratching React Fiber', time: '9:10 am', }, { title: 'Fernando Daciuk', description: 'The magic world of tests with Jest', time: '9:40 am', }, { title: 'Kete Rufino e Christino Milfont', description: 'Transformando um front-end legado em uma React SPA', time: '10:10 am', }, { title: 'Marcelo Camargo', description: "Let's dive into Babel: How everything works", time: '10:35 am', }, { title: 'James Baxley', description: 'Statically Typing your GraphQL App', time: '10:55 am', }, { title: 'Desconferência: Fishbowl', time: '11:30 am', }, { title: 'Almoço', time: '12:00 pm', }, { title: 'Clara Battesini', description: 'MobX: The light side of the force', time: '1:30 pm', }, { title: 'Henrique Sosa', description: 'Gorgeous Apps with React Motion and Animations', time: '1:40 pm', }, { title: 'João Gonçalves', description: 'Show do Milhão React PWA (Caso de Sucesso)', time: '1:50 pm', }, { title: 'Raphael Costa', description: 'Building the Pipefy mobile app in 3 weeks with React Native, GraphQL and Apollo', time: '2:00 pm', }, { title: 'Sashko Stubailo', description: 'The GraphQL and Apollo stack: connecting everything together', time: '2:25 pm', }, { title: 'Sebastian Ferrari', description: 'Why React is good for business', time: '3:05 pm', }, { title: 'Coffee Break', time: '3:30 pm', }, { title: 'Matheus Marsiglio', description: 'Isomorphic React + Redux App', time: '4:00 pm', }, { title: 'Matheus Lima', description: 'O que tem de Funcional no React', time: '4:25 pm', }, { title: 'Keuller Magalhães', description: 'React Performance from Scratch', time: '4:35 pm', }, { title: 'Geisy Domiciano', description: 'Continuos Integration / Continuos Deployment com create-react-app', time: '4:45 pm', }, { title: 'Sibelius Seraphini', description: 'Relay Modern', time: '4:55 pm', }, { title: 'Desconferência: Fishbowl', time: '5:15 pm', }, { title: 'Sorteios', time: '5:45 pm', }, { title: 'Encerramento', time: '6:00 pm', }, { title: 'AfterParty', description: 'Mono Club by An English Thing', time: '6:30 pm', }, ]; const Event = ({ title, time, worksIn = false, worksLink, description }) => <li {...styles.event}> <div {...styles.time}> {time} </div> <div {...styles.desc}> <h2> {title} {worksIn && <span> {worksIn} </span>} </h2> {description && <h3> {description} </h3>} </div> </li>; const Schedule = ({ events = eventsList }) => <section {...styles.container}> <Text title="Programa" /> <ol {...styles.list}> {events.map(event => <Event {...event} />)} </ol> <p {...styles.disclaimer}>Horário sujeito a alteração sem aviso prévio</p> </section>; export default Schedule;
app/containers/HomePage/Loadable.js
mxstbr/react-boilerplate
/** * Asynchronously loads the component for HomePage */ import React from 'react'; import loadable from 'utils/loadable'; import LoadingIndicator from 'components/LoadingIndicator'; export default loadable(() => import('./index'), { fallback: <LoadingIndicator />, });
src/layouts/CoreLayout/CoreLayout.js
joris77/admin-web
import React from 'react' import { Layout, Panel } from 'react-toolbox' import Header from '../../components/Header' import './CoreLayout.scss' import '../../styles/core.scss' import GlobalMessage from 'components/GlobalMessage' export const CoreLayout = ({ children }) => ( <Layout> <Panel> <Header /> <GlobalMessage /> {children} </Panel> </Layout> ) export default CoreLayout
src/scenes/SearchScreen/components/RepoSearchBar/index.js
msanatan/GitHubProjects
import React, { Component } from 'react'; import { SearchBar, } from 'react-native-elements'; export default class RepoSearchBar extends Component { constructor(props) { super(props) this.handleChangeText = this.handleChangeText.bind(this); } render() { return ( <SearchBar lightTheme placeholder='Search for user...' autoCapitalize='none' onChangeText={this.handleChangeText} /> ); } handleChangeText(newUsername) { this.props.onChangeText(newUsername); } }
docs/src/app/pages/components/RadioGroup/ExampleRadioGroupDescription.js
GetAmbassador/react-ions
import React from 'react' import RadioGroup from 'react-ions/lib/components/Radio/RadioGroup' import Radio from 'react-ions/lib/components/Radio/Radio' import Input from 'react-ions/lib/components/Input' import style from './style.scss' const radioOptions = [ { value: 'welcome_email', label: 'Send welcome email', description: 'Send an email welcoming your contact to your program.' }, { value: 'payment_update_email', label: 'Send update payment email', description: 'Send a payment update email to your contact.' } ] class ExampleRadioGroupDescription extends React.Component { constructor(props) { super(props) } getRadioBlocks = () => { return radioOptions.map((option, index) => { return <Radio key={index} value={option.value} label={option.label} description={option.description} /> }) } render() { return ( <div> <RadioGroup name='child-description-group' changeCallback={this.handleChange}> {this.getRadioBlocks()} </RadioGroup> </div> ) } } export default ExampleRadioGroupDescription
src/calendar/header/index.js
eals/react-native-calender-pn-wix-extended
import React, { Component } from 'react'; import { ActivityIndicator } from 'react-native'; import { View, Text, TouchableOpacity, Image } from 'react-native'; import XDate from 'xdate'; import PropTypes from 'prop-types'; import styleConstructor from './style'; import { weekDayNames } from '../../dateutils'; import Icon from 'react-native-vector-icons/Ionicons'; import theme from '../../../../../components/theme'; import moment from 'moment'; class CalendarHeader extends Component { static propTypes = { theme: PropTypes.object, hideArrows: PropTypes.bool, month: PropTypes.instanceOf(XDate), addMonth: PropTypes.func, showIndicator: PropTypes.bool, firstDay: PropTypes.number, renderArrow: PropTypes.func, hideDayNames: PropTypes.bool, }; constructor(props) { super(props); this.style = styleConstructor(props.theme); this.addMonth = this.addMonth.bind(this); this.substractMonth = this.substractMonth.bind(this); } nextMonth(next){ var month = ["Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan"]; return month[next-1]; } twoMonth(next){ var month = ["Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb"]; return month[next-1]; } addMonth() { this.props.addMonth(1); } substractMonth() { this.props.addMonth(-1); } shouldComponentUpdate(nextProps) { if ( nextProps.month.toString('yyyy MM') !== this.props.month.toString('yyyy MM') ) { return true; } if (nextProps.showIndicator !== this.props.showIndicator) { return true; } return false; } render() { let leftArrow = <View />; let rightArrow = <View />; let weekDaysNames = weekDayNames(this.props.firstDay); if (!this.props.hideArrows) { leftArrow = ( <TouchableOpacity onPress={this.substractMonth} style={this.style.arrow} > {this.props.renderArrow ? this.props.renderArrow('left') : <Image source={require('../img/previous.png')} style={this.style.arrowImage} />} </TouchableOpacity> ); rightArrow = ( <TouchableOpacity onPress={this.addMonth} style={this.style.arrow}> {this.props.renderArrow ? this.props.renderArrow('right') : <Image source={require('../img/next.png')} style={this.style.arrowImage} />} </TouchableOpacity> ); } let indicator; if (this.props.showIndicator) { indicator = <ActivityIndicator />; } return ( <View style={{}}> <Image style={this.style.proBg} source={require('../img/proBgg.png')}> <View style={{flex:1,flexDirection:'row',alignSelf:'center',marginBottom:-25}}> {leftArrow} <Text style={{color:"#fff",fontSize:18,alignSelf:'flex-end',marginBottom:35,marginRight:25,borderBottomWidth:1,borderColor:'#fff'}}> {this.props.month.toString(this.props.monthFormat ? this.props.monthFormat : 'MMM')} </Text> <Text style={{color:"#DBAEAF",fontSize:18,alignSelf:'flex-end',marginBottom:35,marginRight:25}}> {this.nextMonth(this.props.month.toString(this.props.monthFormat ? this.props.monthFormat : 'M'))} </Text> <Text style={{color:"#C36D6F",fontSize:18,alignSelf:'flex-end',marginBottom:35,}}> {this.twoMonth(this.props.month.toString(this.props.monthFormat ? this.props.monthFormat : 'M'))} </Text> {rightArrow} <View style={{flexDirection:'column',flex:1}}> <View style={{alignSelf:'flex-end'}}> <Text style={{fontSize:18,alignSelf:'center',color:"#fff"}}> {moment().format("MMMM")} </Text> <Text style={{fontSize:22,alignSelf:'center',color:"#fff"}}> {moment().format("DD, YYYY")} </Text> <View style={{width: 80, alignSelf:'center',height:80,borderRadius:40,backgroundColor:"white",borderRadius:40,borderWidth:5,borderColor:'rgba(193, 192, 192, 0.53)',justifyContent:'center'}}> <Icon size={42} name="ios-calendar" style={{color: theme.themeColor, alignSelf:'center' }} /> </View> </View> </View> </View> </Image> <View style={{borderBottomWidth:1,borderColor:'#ECECEC',marginBottom:10,paddingBottom:10,backgroundColor:"#F9F9F9"}}> { !this.props.hideDayNames && <View style={this.style.week}> {weekDaysNames.map((day, idx) => { if(moment().format("ddd") == day){ return( <View key={idx} style={{flexDirection:'column'}}> <View style={{height:15,width:15,borderRadius:10,backgroundColor:"#E81B21",alignSelf:'center',borderWidth:2,borderColor:"#F6CDCE",marginBottom:10,paddingBottom:10}}></View> <Text style={[this.style.dayHeader,{color:"#E81B21"}]} numberOfLines={1}>{day.toUpperCase()}</Text> </View> ) } else { return( <View key={idx} style={{flexDirection:'column'}}> <View style={{height:15,width:15,borderRadius:10,backgroundColor:"#BBBBBB",alignSelf:'center',marginBottom:10,paddingBottom:10}}></View> <Text style={[this.style.dayHeader,{color:"#626262"}]} numberOfLines={1}>{day.toUpperCase()}</Text> </View> )} })} </View> } </View> </View> ); } } export default CalendarHeader;
classic/src/scenes/mailboxes/src/Scenes/AppScene/ServiceTab/ServiceInfoDrawer/ServiceInstallInfo.js
wavebox/waveboxapp
import PropTypes from 'prop-types' import React from 'react' import { accountActions, accountStore } from 'stores/account' import { withStyles } from '@material-ui/core/styles' import shallowCompare from 'react-addons-shallow-compare' import DoneIcon from '@material-ui/icons/Done' import ServiceInfoPanelActionButton from 'wbui/ServiceInfoPanelActionButton' import ServiceInfoPanelActions from 'wbui/ServiceInfoPanelActions' import ServiceInfoPanelBody from 'wbui/ServiceInfoPanelBody' import ServiceInfoPanelContent from 'wbui/ServiceInfoPanelContent' import ServiceReducer from 'shared/AltStores/Account/ServiceReducers/ServiceReducer' import ReactMarkdown from 'react-markdown' import WBRPCRenderer from 'shared/WBRPCRenderer' const styles = { markdown: { '& img': { maxWidth: '100%' } }, buttonIcon: { marginRight: 6 } } class Link extends React.Component { render () { const { href, children, ...passProps } = this.props return ( <a {...passProps} href='#' onClick={() => WBRPCRenderer.wavebox.openExternal(href)}> {children} </a> ) } } @withStyles(styles) class ServiceInstallInfo extends React.Component { /* **************************************************************************/ // Class /* **************************************************************************/ static propTypes = { serviceId: PropTypes.string.isRequired } /* **************************************************************************/ // Component Lifecycle /* **************************************************************************/ componentDidMount () { accountStore.listen(this.accountUpdated) } componentWillUnmount () { accountStore.unlisten(this.accountUpdated) } componentWillReceiveProps (nextProps) { if (this.props.serviceId !== nextProps.serviceId) { this.setState({ ...this.deriveServiceInfo(nextProps.serviceId, accountStore.getState()) }) } } /* **************************************************************************/ // Data lifecycle /* **************************************************************************/ state = (() => { return { ...this.deriveServiceInfo(this.props.serviceId, accountStore.getState()) } })() accountUpdated = (accountState) => { this.setState({ ...this.deriveServiceInfo(this.props.serviceId, accountState) }) } /** * Gets the service info from the account state * @param serviceId: the id of the service * @param accountState: the current account state * @return a state update object */ deriveServiceInfo (serviceId, accountState) { const service = accountState.getService(serviceId) return { installText: service ? service.installText : '' } } /* **************************************************************************/ // UI Events /* **************************************************************************/ /** * Handles a link being clicked */ handleLinkClick = (url, text, title) => { WBRPCRenderer.wavebox.openExternal(url) } /* **************************************************************************/ // Rendering /* **************************************************************************/ shouldComponentUpdate (nextProps, nextState) { return shallowCompare(this, nextProps, nextState) } render () { const { serviceId, classes, ...passProps } = this.props const { installText } = this.state return ( <ServiceInfoPanelContent {...passProps}> <ServiceInfoPanelBody actions={1}> <ReactMarkdown className={classes.markdown} source={installText} skipHtml renderers={{ link: Link, linkReference: Link }} /> </ServiceInfoPanelBody> <ServiceInfoPanelActions actions={1}> <ServiceInfoPanelActionButton color='primary' variant='contained' onClick={() => { accountActions.reduceService(serviceId, ServiceReducer.setHasSeenInstallInfo, true) }}> <DoneIcon className={classes.buttonIcon} /> Done </ServiceInfoPanelActionButton> </ServiceInfoPanelActions> </ServiceInfoPanelContent> ) } } export default ServiceInstallInfo
MobileApp/node_modules/react-native-elements/src/badge/badge.js
VowelWeb/CoinTradePros.com
import PropTypes from 'prop-types'; import React from 'react'; import { Text, View, StyleSheet, TouchableOpacity } from 'react-native'; import colors from '../config/colors'; const Badge = props => { const { containerStyle, textStyle, wrapperStyle, onPress, component, value, children, element, ...attributes } = props; if (element) return element; let Component = View; let childElement = ( <Text style={[styles.text, textStyle && textStyle]}>{value}</Text> ); if (children) { childElement = children; } if (children && value) { console.error('Badge can only contain either child element or value'); } if (!component && onPress) { Component = TouchableOpacity; } if (React.isValidElement(component)) { Component = component; } return ( <View style={[styles.container && wrapperStyle && wrapperStyle]}> <Component style={[styles.badge, containerStyle && containerStyle]} onPress={onPress} {...attributes} > {childElement} </Component> </View> ); }; Badge.propTypes = { containerStyle: View.propTypes.style, wrapperStyle: View.propTypes.style, textStyle: Text.propTypes.style, children: PropTypes.element, value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), onPress: PropTypes.func, component: PropTypes.func, element: PropTypes.element, }; const styles = StyleSheet.create({ container: { flexDirection: 'row', }, badge: { padding: 12, paddingTop: 3, paddingBottom: 3, backgroundColor: colors.grey1, borderRadius: 20, alignItems: 'center', justifyContent: 'center', }, text: { fontSize: 14, color: 'white', }, }); export default Badge;
src/svg-icons/action/highlight-off.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionHighlightOff = (props) => ( <SvgIcon {...props}> <path d="M14.59 8L12 10.59 9.41 8 8 9.41 10.59 12 8 14.59 9.41 16 12 13.41 14.59 16 16 14.59 13.41 12 16 9.41 14.59 8zM12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/> </SvgIcon> ); ActionHighlightOff = pure(ActionHighlightOff); ActionHighlightOff.displayName = 'ActionHighlightOff'; ActionHighlightOff.muiName = 'SvgIcon'; export default ActionHighlightOff;
js/jqwidgets/demos/react/app/kanban/disablecollapse/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxKanban from '../../../jqwidgets-react/react_jqxkanban.js'; class App extends React.Component { render() { let fields = [ { name: 'id', type: 'string' }, { name: 'status', map: 'state', type: 'string' }, { name: 'text', map: 'label', type: 'string' }, { name: 'tags', type: 'string' }, { name: 'color', map: 'hex', type: 'string' }, { name: 'resourceId', type: 'number' } ]; let source = { localData: [ { id: '1161', state: 'new', label: 'Make a new Dashboard', tags: 'dashboard', hex: '#36c7d0', resourceId: 3 }, { id: '1645', state: 'work', label: 'Prepare new release', tags: 'release', hex: '#ff7878', resourceId: 1 }, { id: '9213', state: 'new', label: 'One item added to the cart', tags: 'cart', hex: '#96c443', resourceId: 3 }, { id: '6546', state: 'done', label: 'Edit Item Price', tags: 'price, edit', hex: '#ff7878', resourceId: 4 }, { id: '9034', state: 'new', label: 'Login 404 issue', tags: 'issue, login', hex: '#96c443' } ], dataType: 'array', dataFields: fields }; let dataAdapter = new $.jqx.dataAdapter(source); let resourcesAdapterFunc = () => { let resourcesSource = { localData: [ { id: 0, name: 'No name', image: '../../jqwidgets/styles/images/common.png', common: true }, { id: 1, name: 'Andrew Fuller', image: '../../images/andrew.png' }, { id: 2, name: 'Janet Leverling', image: '../../images/janet.png' }, { id: 3, name: 'Steven Buchanan', image: '../../images/steven.png' }, { id: 4, name: 'Nancy Davolio', image: '../../images/nancy.png' }, { id: 5, name: 'Michael Buchanan', image: '../../images/Michael.png' }, { id: 6, name: 'Margaret Buchanan', image: '../../images/margaret.png' }, { id: 7, name: 'Robert Buchanan', image: '../../images/robert.png' }, { id: 8, name: 'Laura Buchanan', image: '../../images/Laura.png' }, { id: 9, name: 'Laura Buchanan', image: '../../images/Anne.png' } ], dataType: 'array', dataFields: [ { name: 'id', type: 'number' }, { name: 'name', type: 'string' }, { name: 'image', type: 'string' }, { name: 'common', type: 'boolean' } ] }; let resourcesDataAdapter = new $.jqx.dataAdapter(resourcesSource); return resourcesDataAdapter; } let columns = [ { text: 'Backlog', dataField: 'new', maxItems: 4 }, { text: 'In Progress', dataField: 'work', maxItems: 2 }, { text: 'Done', dataField: 'done', collapsible: false, maxItems: 5 } ]; let columnRenderer = (element, collapsedElement, column) => { setTimeout(() => { let columnItems = this.refs.myKanban.getColumnItems(column.dataField).length; // update header's status. element.find('.jqx-kanban-column-header-status').html(' (' + columnItems + '/' + column.maxItems + ')'); // update collapsed header's status. collapsedElement.find('.jqx-kanban-column-header-status').html(' (' + columnItems + '/' + column.maxItems + ')'); }); }; return ( <JqxKanban ref='myKanban' resources={resourcesAdapterFunc()} source={dataAdapter} columns={columns} columnRenderer={columnRenderer} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
docs/src/app/components/pages/components/DatePicker/ExampleInline.js
IsenrichO/mui-with-arrows
import React from 'react'; import DatePicker from 'material-ui/DatePicker'; /** * Inline Date Pickers are displayed below the input, rather than as a modal dialog. */ const DatePickerExampleInline = () => ( <div> <DatePicker hintText="Portrait Inline Dialog" container="inline" /> <DatePicker hintText="Landscape Inline Dialog" container="inline" mode="landscape" /> </div> ); export default DatePickerExampleInline;
app/components/Item/Background/Background.js
TriPSs/popcorn-time-desktop
// @flow import React from 'react' import classNames from 'classnames' import type { Props } from './BackgroundTypes' import classes from './Background.scss' export const Background = ({ backgroundImage }: Props) => ( <div className={classes.background__container}> <div className={classNames(classes.background__poster, 'animated fadeIn')} style={{ backgroundImage: `url(${backgroundImage})` }}> <div className={classes.background__overlay} /> </div> </div> ) export default Background
blueprints/view/files/__root__/views/__name__View/__name__View.js
llukasxx/school-organizer-front
import React from 'react' type Props = { }; export class <%= pascalEntityName %> extends React.Component { props: Props; render () { return ( <div></div> ) } } export default <%= pascalEntityName %>
actor-apps/app-web/src/app/components/modals/create-group/ContactItem.react.js
Johnnywang1221/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;
blueocean-material-icons/src/js/components/svg-icons/communication/vpn-key.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const CommunicationVpnKey = (props) => ( <SvgIcon {...props}> <path d="M12.65 10C11.83 7.67 9.61 6 7 6c-3.31 0-6 2.69-6 6s2.69 6 6 6c2.61 0 4.83-1.67 5.65-4H17v4h4v-4h2v-4H12.65zM7 14c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/> </SvgIcon> ); CommunicationVpnKey.displayName = 'CommunicationVpnKey'; CommunicationVpnKey.muiName = 'SvgIcon'; export default CommunicationVpnKey;
frontend/capitolwords-spa/src/components/HomePage/HomePage.js
propublica/Capitol-Words
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { routeToPhraseSearch } from '../../actions/search-actions'; import SearchInput from '../SearchInput/SearchInput'; import './HomePage.css'; import { isSearching, isSearchFailure, isSearchSuccess, searchResultList, searchDelta } from '../../selectors/phrase-search-selectors'; class HomePage extends Component { static propTypes = { isSearching: PropTypes.bool.isRequired, isSearchFailure: PropTypes.bool.isRequired, isSearchSuccess: PropTypes.bool.isRequired, searchResultList: PropTypes.array, searchDelta: PropTypes.number }; render() { const { routeToPhraseSearch } = this.props; return ( <div className="HomePage-container"> <div className="Title"> <h3>Capitol Words</h3> <p>Dig up some data on the words our legislators use every day.</p> </div> <div className="HomePage-searchInput"> <SearchInput variant="blue" onSubmit={routeToPhraseSearch}/> </div> <div className="QuickOptions-container"> <div className="QuickOption" onClick={() => {routeToPhraseSearch('Poverty')}}>Poverty</div> <div className="QuickOption" onClick={() => {routeToPhraseSearch('Russian Interference')}}>Russian Interference</div> <div className="QuickOption" onClick={() => {routeToPhraseSearch('Education')}}>Education</div> <div className="QuickOption" onClick={() => {routeToPhraseSearch('Tax Cuts')}}>Tax Cuts</div> </div> </div> ); } } export default connect(state => ({ isSearching: isSearching(state), isSearchFailure: isSearchFailure(state), isSearchSuccess: isSearchSuccess(state), searchDelta: searchDelta(state), searchResultList: searchResultList(state), }), { routeToPhraseSearch, })(HomePage);
packages/cf-component-dropdown/src/Dropdown.js
koddsson/cf-ui
import React from 'react'; import PropTypes from 'prop-types'; import { canUseDOM } from 'exenv'; import { createComponent } from 'cf-style-container'; import DropdownRegistry from './DropdownRegistry'; const styles = ({ theme, align }) => ({ position: 'absolute', zIndex: 1, minWidth: '10.66667rem', margin: '0.5em 0 0', padding: '0.33333rem 0', listStyle: 'none', background: theme.colorWhite, border: `1px solid ${theme.colorGrayLight}`, borderRadius: theme.borderRadius, boxShadow: '0 3px 10px rgba(0, 0, 0, 0.2)', left: align === 'left' ? 0 : 'initial', right: align === 'right' ? 0 : 'initial', textAlign: theme.textAlign, animationName: { '0%': { display: 'none', opacity: 0 }, '1%': { display: 'block', opacity: 0, top: '80%' }, '100%': { display: 'none', opacity: 1, top: '102%' } }, animationDuration: '150ms', animationTimingFunction: 'ease-out', '&::before': { content: "''", display: 'block', position: 'absolute', bottom: '100%', border: 'solid transparent', borderWidth: '10px', borderTopWidth: 0, borderBottomColor: theme.colorWhite, left: align === 'left' ? '10px' : 'initial', right: align === 'right' ? '10px' : 'initial' } }); class Dropdown extends React.Component { getChildContext() { return { dropdownRegistry: this.dropdownRegistry }; } constructor(props, context) { super(props, context); this.dropdownRegistry = new DropdownRegistry(); this.handleDocumentClick = this.handleDocumentClick.bind(this); this.handleDocumentKeydown = this.handleDocumentKeydown.bind(this); } componentDidMount() { if (canUseDOM) { global.document.addEventListener('keydown', this.handleDocumentKeydown); global.document.addEventListener('click', this.handleDocumentClick); } } componentWillUnmount() { if (canUseDOM) { global.document.removeEventListener( 'keydown', this.handleDocumentKeydown ); global.document.removeEventListener('click', this.handleDocumentClick); } } handleDocumentKeydown(event) { const keyCode = event.keyCode; if (keyCode === 40) { // down event.preventDefault(); this.dropdownRegistry.focusNext(); } else if (keyCode === 38) { // up event.preventDefault(); this.dropdownRegistry.focusPrev(); } else if (keyCode === 27) { // esc this.props.onClose(); } } handleDocumentClick() { this.props.onClose(); } render() { return ( <ul className={this.props.className} role="menu"> {this.props.children} </ul> ); } } Dropdown.propTypes = { onClose: PropTypes.func.isRequired, align: PropTypes.oneOf(['left', 'right']), children: PropTypes.node }; Dropdown.defaultProps = { align: 'left' }; Dropdown.childContextTypes = { dropdownRegistry: PropTypes.instanceOf(DropdownRegistry).isRequired }; export default createComponent(styles, Dropdown);
app/stories/index.js
atralice/reactDockerizeBoilerplate
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { linkTo } from '@storybook/addon-links'; import { Button, Welcome } from '@storybook/react/demo'; storiesOf('Welcome', module).add('to Storybook', () => <Welcome showApp={linkTo('Button')} />); storiesOf('Button', module) .add('with text', () => <Button onClick={action('clicked')}>Hello Button</Button>) .add('with some emoji', () => <Button onClick={action('clicked')}>😀 😎 👍 💯</Button>);
packages/mineral-ui-icons/src/IconImageAspectRatio.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconImageAspectRatio(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M16 10h-2v2h2v-2zm0 4h-2v2h2v-2zm-8-4H6v2h2v-2zm4 0h-2v2h2v-2zm8-6H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H4V6h16v12z"/> </g> </Icon> ); } IconImageAspectRatio.displayName = 'IconImageAspectRatio'; IconImageAspectRatio.category = 'image';
Libraries/Utilities/throwOnWrongReactAPI.js
esauter5/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule throwOnWrongReactAPI * @flow */ 'use strict'; function throwOnWrongReactAPI(key: string) { throw new Error( `Seems you're trying to access 'ReactNative.${key}' from the 'react-native' package. Perhaps you meant to access 'React.${key}' from the 'react' package instead? For example, instead of: import React, { Component, View } from 'react-native'; You should now do: import React, { Component } from 'react'; import { View } from 'react-native'; Check the release notes on how to upgrade your code - https://github.com/facebook/react-native/releases/tag/v0.25.1 `); } module.exports = throwOnWrongReactAPI;
src/components/Footer.js
SaKKo/react-redux-todo-boilerplate
import React from 'react'; import { connect } from 'react-redux'; import { setVisibilityFilter } from '../actions/actions'; import { SHOW_ALL,SHOW_ACTIVE,SHOW_COMPLETED } from '../constants/ActionTypes'; import Link from './Link'; const mapStateProps = ( state, ownProps ) => { return { active: ownProps.filter === state.visibilityFilter }; }; const mapDispatchProps = ( dispatch, ownProps ) => { return { onClick: () => { dispatch( setVisibilityFilter(ownProps.filter) ); } }; }; const FilterLink = connect( mapStateProps, mapDispatchProps )(Link); const Footer = () => ( <p> Show: {' '} <FilterLink filter={SHOW_ALL}> All </FilterLink> {', '} <FilterLink filter={SHOW_ACTIVE}> Active </FilterLink> {', '} <FilterLink filter={SHOW_COMPLETED}> Completed </FilterLink> </p> ); export default Footer;
src/index.js
Warm-men/Investment-by-react
import React from 'react' import { render } from 'react-dom' import { hashHistory } from 'react-router' import RouteMap from './router/routeMap' render( <RouteMap history={hashHistory}/>, document.getElementById('app') );
src/views/components/notification/notification.js
connorbanderson/CoinREXX
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import './notification.css'; class Notification extends Component { static propTypes = { action: PropTypes.func.isRequired, actionLabel: PropTypes.string.isRequired, dismiss: PropTypes.func.isRequired, display: PropTypes.bool.isRequired, duration: PropTypes.number, message: PropTypes.string.isRequired }; componentDidMount() { this.startTimer(); } componentWillReceiveProps(nextProps) { if (nextProps.display) { this.startTimer(); } } componentWillUnmount() { this.clearTimer(); } clearTimer() { if (this.timerId) { clearTimeout(this.timerId); } } startTimer() { this.clearTimer(); this.timerId = setTimeout(() => { this.props.dismiss(); }, this.props.duration || 5000); } render() { return ( <div className="notification"> <p className="notification__message" ref={c => this.message = c}>{this.props.message}</p> <button className="btn notification__button" onClick={this.props.action} ref={c => this.button = c} type="button">{this.props.actionLabel}</button> </div> ); } } export default Notification;
src/Well.js
JimiHFord/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const Well = React.createClass({ mixins: [BootstrapMixin], getDefaultProps() { return { bsClass: 'well' }; }, render() { let classes = this.getBsClassSet(); return ( <div {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </div> ); } }); export default Well;
src/js/Pickers/__tests__/Year.js
lwhitlock/grow-tracker
/* eslint-env jest*/ jest.unmock('../Year'); import React from 'react'; import { findDOMNode } from 'react-dom'; import { Simulate, renderIntoDocument, } from 'react-dom/test-utils'; import Year from '../Year'; describe('Year', () => { it('calls the onClick function when clicked', () => { const onClick = jest.fn(); const year = renderIntoDocument( <Year year={2000} onClick={onClick} active={false} /> ); const yearNode = findDOMNode(year); Simulate.click(yearNode); expect(onClick.mock.calls.length).toBe(1); }); it('renders the year as children', () => { const year = renderIntoDocument( <Year year={2000} onClick={jest.fn()} active={false} /> ); const yearNode = findDOMNode(year); expect(yearNode.textContent).toBe('2000'); }); });
test/reveal.spec.js
negomi/react-burger-menu
'use strict'; import React from 'react'; import TestUtils from 'react-dom/test-utils'; import { expect } from 'chai'; import createShallowComponent from './utils/createShallowComponent'; import renderIntoDocument from './utils/renderIntoDocument'; import BurgerMenu from '../src/BurgerMenu'; const Menu = BurgerMenu.reveal.default; describe('reveal', () => { let component, menuWrap, menu, itemList, firstItem; function addWrapperElementsToDOM() { let outerContainer = document.createElement('div'); outerContainer.setAttribute('id', 'outer-container'); let pageWrap = document.createElement('div'); pageWrap.setAttribute('id', 'page-wrap'); outerContainer.appendChild(pageWrap); document.body.appendChild(outerContainer); } function removeWrapperElementsFromDOM() { let outerContainer = document.getElementById('outer-container'); document.body.removeChild(outerContainer); } beforeEach(() => { addWrapperElementsToDOM(); }); afterEach(() => { removeWrapperElementsFromDOM(); }); it('has correct menuWrap styles', () => { component = createShallowComponent( <Menu pageWrapId={'page-wrap'} outerContainerId={'outer-container'}> <div>An item</div> </Menu> ); menuWrap = component.props.children[2]; expect(menuWrap.props.style.position).to.equal('fixed'); expect(menuWrap.props.style.zIndex).to.equal(-1); expect(menuWrap.props.style.width).to.equal('300px'); expect(menuWrap.props.style.height).to.equal('100%'); }); it('has correct menu styles', () => { component = renderIntoDocument( <Menu pageWrapId={'page-wrap'} outerContainerId={'outer-container'}> <div>An item</div> </Menu> ); menu = TestUtils.findRenderedDOMComponentWithClass(component, 'bm-menu'); expect(menu.style.height).to.equal('100%'); expect(menu.style.boxSizing).to.equal('border-box'); }); it('has correct itemList styles', () => { component = renderIntoDocument( <Menu pageWrapId={'page-wrap'} outerContainerId={'outer-container'}> <div>An item</div> </Menu> ); itemList = TestUtils.findRenderedDOMComponentWithClass( component, 'bm-item-list' ); expect(itemList.style.height).to.equal('100%'); }); it('has correct item styles', () => { component = renderIntoDocument( <Menu pageWrapId={'page-wrap'} outerContainerId={'outer-container'}> <div>An item</div> </Menu> ); firstItem = TestUtils.findRenderedDOMComponentWithClass( component, 'bm-item-list' ).children[0]; expect(firstItem.style.display).to.equal('block'); }); it('can be positioned on the right', () => { component = renderIntoDocument( <Menu pageWrapId={'page-wrap'} outerContainerId={'outer-container'} right> <div>An item</div> </Menu> ); menuWrap = TestUtils.findRenderedDOMComponentWithClass( component, 'bm-menu-wrap' ); expect(menuWrap.style.right).to.equal('0px'); }); });
src/js/components/icons/base/Book.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-book`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'book'); 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="M10,1 L10,11 L13,9 L16,11 L16,1 M5.5,18 C4.11928813,18 3,19.1192881 3,20.5 C3,21.8807119 4.11928813,23 5.5,23 L22,23 M3,20.5 L3,3.5 C3,2.11928813 4.11928813,1 5.5,1 L21,1 L21,18.0073514 L5.49217286,18.0073514 M20.5,18 C19.1192881,18 18,19.1192881 18,20.5 C18,21.8807119 19.1192881,23 20.5,23 L20.5,23"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Book'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
app/containers/CardForm.js
wenwuwu/redux-restful-example
import React from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import CardForm from '../components/CardForm' import * as ActionCreators from '../actions' import _ from 'underscore' function mapStateToProps (state, ownProps) { const card = _.find(state.cards, {id: ownProps.cardId}) return card ? card : {} } const CardFormWrapper = connect( mapStateToProps, dispatch => bindActionCreators(ActionCreators, dispatch) )(CardForm) export default CardFormWrapper
packages/linter-ui-default/lib/tooltip/message.js
luizpicolo/.atom
/* @flow */ import * as url from 'url' import React from 'react' import marked from 'marked' import { visitMessage, openExternally, openFile, applySolution, getActiveTextEditor, sortSolutions } from '../helpers' import type TooltipDelegate from './delegate' import type { Message, LinterMessage } from '../types' import FixButton from './fix-button' function findHref(el: ?Element): ?string { while (el && !el.classList.contains('linter-line')) { if (el instanceof HTMLAnchorElement) { return el.href } el = el.parentElement } return null } type Props = { message: Message, delegate: TooltipDelegate, } type State = { description?: string, descriptionShow?: boolean, } class MessageElement extends React.Component<Props, State> { state: State = { description: '', descriptionShow: false, } componentDidMount() { this.props.delegate.onShouldUpdate(() => { this.setState({}) }) this.props.delegate.onShouldExpand(() => { if (!this.state.descriptionShow) { this.toggleDescription() } }) this.props.delegate.onShouldCollapse(() => { if (this.state.descriptionShow) { this.toggleDescription() } }) } // NOTE: Only handling messages v2 because v1 would be handled by message-legacy component onFixClick(): void { const message = this.props.message const textEditor = getActiveTextEditor() if (message.version === 2 && message.solutions && message.solutions.length) { applySolution(textEditor, message.version, sortSolutions(message.solutions)[0]) } } openFile = (ev: Event) => { if (!(ev.target instanceof HTMLElement)) { return } const href = findHref(ev.target) if (!href) { return } // parse the link. e.g. atom://linter?file=<path>&row=<number>&column=<number> const { protocol, hostname, query } = url.parse(href, true) const file = query && query.file if (protocol !== 'atom:' || hostname !== 'linter' || !file) { return } const row = query && query.row ? parseInt(query.row, 10) : 0 const column = query && query.column ? parseInt(query.column, 10) : 0 openFile(file, { row, column }) } canBeFixed(message: LinterMessage): boolean { if (message.version === 1 && message.fix) { return true } else if (message.version === 2 && message.solutions && message.solutions.length) { return true } return false } toggleDescription(result: ?string = null) { const newStatus = !this.state.descriptionShow const description = this.state.description || this.props.message.description if (!newStatus && !result) { this.setState({ descriptionShow: false }) return } if (typeof description === 'string' || result) { const descriptionToUse = marked(result || description) this.setState({ descriptionShow: true, description: descriptionToUse }) } else if (typeof description === 'function') { this.setState({ descriptionShow: true }) if (this.descriptionLoading) { return } this.descriptionLoading = true new Promise(function(resolve) { resolve(description()) }) .then(response => { if (typeof response !== 'string') { throw new Error(`Expected result to be string, got: ${typeof response}`) } this.toggleDescription(response) }) .catch(error => { console.log('[Linter] Error getting descriptions', error) this.descriptionLoading = false if (this.state.descriptionShow) { this.toggleDescription() } }) } else { console.error('[Linter] Invalid description detected, expected string or function but got:', typeof description) } } props: Props descriptionLoading: boolean = false render() { const { message, delegate } = this.props return ( <linter-message class={message.severity} onClick={this.openFile}> {message.description && ( <a href="#" onClick={() => this.toggleDescription()}> <span className={`icon linter-icon icon-${this.state.descriptionShow ? 'chevron-down' : 'chevron-right'}`} /> </a> )} <linter-excerpt> {this.canBeFixed(message) && <FixButton onClick={() => this.onFixClick()} />} {delegate.showProviderName ? `${message.linterName}: ` : ''} {message.excerpt} </linter-excerpt>{' '} {message.reference && message.reference.file && ( <a href="#" onClick={() => visitMessage(message, true)}> <span className="icon linter-icon icon-alignment-aligned-to" /> </a> )} {message.url && ( <a href="#" onClick={() => openExternally(message)}> <span className="icon linter-icon icon-link" /> </a> )} {this.state.descriptionShow && ( <div dangerouslySetInnerHTML={{ __html: this.state.description || 'Loading...', }} className="linter-line" /> )} </linter-message> ) } } module.exports = MessageElement
client/index.js
LinearAtWorst/cogile
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import ReactRoutes from './routes/routes.js'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware()(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> {ReactRoutes} </Provider> , document.getElementById('app'));
examples/js/selection/externally-managed-selection.js
echaouchna/react-bootstrap-tab
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(100); export default class ExternallyManagedSelection extends React.Component { constructor(props) { super(props); this.state = { selected: [], currPage: 1 }; } render() { const { currPage } = this.state; const onRowSelect = ({ id }, isSelected) => { if (isSelected && this.state.selected.length !== 2) { this.setState({ selected: [ ...this.state.selected, id ].sort(), currPage: this.refs.table.state.currPage }); } else { this.setState({ selected: this.state.selected.filter(it => it !== id) }); } return false; }; const selectRowProp = { mode: 'checkbox', clickToSelect: true, onSelect: onRowSelect, selected: this.state.selected }; const options = { sizePerPageList: [ 5, 10, 15, 20 ], sizePerPage: 10, page: currPage, sortName: 'id', sortOrder: 'desc' }; return ( <BootstrapTable ref='table' data={ products } selectRow={ selectRowProp } pagination={ true } options={ options }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
examples/huge-apps/routes/Profile/components/Profile.js
dmitrigrabov/react-router
import React from 'react' class Profile extends React.Component { render() { return ( <div> <h2>Profile</h2> </div> ) } } export default Profile
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
kaizensauce/campari-app
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'));
js/components/tab/configTab.js
ChiragHindocha/stay_fit
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Container, Header, Title, Button, Icon, Tabs, Tab, Text, Right, Left, Body, TabHeading } from 'native-base'; import { Actions } from 'react-native-router-flux'; import { actions } from 'react-native-navigation-redux-helpers'; import myTheme from '../../themes/base-theme'; import TabOne from './tabOne'; import TabTwo from './tabTwo'; import TabThree from './tabThree'; const { popRoute, } = actions; class ConfigTab extends Component { // eslint-disable-line static propTypes = { popRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } popRoute() { this.props.popRoute(this.props.navigation.key); } render() { return ( <Container> <Header hasTabs> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="arrow-back" /> </Button> </Left> <Body> <Title> Advanced Tabs</Title> </Body> <Right /> </Header> <Tabs style={{ elevation: 3 }}> <Tab heading={<TabHeading><Icon name="camera" /><Text>Camera</Text></TabHeading>}> <TabOne /> </Tab> <Tab heading={<TabHeading><Text>No Icon</Text></TabHeading>}> <TabTwo /> </Tab> <Tab heading={<TabHeading><Icon name="apps" /></TabHeading>}> <TabThree /> </Tab> </Tabs> </Container> ); } } function bindAction(dispatch) { return { popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(ConfigTab);
app/javascript/mastodon/features/standalone/public_timeline/index.js
musashino205/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { expandPublicTimeline, expandCommunityTimeline } from 'mastodon/actions/timelines'; import Masonry from 'react-masonry-infinite'; import { List as ImmutableList, Map as ImmutableMap } from 'immutable'; import DetailedStatusContainer from 'mastodon/features/status/containers/detailed_status_container'; import { debounce } from 'lodash'; import LoadingIndicator from 'mastodon/components/loading_indicator'; const mapStateToProps = (state, { local }) => { const timeline = state.getIn(['timelines', local ? 'community' : 'public'], ImmutableMap()); return { statusIds: timeline.get('items', ImmutableList()), isLoading: timeline.get('isLoading', false), hasMore: timeline.get('hasMore', false), }; }; export default @connect(mapStateToProps) class PublicTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, statusIds: ImmutablePropTypes.list.isRequired, isLoading: PropTypes.bool.isRequired, hasMore: PropTypes.bool.isRequired, local: PropTypes.bool, }; componentDidMount () { this._connect(); } componentDidUpdate (prevProps) { if (prevProps.local !== this.props.local) { this._connect(); } } _connect () { const { dispatch, local } = this.props; dispatch(local ? expandCommunityTimeline() : expandPublicTimeline()); } handleLoadMore = () => { const { dispatch, statusIds, local } = this.props; const maxId = statusIds.last(); if (maxId) { dispatch(local ? expandCommunityTimeline({ maxId }) : expandPublicTimeline({ maxId })); } } setRef = c => { this.masonry = c; } handleHeightChange = debounce(() => { if (!this.masonry) { return; } this.masonry.forcePack(); }, 50) render () { const { statusIds, hasMore, isLoading } = this.props; const sizes = [ { columns: 1, gutter: 0 }, { mq: '415px', columns: 1, gutter: 10 }, { mq: '640px', columns: 2, gutter: 10 }, { mq: '960px', columns: 3, gutter: 10 }, { mq: '1255px', columns: 3, gutter: 10 }, ]; const loader = (isLoading && statusIds.isEmpty()) ? <LoadingIndicator key={0} /> : undefined; return ( <Masonry ref={this.setRef} className='statuses-grid' hasMore={hasMore} loadMore={this.handleLoadMore} sizes={sizes} loader={loader}> {statusIds.map(statusId => ( <div className='statuses-grid__item' key={statusId}> <DetailedStatusContainer id={statusId} compact measureHeight onHeightChange={this.handleHeightChange} /> </div> )).toArray()} </Masonry> ); } }
source/components/SectionPanel/Body.js
mikey1384/twin-kle
import React from 'react'; import PropTypes from 'prop-types'; import { stringIsEmpty } from 'helpers/stringHelpers'; Body.propTypes = { emptyMessage: PropTypes.string, searchQuery: PropTypes.string, isSearching: PropTypes.bool, isEmpty: PropTypes.bool, loadMoreButtonShown: PropTypes.bool, statusMsgStyle: PropTypes.string, content: PropTypes.node }; export default function Body({ emptyMessage, searchQuery, isSearching, isEmpty, statusMsgStyle, content, loadMoreButtonShown }) { return ( <div> {(!stringIsEmpty(searchQuery) && isSearching) || (isEmpty && !loadMoreButtonShown) ? ( <div className={statusMsgStyle}> {searchQuery && isSearching ? 'Searching...' : searchQuery ? 'No Results' : emptyMessage} </div> ) : ( content )} </div> ); }
src/svg-icons/navigation/close.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationClose = (props) => ( <SvgIcon {...props}> <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/> </SvgIcon> ); NavigationClose = pure(NavigationClose); NavigationClose.displayName = 'NavigationClose'; NavigationClose.muiName = 'SvgIcon'; export default NavigationClose;
src/svg-icons/av/note.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvNote = (props) => ( <SvgIcon {...props}> <path d="M22 10l-6-6H4c-1.1 0-2 .9-2 2v12.01c0 1.1.9 1.99 2 1.99l16-.01c1.1 0 2-.89 2-1.99v-8zm-7-4.5l5.5 5.5H15V5.5z"/> </SvgIcon> ); AvNote = pure(AvNote); AvNote.displayName = 'AvNote'; AvNote.muiName = 'SvgIcon'; export default AvNote;
Header.js
srserx/react-native-ui-common
import React from 'react'; import { View, Text } from 'react-native'; const Header = (props) => { const { viewStyle, textStyle } = styles; return ( <View style={viewStyle}> <Text style={textStyle}>{props.headerText}</Text> </View> ); }; const styles = { viewStyle: { backgroundColor: '#F8F8F8', justifyContent: 'center', alignItems: 'center', height: 60, paddingTop: 15, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.2, elevation: 2, position: 'relative' }, textStyle: { fontSize: 20 } }; export { Header };
test/ApiProvider.js
sborrazas/redux-apimap
import test from 'ava'; import React from 'react'; import TestUtils from 'react-addons-test-utils'; import spy from 'spy'; import './setupDom'; import createApi from '../src/createApi'; import ApiProvider from '../src/ApiProvider'; const api = createApi({}, {}); test('Enforce rendering a single child', (t) => { const cns = spy(console, 'error'); cns.mock(); t.notThrows(() => { TestUtils.renderIntoDocument( <ApiProvider api={api}> <div /> </ApiProvider>, ); }); t.is(cns.calls.length, 0); cns.reset(); cns.mock(); t.throws(() => { TestUtils.renderIntoDocument( <ApiProvider api={api}> <div /> </ApiProvider>, ); TestUtils.renderIntoDocument(<ApiProvider api={api} />); }); t.is(cns.calls.length, 1); cns.reset(); cns.mock(); t.throws(() => { TestUtils.renderIntoDocument( <ApiProvider api={api}> <div /> <div /> </ApiProvider>, ); }); t.is(cns.calls.length, 1); cns.restore(); });
src/js/containers/Dashboard/DashboardAssetsLayer/index.js
grommet/grommet-cms-boilerplate
/* @flow */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import Box from 'grommet/components/Box'; import Button from 'grommet/components/Button'; import Layer from 'grommet/components/Layer'; import { AssetTile } from 'grommet-cms/components/Dashboard'; import { getAssets } from 'grommet-cms/containers/Assets/actions'; import AssetForm from 'grommet-cms/containers/Dashboard/DashboardAssetPage'; import { PageHeader } from 'grommet-cms/components'; import type { Asset } from 'grommet-cms/containers/Assets/flowTypes'; type Props = { error: string, posts: Array<Asset>, request: boolean }; export class DashboardAssetsLayer extends Component { state: { addNewAsset: boolean }; _onAssetFormSubmit: () => void; _onAddAssetClick: () => void; constructor(props: Props) { super(props); this.state = { addNewAsset: false }; this._onAssetFormSubmit = this._onAssetFormSubmit.bind(this); this._onAddAssetClick = this._onAddAssetClick.bind(this); } componentDidMount() { this.props.dispatch(getAssets()); } _onAddAssetClick() { this.setState({ addNewAsset: true }); } _onAssetFormSubmit() { // Refresh Assets list. this.props.dispatch((getAssets())) .then(() => { this.setState({ addNewAsset: false }); }); } render() { const assets = ( this.props.posts && this.props.posts.length > 0 && !this.state.addNewAsset) ? this.props.posts.map(({_id, path, title}) => <AssetTile id={_id} title={title} path={path} key={`asset-${_id}`} size="small" showControls={false} onClick={this.props.onAssetSelect.bind(this, {_id, path, title})} />) : undefined; const assetForm = (this.state.addNewAsset) ? <AssetForm params={{ id: 'create' }} onSubmit={this._onAssetFormSubmit} /> : undefined; return ( <Layer flush={true} onClose={this.props.onClose}> <PageHeader title="Assets" controls={ <Box direction="row" pad={{ between: 'medium' }}> <Button onClick={this._onAddAssetClick}> Add Asset </Button> <Button onClick={this.props.onClose}> Exit </Button> </Box> } /> {assetForm} <Box full="horizontal" direction="row" pad="medium" justify="center" wrap={true}> {assets} </Box> </Layer> ); } }; function mapStateToProps(state, props) { const { error, posts, request } = state.assets; return { error, posts, request }; } export default connect(mapStateToProps)(DashboardAssetsLayer);
app/Calendar/__tests__/DayPicker.spec.js
sgrepo/react-calendar-multiday
// import React from 'react' // import Enzyme, {mount} from 'enzyme' // import Adapter from 'enzyme-adapter-react-16' // import Calendar from '../Calendar' // import DayWrapper from '../DayWrapper' // import toJson from 'enzyme-to-json' // import {equals, range, inc} from 'ramda' // import jsdom from 'jsdom' // Enzyme.configure({ adapter: new Adapter() }) // var exposedProperties = ['window', 'navigator', 'document'] // global.document = jsdom.jsdom('') // global.window = document.defaultView // Object.keys(document.defaultView).forEach((property) => { // if (typeof global[property] === 'undefined') { // exposedProperties.push(property) // global[property] = document.defaultView[property] // } // }) // global.navigator = { // userAgent: 'node.js', // } // // const dayPicker = mount(<Calendar />)
native/components/speechBubble/SpeechBubble.js
miukimiu/react-kawaii
import React from 'react'; import PropTypes from 'prop-types'; import paths from './paths'; import Face from '../common/face/Face'; import getUniqueId from '../../utils/getUniqueId'; import Wrapper from '../common/wrapper/Wrapper'; import Svg, { G, Path, Use, Defs, Mask } from 'react-native-svg'; const SpeechBubble = ({ size, color, mood, className }) => ( <Wrapper className={className}> <Svg width={size} height={size} version="1.1" viewBox="0 0 134 134" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" > <Defs> <Path d={paths.shape} id="kawaii-speechBubble__shape--path" /> <Path d={paths.shadow} id="kawaii-speechBubble__shadow--path" /> </Defs> <G id="Kawaii-speechBubble"> <G id="Kawaii-speechBubble__body"> <Mask fill="#fff"> <Use xlinkHref="#kawaii-speechBubble__shape--path" href="#kawaii-speechBubble__shape--path" /> </Mask> <Use id="Kawaii-speechBubble__shape" fill={color} xlinkHref="#kawaii-speechBubble__shape--path" href="#kawaii-speechBubble__shape--path" /> <Mask fill="#fff"> <Use xlinkHref="#kawaii-speechBubble__shadow--path" href="#kawaii-speechBubble__shadow--path" /> </Mask> <Use id="Kawaii-speechBubble__shadow" fill="#000" opacity=".1" xlinkHref="#kawaii-speechBubble__shadow--path" href="#kawaii-speechBubble__shadow--path" /> </G> <Face mood={mood} transform="translate(34 57)" uniqueId={getUniqueId()} /> </G> </Svg> </Wrapper> ); SpeechBubble.propTypes = { /** * Size of the width * */ size: PropTypes.number, mood: PropTypes.oneOf([ 'sad', 'shocked', 'happy', 'blissful', 'lovestruck', 'excited', 'ko' ]), /** * Hex color */ color: PropTypes.string }; SpeechBubble.defaultProps = { size: 150, mood: 'blissful', color: '#83D1FB' }; export default SpeechBubble;
src/app/development/DevelopmentTable.js
cityofasheville/simplicity2
import React from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; import AccessibleReactTable, { CellFocusWrapper } from 'accessible-react-table'; import expandingRows from '../../shared/react_table_hoc/ExpandingRows'; import DevelopmentDetail from './DevelopmentDetail'; import Icon from '../../shared/Icon'; import { IM_HOME2, IM_MAP5, IM_OFFICE, IM_DIRECTION, IM_LIBRARY2, IM_FIRE, IM_USERS4, IM_COOK, IM_CITY, LI_WALKING, IM_MUG } from '../../shared/iconConstants'; import createFilterRenderer from '../../shared/FilterRenderer'; const getIcon = (type, isExpanded) => { switch (type) { case 'Commercial': return <Icon path={IM_OFFICE} size={25} color={isExpanded ? '#fff' : '#4077a5'} />; case 'Residential': return <Icon path={IM_HOME2} size={25} color={isExpanded ? '#fff' : '#4077a5'} />; case 'Sign': return <Icon path={IM_DIRECTION} size={25} color={isExpanded ? '#fff' : '#4077a5'} />; case 'Historical': return <Icon path={IM_LIBRARY2} size={25} color={isExpanded ? '#fff' : '#4077a5'} />; case 'Fire': return <Icon path={IM_FIRE} size={25} color={isExpanded ? '#fff' : '#4077a5'} />; case 'Event-Temporary Use': return <Icon path={IM_USERS4} size={25} viewBox="0 0 24 24" color={isExpanded ? '#fff' : '#4077a5'} />; case 'Outdoor Vendor': return <Icon path={IM_COOK} size={25} color={isExpanded ? '#fff' : '#4077a5'} />; case 'Development': return <Icon path={IM_CITY} size={25} color={isExpanded ? '#fff' : '#4077a5'} />; case 'Right of Way': return <Icon path={LI_WALKING} size={25} viewBox="0 0 24 24" color={isExpanded ? '#fff' : '#4077a5'} />; case 'Over The Counter': return <Icon path={IM_MUG} size={25} color={isExpanded ? '#fff' : '#4077a5'} />; default: return <svg xmlns="http://www.w3.org/2000/svg" height="25px" transform="translate(0,4)" version="1.1" viewBox="0 0 16 16" width="25px"><g fill="none" fillRule="evenodd" id="Icons with numbers" stroke="none" strokeWidth="1"><g fill={isExpanded ? '#fff' : '#4077a5'} id="Group" transform="translate(-528.000000, -576.000000)"><path d="M536,592 C531.581722,592 528,588.418278 528,584 C528,579.581722 531.581722,576 536,576 C540.418278,576 544,579.581722 544,584 C544,588.418278 540.418278,592 536,592 Z M541,586 C542.10457,586 543,585.10457 543,584 C543,582.89543 542.10457,582 541,582 C539.89543,582 539,582.89543 539,584 C539,585.10457 539.89543,586 541,586 Z M531,586 C532.10457,586 533,585.10457 533,584 C533,582.89543 532.10457,582 531,582 C529.89543,582 529,582.89543 529,584 C529,585.10457 529.89543,586 531,586 Z M536,586 C537.10457,586 538,585.10457 538,584 C538,582.89543 537.10457,582 536,582 C534.89543,582 534,582.89543 534,584 C534,585.10457 534.89543,586 536,586 Z M536,586" id="Oval 12 copy" /></g></g></svg>; } }; const FilterRenderer = createFilterRenderer('Search...'); class DevelopmentTable extends React.Component { constructor(props) { super(props); this.state = { urlString: '', }; } componentDidMount() { this.setState({ urlString: [this.props.location.pathname, '?entity=', this.props.location.query.entity, '&id=', this.props.location.query.id, '&entities=', this.props.location.query.entities, '&label=', this.props.location.query.label, '&within=', document.getElementById('extent').value, '&during=', document.getElementById('time').value, '&hideNavbar=', this.props.location.query.hideNavbar, '&search=', this.props.location.query.search, '&view=map', '&x=', this.props.location.query.x, '&y=', this.props.location.query.y].join('') }) } render() { const ExpandableAccessibleReactTable = expandingRows(AccessibleReactTable); const dataColumns = [ { Header: 'Project', accessor: 'application_name', minWidth: 250, innerFocus: true, Cell: row => ( <CellFocusWrapper> {(focusRef, focusable) => ( <span> <span> {/*<a title="Click to show permit in map" href={[ this.state.urlString, '&zoomToPoint=', [row.original.y, row.original.x].join(','), ].join('')} style={{ color: row.isExpanded ? 'white' : '#4077a5' }} tabIndex={focusable ? 0 : -1} ref={focusRef} onClick={e => e.stopPropagation()} >*/} <Icon path={IM_MAP5} size={23} /> <span style={{ marginLeft: '5px' }}>{row.value}</span> {/*</a>*/} </span> </span> )} </CellFocusWrapper> ), Filter: FilterRenderer, }, { Header: 'Type', accessor: 'permit_type', minWidth: 150, Cell: row => ( <span> <span title={row.original.permit_type}>{getIcon(row.value, row.isExpanded)}</span> <span style={{ marginLeft: '5px' }}>{row.value}</span> </span> ), Filter: FilterRenderer, }, { Header: 'Contractor', accessor: 'contractor_name', minWidth: 150, Filter: FilterRenderer, }, { Header: 'Applied Date', id: 'applied_date', accessor: permit => (<span>{moment.utc(permit.applied_date).format('M/DD/YYYY')}</span>), width: 110, Filter: FilterRenderer, filterMethod: (filter, row) => { const id = filter.pivotId || filter.id; return row[id] !== undefined ? String(row[id].props.children).toLowerCase().indexOf(filter.value.toLowerCase()) > -1 : true; }, }, { Header: 'Permit #', accessor: 'permit_number', width: 115, Filter: FilterRenderer, }, ]; return ( <div> <div className="col-sm-12"> {this.props.data.length < 1 ? <div className="alert alert-info">No results found</div> : <div style={{ marginTop: '10px' }}> <ExpandableAccessibleReactTable ariaLabel="Development" data={this.props.data} columns={dataColumns} showPagination={this.props.data.length > 20} defaultPageSize={this.props.data.length <= 20 ? this.props.data.length : 20} filterable defaultFilterMethod={(filter, row) => { const id = filter.pivotId || filter.id; return row[id] !== undefined ? String(row[id]).toLowerCase().indexOf(filter.value.toLowerCase()) > -1 : true; }} getTdProps={() => { return { style: { whiteSpace: 'normal', }, }; }} getTrProps={(state, rowInfo) => { return { style: { cursor: 'pointer', background: rowInfo !== undefined && Object.keys(state.expanded).includes(rowInfo.viewIndex.toString()) && state.expanded[rowInfo.viewIndex] ? '#4077a5' : 'none', color: rowInfo !== undefined && Object.keys(state.expanded).includes(rowInfo.viewIndex.toString()) && state.expanded[rowInfo.viewIndex] ? '#fff' : '', fontWeight: rowInfo !== undefined && Object.keys(state.expanded).includes(rowInfo.viewIndex.toString()) && state.expanded[rowInfo.viewIndex] ? 'bold' : 'normal', fontSize: rowInfo !== undefined && Object.keys(state.expanded).includes(rowInfo.viewIndex.toString()) && state.expanded[rowInfo.viewIndex] ? '1.2em' : '1em', }, }; }} SubComponent={row => ( <div style={{ paddingLeft: '34px', paddingRight: '34px', paddingBottom: '15px', backgroundColor: '#f6fcff', borderRadius: '0px', border: '2px solid #4077a5', }} > <DevelopmentDetail data={row.original} standalone={false} /> </div> )} /> </div> } </div> </div> ); } } DevelopmentTable.propTypes = { data: PropTypes.array, // eslint-disable-line }; export default DevelopmentTable;
src/pages/client/listpage.js
vgarcia692/wutmi_frontend
import React from 'react'; import { Link } from 'react-router'; import { Table, Button, Row, Col } from 'react-bootstrap'; import styles from './style.css'; import CustomAxios from '../../common/components/CustomAxios'; import NewClientForm from '../../common/components/NewClientForm'; import LoadingGifModal from '../../common/components/LoadingGifModal'; import dateFormat from 'dateFormat'; export default class ClientListPage extends React.Component { constructor() { super() this.state = { data: [], modalShow: false, loadingShow: false } this.showModal = this.showModal.bind(this); this.closeModal = this.closeModal.bind(this); this.refreshData = this.refreshData.bind(this); this.showLoading = this.showLoading.bind(this); this.hideLoading = this.hideLoading.bind(this); } componentDidMount() { this.getData(); } getData() { this.showLoading(); const axios = CustomAxios.wAxios; axios.get('/basic_clients_data/') .then(function (response) { const results = response.data.results; var data = []; results.forEach(function(client,index) { data.push( <tr key={index}> <th>{index + 1}</th> <th><Link to={'/home/client/'+ client.pk} >{client.first_name + ' ' + client.last_name}</Link></th> <th>{client.atoll.name}</th> <th>{dateFormat(client.created_at, 'fullDate')}</th> </tr> ); }); this.setState({ data:data }); this.hideLoading(); }.bind(this)) .catch(function (error) { console.log(error); }); } showModal() { this.setState(() => ({ modalShow: true })) } closeModal() { this.setState(() => ({ modalShow: false })) } showLoading() { this.setState({ loadingShow: true }); } hideLoading() { this.setState({ loadingShow: false }); } refreshData() { this.setState(() => ({ modalShow: false })) // Refresh data from Database this.getData(); console.log('data refreshed'); } render() { return ( <div className={styles.content}> <h1 className={styles.heading}>Client Listing</h1> <Row> <Button bsStyle="success" className={styles.addButton} onClick={this.showModal}>+</Button> </Row> <Row> <Table striped bordered condensed hover responsive> <thead> <tr> <th>#</th> <th>Name</th> <th>Atoll</th> <th>Input Date</th> </tr> </thead> <tbody> {this.state.data} </tbody> </Table> </Row> <NewClientForm show={this.state.modalShow} onHide={this.closeModal} onAdd={()=>this.refreshData()} /> <LoadingGifModal show={this.state.loadingShow} onHide={this.hideLoading} label='Loading Clients...'/> </div> ); } }
components/menu/__test__/index.spec.js
showings/react-toolbox
import React from 'react'; import { shallow } from 'enzyme'; import { Menu } from '../Menu'; import { MenuItem } from '../MenuItem'; describe('MenuItem', () => { describe('#onClick', () => { it('passes to listener the event', () => { const onClick = jest.fn(); const wrapper = shallow( <Menu> <MenuItem key="1" onClick={onClick} /> </Menu>, ); wrapper.find(MenuItem).first().simulate('click', { persist: () => {} }); expect(onClick).toHaveBeenCalled(); }); }); });
src/svg-icons/device/add-alarm.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceAddAlarm = (props) => ( <SvgIcon {...props}> <path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm1-11h-2v3H8v2h3v3h2v-3h3v-2h-3V9z"/> </SvgIcon> ); DeviceAddAlarm = pure(DeviceAddAlarm); DeviceAddAlarm.displayName = 'DeviceAddAlarm'; export default DeviceAddAlarm;
app/components/events/comments/CommentList.js
alexko13/block-and-frame
import React from 'react'; import Comment from './CommentItem'; import moment from 'moment'; const CommentList = (props) => { return ( <div className="ui segment"> <div className="ui comments"> <h3 className="ui dividing header">Comments</h3> { props.commentData.map((comment) => { return ( <Comment username={comment.username} timeCreated={moment(comment.timeCreated).calendar()} text={comment.text} /> ); }) } <form className="ui reply form" onSubmit={props.preventDefaultSubmit} > <div className="field"> <label></label> <textarea rows="2" value={props.reply} onChange={props.handleReplyChange} ></textarea> </div> <div className="ui labeled submit icon button" onClick={props.handleSubmit} > <i className="icon edit"></i> Add Reply </div> </form> </div> </div> ); }; module.exports = CommentList;
app/javascript/plugins/email_pension/SelectTarget.js
SumOfUs/Champaign
import React, { Component } from 'react'; import { FormattedMessage } from 'react-intl'; import Input from '../../components/SweetInput/SweetInput'; import FormGroup from '../../components/Form/FormGroup'; class SelectTarget extends Component { constructor(props) { super(props); this.state = { searching: false, not_found: false, postcode: '', targets: [], }; } getTarget = postcode => { this.setState({ postcode: postcode }); if (!postcode) return; if (postcode.length < 5) return; this.setState({ searching: true, not_found: false }); fetch(`${this.props.endpoint}${postcode}`) .then(resp => { if (resp.ok) { return resp.json(); } throw new Error('not found.'); }) .then(json => { this.setState({ targets: json, searching: false }); const data = { postcode, targets: json }; this.props.handler(data); }) .catch(e => { this.setState({ not_found: true, targets: [], searching: false }); console.log('error', e); }); }; renderTarget({ id, title, first_name, last_name }) { return ( <p key={id}> {title} {first_name} {last_name} </p> ); } render() { let targets; if (this.state.not_found) { targets = ( <FormattedMessage id="email_tool.form.representative.not_found" defaultMessage="Sorry, we couldn't find a target with this location." /> ); } else { targets = this.state.targets.length ? ( this.state.targets.map(target => this.renderTarget(target)) ) : ( <FormattedMessage id="email_tool.form.representative.search_pending" defaultMessage="Please enter your postal code above." /> ); } return ( <div> <FormGroup> <Input name="postcode" type="text" label={ <FormattedMessage id="email_tool.form.representative.postal_code" defaultMessage="Enter your postal code" /> } value={this.state.postcode} onChange={value => this.getTarget(value)} errorMessage={this.props.error} /> </FormGroup> <FormGroup> <div className="target-panel"> <h3> <FormattedMessage id="email_tool.form.representative.selected_targets" defaultMessage="Representatives" /> </h3> <div className="target-panel-body"> {this.state.searching ? ( <FormattedMessage id="email_tool.form.representative.searching" defaultMessage="Searching for your representative" /> ) : ( targets )} </div> </div> </FormGroup> </div> ); } } export default SelectTarget;
packages/icons/src/md/action/SettingsBluetooth.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdSettingsBluetooth(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M23 48h4v-4h-4v4zm-8 0h4v-4h-4v4zm16 0h4v-4h-4v4zm5.41-36.59L27.83 20l8.58 8.59L25 40h-2V24.83L13.83 34 11 31.17 22.17 20 11 8.83 13.83 6 23 15.17V0h2l11.41 11.41zM27 7.66v7.51l3.76-3.75L27 7.66zm3.76 20.93L27 24.83v7.51l3.76-3.75z" /> </IconBase> ); } export default MdSettingsBluetooth;
src/js/components/icons/base/Diamond.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-diamond`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'diamond'); 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="M6,3 L18,3 L22,9 L12,21 L2,9 L6,3 Z M2,9 L22,9 M11,3 L7,9 L12,20 M13,3 L17,9 L12,20"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Diamond'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/select/multiselect/OptionGroupRenderer.js
sthomas1618/react-crane
import React from 'react' import PropTypes from 'prop-types' import { isValueEqual } from '../utils' function OptionGroupRenderer(props) { const { groupTitleKey, groupValueKey, option, optionDisabledKey, value, valueKey } = props const checked = value && value.length && value.some( (val) => isValueEqual(option, val, groupValueKey) || (option.options && option.options.length && option.options.some((opt) => isValueEqual(opt, val, valueKey))) ) const isDisabled = option[optionDisabledKey] const onChange = (e) => { e.preventDefault() } const controlId = `group-${option[groupValueKey]}` return ( <span> <label htmlFor={controlId}> <input id={controlId} checked={checked} disabled={isDisabled} onChange={onChange} type="checkbox" /> {option[groupTitleKey]} </label> </span> ) } OptionGroupRenderer.propTypes = { groupTitleKey: PropTypes.string.isRequired, groupValueKey: PropTypes.string.isRequired, option: PropTypes.object.isRequired, optionDisabledKey: PropTypes.string, value: PropTypes.oneOfType([ PropTypes.array, PropTypes.number, PropTypes.object, PropTypes.string ]).isRequired, valueKey: PropTypes.string.isRequired } OptionGroupRenderer.defaultProps = { optionDisabledKey: 'isDisabled' } export default OptionGroupRenderer
lib/ui/src/modules/ui/routes.js
jribeiro/storybook
import React from 'react'; import ReactDOM from 'react-dom'; import Layout from './containers/layout'; import LeftPanel from './containers/left_panel'; import DownPanel from './containers/down_panel'; import ShortcutsHelp from './containers/shortcuts_help'; import SearchBox from './containers/search_box'; export default function(injectDeps, { clientStore, provider, domNode }) { // generate preview const Preview = () => { const state = clientStore.getAll(); const preview = provider.renderPreview(state.selectedKind, state.selectedStory); return preview; }; const root = ( <div> <Layout leftPanel={() => <LeftPanel />} preview={() => <Preview />} downPanel={() => <DownPanel />} /> <ShortcutsHelp /> <SearchBox /> </div> ); ReactDOM.render(root, domNode); }
src/Parser/HolyPaladin/Modules/Talents/AuraOfMercy.js
Yuyz0112/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatNumber } from 'common/format'; import Module from 'Parser/Core/Module'; import AbilityTracker from 'Parser/Core/Modules/AbilityTracker'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; class AuraOfMercy extends Module { static dependencies = { abilityTracker: AbilityTracker, }; on_initialized() { if (!this.owner.error) { this.active = this.owner.selectedCombatant.hasTalent(SPELLS.AURA_OF_MERCY_TALENT.id); } } get healing() { const abilityTracker = this.abilityTracker; const getAbility = spellId => abilityTracker.getAbility(spellId); return (getAbility(SPELLS.AURA_OF_MERCY_HEAL.id).healingEffective + getAbility(SPELLS.AURA_OF_MERCY_HEAL.id).healingAbsorbed); } get hps() { return this.healing / this.owner.fightDuration * 1000; } suggestions(when) { when(this.auraOfSacrificeHps).isLessThan(30000) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>The healing done by your <SpellLink id={SPELLS.AURA_OF_SACRIFICE_TALENT.id} /> is low. Try to find a better moment to cast it or consider changing to <SpellLink id={SPELLS.AURA_OF_MERCY_TALENT.id} /> or <SpellLink id={SPELLS.DEVOTION_AURA_TALENT.id} /> which can be more reliable.</span>) .icon(SPELLS.AURA_OF_SACRIFICE_TALENT.icon) .actual(`${formatNumber(actual)} HPS`) .recommended(`>${formatNumber(recommended)} HPS is recommended`) .regular(recommended - 5000).major(recommended - 10000); }); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.AURA_OF_MERCY_TALENT.id} />} value={`${formatNumber(this.hps)} HPS`} label="Healing done" /> ); } statisticOrder = STATISTIC_ORDER.OPTIONAL(); } export default AuraOfMercy;
packages/core/admin/admin/src/content-manager/pages/EditSettingsView/components/ComponentFieldList.js
wistityhq/strapi
import React from 'react'; import PropTypes from 'prop-types'; import { Box } from '@strapi/design-system/Box'; import { Flex } from '@strapi/design-system/Flex'; import { Link } from '@strapi/design-system/Link'; import { Typography } from '@strapi/design-system/Typography'; import Cog from '@strapi/icons/Cog'; import { useIntl } from 'react-intl'; import get from 'lodash/get'; import { Grid, GridItem } from '@strapi/design-system/Grid'; import useLayoutDnd from '../../../hooks/useLayoutDnd'; import getTrad from '../../../utils/getTrad'; const ComponentFieldList = ({ componentUid }) => { const { componentLayouts } = useLayoutDnd(); const { formatMessage } = useIntl(); const componentData = get(componentLayouts, [componentUid], {}); const componentLayout = get(componentData, ['layouts', 'edit'], []); return ( <Box padding={3}> {componentLayout.map((row, index) => ( // eslint-disable-next-line react/no-array-index-key <Grid gap={4} key={index}> {row.map(rowContent => ( <GridItem key={rowContent.name} col={rowContent.size}> <Box paddingTop={2}> <Flex alignItems="center" background="neutral0" paddingLeft={3} paddingRight={3} height={`${32 / 16}rem`} hasRadius borderColor="neutral200" > <Typography textColor="neutral800">{rowContent.name}</Typography> </Flex> </Box> </GridItem> ))} </Grid> ))} <Box paddingTop={2}> <Link startIcon={<Cog />} to={`/content-manager/components/${componentUid}/configurations/edit`} > {formatMessage({ id: getTrad('components.FieldItem.linkToComponentLayout'), defaultMessage: "Set the component's layout", })} </Link> </Box> </Box> ); }; ComponentFieldList.propTypes = { componentUid: PropTypes.string.isRequired, }; export default ComponentFieldList;
pollard/components/SongInput.js
spencerliechty/pollard
import React, { Component } from 'react'; import classNames from 'classnames'; import mergeStyles from '../lib/mergeStyles'; export default class SongInput extends Component { handleChange(event) { this.props.updateSong({ idx: this.props.songIdx, key: this.props.label, val: event.target.value }); } render() { let gridStyle = mergeStyles({ marginTop: 5 }); let labelId = "label-" + this.props.label; return ( <div style={ gridStyle }> <div className="input-group"> <span className="input-group-addon" id={ labelId }>{ this.props.label }</span> <input type="text" tabIndex='2' className={ "form-control " + labelId } aria-describedby={ labelId } value={ this.props.val } onChange={ (e) => this.handleChange(e) } /> </div> </div> ); } }
src/svg-icons/file/file-download.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileFileDownload = (props) => ( <SvgIcon {...props}> <path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/> </SvgIcon> ); FileFileDownload = pure(FileFileDownload); FileFileDownload.displayName = 'FileFileDownload'; FileFileDownload.muiName = 'SvgIcon'; export default FileFileDownload;
src/components/Separator/Separator.js
jmoguelruiz/react-common-components
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class Separator extends Component{ getStyle(){ return { color : "#f4f5f8", margin: "20px -10px", width : "100%" }; } render(){ const { style } = this.props; return( <hr style = {style ? style : this.getStyle()}/> ); } } Separator.propTypes = { /** * Style */ style : PropTypes.object }; export default Separator;
docs/src/app/components/pages/components/TimePicker/ExampleSimple.js
barakmitz/material-ui
import React from 'react'; import TimePicker from 'material-ui/TimePicker'; const TimePickerExampleSimple = () => ( <div> <TimePicker hintText="12hr Format" /> <TimePicker format="24hr" hintText="24hr Format" /> <TimePicker disabled={true} format="24hr" hintText="Disabled TimePicker" /> </div> ); export default TimePickerExampleSimple;
src/Alert.js
erictherobot/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const Alert = React.createClass({ mixins: [BootstrapMixin], propTypes: { onDismiss: React.PropTypes.func, dismissAfter: React.PropTypes.number, closeLabel: React.PropTypes.string }, getDefaultProps() { return { bsClass: 'alert', bsStyle: 'info', closeLabel: 'Close Alert' }; }, renderDismissButton() { return ( <button type="button" className="close" onClick={this.props.onDismiss} aria-hidden="true"> <span>&times;</span> </button> ); }, renderSrOnlyDismissButton() { return ( <button type="button" className="close sr-only" onClick={this.props.onDismiss}> {this.props.closeLabel} </button> ); }, render() { let classes = this.getBsClassSet(); let isDismissable = !!this.props.onDismiss; classes['alert-dismissable'] = isDismissable; return ( <div {...this.props} role="alert" className={classNames(this.props.className, classes)}> {isDismissable ? this.renderDismissButton() : null} {this.props.children} {isDismissable ? this.renderSrOnlyDismissButton() : null} </div> ); }, componentDidMount() { if (this.props.dismissAfter && this.props.onDismiss) { this.dismissTimer = setTimeout(this.props.onDismiss, this.props.dismissAfter); } }, componentWillUnmount() { clearTimeout(this.dismissTimer); } }); export default Alert;
src/js/components/nodes/registerNodes/driverFields/DriverFields.js
knowncitizen/tripleo-ui
/** * Copyright 2017 Red Hat Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import { defineMessages, injectIntl } from 'react-intl'; import { Field } from 'redux-form'; import { format, required } from 'redux-form-validators'; import PropTypes from 'prop-types'; import React from 'react'; import HorizontalInput from '../../../ui/reduxForm/HorizontalInput'; import HorizontalTextarea from '../../../ui/reduxForm/HorizontalTextarea'; import { IPV4_REGEX, FQDN_REGEX, PORT_REGEX } from '../../../../utils/regex'; const messages = defineMessages({ ipOrFqdnValidatorMessage: { id: 'DriverFields.ipOrFqdnValidatorMessage', defaultMessage: 'Please enter a valid IPv4 Address or a valid FQDN.' }, portValidationMessage: { id: 'DriverFields.portValidationMessage', defaultMessage: 'Please enter valid Port number (0 - 65535)' } }); export const DriverFields = ({ addressLabel, intl: { formatMessage }, passwordLabel, portLabel, node, userLabel }) => ( <div> <Field name={`${node}.pm_addr`} component={HorizontalInput} id={`${node}.pm_addr`} label={addressLabel} validate={[ format({ with: new RegExp(IPV4_REGEX.source + '|' + FQDN_REGEX.source), message: formatMessage(messages.ipOrFqdnValidatorMessage) }), required() ]} required /> <Field name={`${node}.pm_port`} component={HorizontalInput} id={`${node}.pm_port`} label={portLabel} type="number" min={0} max={65535} validate={[ format({ with: PORT_REGEX, message: formatMessage(messages.portValidationMessage), allowBlank: true }) ]} /> <Field name={`${node}.pm_user`} component={HorizontalInput} id={`${node}.pm_user`} label={userLabel} validate={required()} required /> <Field name={`${node}.pm_password`} component={HorizontalTextarea} id={`${node}.pm_password`} label={passwordLabel} validate={required()} required /> </div> ); DriverFields.propTypes = { addressLabel: PropTypes.string.isRequired, intl: PropTypes.object.isRequired, node: PropTypes.string.isRequired, passwordLabel: PropTypes.string.isRequired, portLabel: PropTypes.string.isRequired, userLabel: PropTypes.string.isRequired }; export default injectIntl(DriverFields);
assets/javascripts/kitten/components/interaction/stepper/test.js
KissKissBankBank/kitten
import renderer from 'react-test-renderer' import React from 'react' import { Stepper } from './index' describe('NEXT // <Stepper />', () => { it('default item matches with snapshot', () => { const component = renderer .create( <Stepper> <Stepper.Item>Default Item</Stepper.Item> </Stepper>, ) .toJSON() expect(component).toMatchSnapshot() }) it('pointer item matches with snapshot', () => { const component = renderer .create( <Stepper> <Stepper.Item pointer>Default Item</Stepper.Item> </Stepper>, ) .toJSON() expect(component).toMatchSnapshot() }) it('progress item matches with snapshot', () => { const component = renderer .create( <Stepper> <Stepper.Item state="progress">Progress Item</Stepper.Item> </Stepper>, ) .toJSON() expect(component).toMatchSnapshot() }) it('validated item matches with snapshot', () => { const component = renderer .create( <Stepper> <Stepper.Item state="validated">Validated Item</Stepper.Item> </Stepper>, ) .toJSON() expect(component).toMatchSnapshot() }) it('default link matches with snapshot', () => { const component = renderer .create( <Stepper> <Stepper.Link href="https://www.kisskissbankbank.com"> Default Link </Stepper.Link> </Stepper>, ) .toJSON() expect(component).toMatchSnapshot() }) it('progress link matches with snapshot', () => { const component = renderer .create( <Stepper> <Stepper.Link href="https://www.kisskissbankbank.com" state="progress" > Progress Link </Stepper.Link> </Stepper>, ) .toJSON() expect(component).toMatchSnapshot() }) it('external link matches with snapshot', () => { const component = renderer .create( <Stepper> <Stepper.Link href="https://www.kisskissbankbank.com" external> External Item </Stepper.Link> </Stepper>, ) .toJSON() expect(component).toMatchSnapshot() }) it('link with linkProps matches with snapshot', () => { const component = renderer .create( <Stepper> <Stepper.Link href="https://www.kisskissbankbank.com" external linkProps={{ 'aria-current': 'page' }} > External Item </Stepper.Link> </Stepper>, ) .toJSON() expect(component).toMatchSnapshot() }) })
client/src/components/role/RoleUpdate.js
FlevianK/cp2-document-management-system
import React from 'react'; import { connect } from 'react-redux'; import { Link, browserHistory } from 'react-router'; import { bindActionCreators } from 'redux'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import RaisedButton from 'material-ui/RaisedButton'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import PropTypes from 'prop-types'; import toastr from 'toastr'; import { Input } from '../../containers'; import * as roleAction from '../../actions/roleAction'; import DashboardHeader from '../common/DashboardHeader'; export class RoleUpdate extends React.Component { /** * RoleUpdate class * It is for updating role description */ constructor(props) { super(props); this.state = { roles: { roleId: this.props.params.roleId }, open: true }; this.onRoleChange = this.onRoleChange.bind(this); this.onRoleUpdate = this.onRoleUpdate.bind(this); this.handleClose = this.handleClose.bind(this); } componentWillMount() { this.props.actions.loadRole(this.props.params); } componentWillReceiveProps(nextProps) { const role = nextProps.roles; this.setState({ roles: role }); } onRoleChange(event) { event.preventDefault(); const field = event.target.name; const roles = this.state.roles; roles[field] = event.target.value; return this.setState({ roles }); } onRoleUpdate(event) { event.preventDefault(); this.props.actions.updateRole(this.state.roles) .then(() => { this.setState({ open: false }); browserHistory.push('/roles'); }) .catch((error) => { toastr.error(error.response.data.message); }); } handleClose() { this.setState({ open: false }); browserHistory.push('/roles'); } render() { console.log(this.props, "llll") const { roles } = this.props; const actions = [ <FlatButton style={{ color: "red", margin: " 0 15% 0 15%", padding: " 0 4% 0 4% " }} label="Cancel" primary={true} onClick={this.handleClose} />, <FlatButton style={{ color: "green", margin: " 0 15% 0 15%", padding: " 0 4% 0 4% " }} label="Update" primary={true} keyboardFocused={true} onClick={this.onRoleUpdate} />]; return ( <div> <DashboardHeader /> <div> <MuiThemeProvider> <Dialog actions={actions} modal={false} open={this.state.open} onRequestClose={this.handleClose} > <div className="row"> <div className="col s10 offset-m1"> <p>Role: {this.state.roles.title}</p> </div> </div> <form> <Input name="description" label="Description" type="text" value={this.state.roles.description} onChange={this.onRoleChange} /> </form> </Dialog> </MuiThemeProvider> </div> </div> ); } } RoleUpdate.propTypes = { roles: PropTypes.object, actions: PropTypes.object, params: PropTypes.object, }; const mapStateToProps = (state, ownProps) => ({ roles: state.roles }); const mapDispatchToProps = dispatch => ({ actions: bindActionCreators(roleAction, dispatch) }); export default connect(mapStateToProps, mapDispatchToProps)(RoleUpdate);
app/main.js
mapbox/osm-comments-frontend
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Application'; import ContentContainer from './containers/Content'; import NotesList from './components/NotesList'; import ChangesetsList from './components/ChangesetsList'; import { Router, Route, IndexRoute, Redirect } from 'react-router'; import createHistory from 'history/lib/createHashHistory'; const history = createHistory({ queryKey: false }); const routes = ( <Router history={history}> <Redirect from="/" to="changesets/" /> <Route path="/" component={App}> <Route path="notes/" component={NotesList} /> <Route path="changesets/" component={ChangesetsList} /> </Route> </Router> ); ReactDOM.render(routes, document.getElementById('application'));
examples/with-yarn-workspaces/packages/bar/index.js
BlancheXu/test
import React from 'react' const Bar = () => <strong>bar</strong> export default Bar
docs/client/components/pages/Image/gettingStarted.js
koaninc/draft-js-plugins
// It is important to import the Editor which accepts plugins. // eslint-disable-next-line import/no-unresolved import Editor from 'draft-js-plugins-editor'; // eslint-disable-next-line import/no-unresolved import createImagePlugin from 'draft-js-image-plugin'; import React from 'react'; const imagePlugin = createImagePlugin(); // The Editor accepts an array of plugins. In this case, only the imagePlugin // is passed in, although it is possible to pass in multiple plugins. const MyEditor = ({ editorState, onChange }) => ( <Editor editorState={editorState} onChange={onChange} plugins={[imagePlugin]} /> ); export default MyEditor;
lib/FocusTrap.js
danauclair/react-hotkeys
import React from 'react'; const FocusTrap = React.createClass({ propTypes: { onFocus: React.PropTypes.func, onBlur: React.PropTypes.func, focusName: React.PropTypes.string, // Currently unused component: React.PropTypes.any }, getDefaultProps() { return { component: 'div' } }, render() { const Component = this.props.component; return ( <Component tabIndex="-1" {...this.props}> {this.props.children} </Component> ); } }); export default FocusTrap;
src/components/NotFoundPage.js
mgavaudan/react-hack
import React from 'react'; import { Link } from 'react-router'; const NotFoundPage = () => { return ( <div> <h4> 404 Page Not Found </h4> <Link to='/'> Go back to homepage </Link> </div> ); }; export default NotFoundPage;
src/PageHeader.js
blue68/react-bootstrap
import React from 'react'; import classNames from 'classnames'; const PageHeader = React.createClass({ render() { return ( <div {...this.props} className={classNames(this.props.className, 'page-header')}> <h1>{this.props.children}</h1> </div> ); } }); export default PageHeader;
webpack/withProtectedView.js
theforeman/foreman_templates
import React from 'react'; // TODO: extract to core const withProtectedView = ( ProtectedComponent, ProtectionComponent, protectionFn, extraProtectionProps = {} ) => props => protectionFn(props) ? ( <ProtectedComponent {...props} /> ) : ( <ProtectionComponent {...props} {...extraProtectionProps} /> ); export default withProtectedView;
app/jsx/assignments_2/student/components/Context.js
djbender/canvas-lms
/* * Copyright (C) 2019 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' export const StudentViewContextDefaults = { // Controls for moving back and forth between displayed submissions nextButtonAction: () => {}, nextButtonEnabled: false, prevButtonAction: () => {}, prevButtonEnabled: false, startNewAttemptAction: () => {}, // Used to display the most current grade in the header, regardless of the // current attempt being displayed in the student view latestSubmission: {} } const StudentViewContext = React.createContext(StudentViewContextDefaults) export default StudentViewContext
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ClassProperties.js
liamhu/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; users = [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, ]; componentDidMount() { this.props.onReady(); } render() { return ( <div id="feature-class-properties"> {this.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
front/components/navbar/navbar.js
bigkangtheory/wanderly
import React, { Component } from 'react'; import { Link } from 'react-router'; import '../../styles/navbar.css'; class Navbar extends Component { constructor(props) { super(props); } handleClick = () => { this.props.action() } render() { const { pathname } = this.props.routing if(pathname === '/') { return ( <div className='loggedout-navbar navbar'> <div className="parent-logo"> <div className='logo-nav '></div> </div> <div className='buttons'> <button className='login-link button-log one' onClick={this.props.loginPop}>Login</button> </div> </div> ) } else { return ( <div className='login-navbar navbar'> <div className="parent-logo"> <div className='logo-nav '></div> </div> <div className="dropdown buttons"> <div id='name-nav'> <button className="dropbtn button-log">{this.props.profile.first_name}</button> <div className='arrow-down'></div> </div> <div className="dropdown-content button-log"> <button className='logout' onClick={this.handleClick}>Log out</button> </div> </div> </div> ) } } } export default Navbar
src/components/artboard/ArtBoardTabs.js
justinyueh/express-react
import { Router, Route, IndexRoute, Redirect, Link, browserHistory } from 'react-router' import React from 'react' import SysTpl from './artboardtabs/SysTpl' export default class ArtBoardTabs extends React.Component { constructor() { super(); this.addTpl = this.addTpl.bind(this); this.state = { activeId: 0, tabs: [ {name: '系统模版', id: 0, icon: 'fa-paper-plane', children: <SysTpl addTpl={this.addTpl} />}, {name: '草稿箱', id: 1, icon: 'fa-archive'} ] } this.handleTabClick = this.handleTabClick.bind(this); } addTpl(tpl) { this.props.addTpl(tpl); } handleTabClick(tab) { return () => { if (tab.id != this.state.activeId) { this.setState({ activeId: tab.id }); } } } render() { let createItem = (tab) => { let className = 'item'; if (tab.id == this.state.activeId) { this.children = tab.children; className = 'item active'; } return ( <li key={tab.id} className={className} onClick={this.handleTabClick(tab)} > <i className={'fa ' + tab.icon}></i><span className="title">{tab.name}</span> </li> ) } return ( <aside className="sidebar"> <ul className="tabs">{this.state.tabs.map(createItem)}</ul> <div className="tab-body"> {this.children} </div> </aside> ) } }
frontend/src/Components/Table/VirtualTableHeader.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React from 'react'; import styles from './VirtualTableHeader.css'; function VirtualTableHeader({ children }) { return ( <div className={styles.header}> {children} </div> ); } VirtualTableHeader.propTypes = { children: PropTypes.node }; export default VirtualTableHeader;
src/app/tabela.js
hugotacito/tabelaebtt
import React from 'react'; import {Navbar, Grid, Row, Col} from 'react-bootstrap'; import {Formulario} from './form'; import {Resultado} from './resultado'; export class Tabela extends React.Component { constructor(props) { super(props); this.state = { formData: {} }; this.handleUserInput = this.handleUserInput.bind(this); } handleUserInput(data) { this.setState({formData: data.formData}); } render() { return ( <div> <Navbar> <Navbar.Header> <Navbar.Brand> <a href="#">Simulador EBTT</a> </Navbar.Brand> </Navbar.Header> </Navbar> <Grid> <Row className="show-grid"> <Col xs={12} md={6}> <Formulario formData={this.state.formData} onUserInput={this.handleUserInput}/> </Col> <Col xs={12} md={6}> <Resultado formData={this.state.formData} onUserInput={this.handleUserInput}/> </Col> </Row> </Grid> </div> ); } }