path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
src/svg-icons/image/brightness-7.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBrightness7 = (props) => ( <SvgIcon {...props}> <path d="M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6zm0-10c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z"/> </SvgIcon> ); ImageBrightness7 = pure(ImageBrightness7); ImageBrightness7.displayName = 'ImageBrightness7'; export default ImageBrightness7;
examples/custom-server-micro/pages/index.js
nelak/next.js
import React from 'react' import Link from 'next/link' export default () => ( <ul> <li><Link href='/b' as='/a'><a>a</a></Link></li> <li><Link href='/a' as='/b'><a>b</a></Link></li> </ul> )
src/mention/__tests__/fixtures/initializeEditor.js
catalinmiron/react-tinymce-mention
import 'babel/polyfill'; import React from 'react'; import TinyMCE from 'react-tinymce'; import Mention from '../../Mention'; import simpleDataSource from './simple'; const plugins = [ 'autolink', 'autoresize', 'code', 'image', 'link', 'media', 'mention', 'tabfocus' ]; export default function initializeEditor() { var domNode = createContainer(); React.render( <div> <TinyMCE content={''} config={{ extended_valid_elements: 'blockquote[dir|style|cite|class|dir<ltr?rtl],iframe[src|frameborder|style|scrolling|class|width|height|name|align],pre', menubar: false, plugins: plugins.join(','), skin: 'kindling', statusbar: false, theme: 'kindling', toolbar: 'bold italic underline strikethrough | bullist numlist blockquote | link unlink | image media | removeformat code' }} /> <Mention dataSource={simpleDataSource} delimiter={'@'} /> </div> , domNode); return window.tinymce; } function createContainer() { const root = document.createElement('div'); const id = 'root'; root.setAttribute('id', id); document.body.appendChild(root); return document.getElementById(id); }
src/components/soporte/chat_servidor.js
bombe-software/demos
//NPM packages import React, { Component } from 'react'; import { connect } from "react-redux"; //Actions import { fetchConversaciones } from "../../actions"; //Components import Chat from "./chat"; /** * @class ChatServidor * @author Vicroni <[email protected]> * @author Someone <none> * @version 1.0 <1/12/17> * @description: * El objetivo de la clase es contolar el * aspecto grafico del chat servidor */ class ChatServidor extends Component { /** * Inicializa el state en donde se colocan * el @const id_externo en donde se pone la * que esta teniendo lugar * @constructor */ constructor(props) { super(props); this.state = { id_externo: 0 }; } /** * Carga de manera logica las conversaciones y * renderiza el conmportamiento grafico * @method componentDidMount * @function props.fetchConversaciones Llamada ajax para obtener las conversaciones */ componentDidMount() { this.props.fetchConversaciones(this.props.id_local) } /** * Enlista las conversaciones de manera grafica * @method listConversaciones * @param conversaciones Un array con todas las conversaciones */ listConversaciones(conversaciones) { return _.map(conversaciones, conversacion => { return ( <div key={conversacion.id_remitente} onClick={() => { this.updateIdExterno(conversacion.id_remitente) }}> <div className="panel-block"> {conversacion.nombre_usuario} </div> </div> ); }); } updateIdExterno(id) { this.setState({ id_externo: id }); } /** * Es una forma de capturar cualquier error en la clase * y que este no crashe el programa, ayuda con la depuracion * de errores * @method componentDidCatch * @const info Es más informacion acerca del error * @const error Es el titulo del error */ componentDidCatch(error, info) { console.log("Error: " + error); console.log("Info: " + info); } render() { return ( <div className="hero"> <div className="columns"> <div className="column is-2-desktop is-4-tablet is-offset-2-desktop is-offset-1-tablet is-10-mobile is-offset-1-mobile"> <div className="panel user-list"> <div className="panel-heading">Usuarios</div> {this.listConversaciones(this.props.conversaciones)} </div> </div> <div className="column is-6-desktop is-6-tablet is-10-mobile is-offset-1-mobile"> <Chat id_local={this.props.id_local} id_externo={this.state.id_externo} /> </div> </div> </div> ); } } function mapStateToProps(state) { return { conversaciones: state.mensajes.conversaciones }; } export default connect(mapStateToProps, { fetchConversaciones })(ChatServidor);
message/src/MessageBox.js
zhufengnodejs/201701node
import React, { Component } from 'react'; import 'bootstrap/dist/css/bootstrap.css' class MessageBox extends Component { render() { return ( <div className="panel panel-default"> <div className="panel-heading"> <h3 className="text-center">珠峰留言板</h3> </div> <div className="panel-body"> <ul className="list-group"> <li className="list-group-item"> 张三:今天下雨 <span className="pull-right">2017年5月23日10:07:59</span> </li> </ul> </div> <div className="panel-footer"> <form> <div className="form-group"> <label htmlFor="name">姓名</label> <input type="text" className="form-control" id="name" placeholder="姓名"/> </div> <div className="form-group"> <label htmlFor="content">内容</label> <textarea className="form-control" id="content" cols="30" rows="10"></textarea> </div> <div className="container"> <button type="submit" className="btn btn-primary">提交</button> </div> </form> </div> </div> ); } } export default MessageBox;
src/scripts/views/DataView.js
recordbleach/recordBleach_front_end
import React from 'react' import Header from './header' import Footer from './footer' import ACTIONS from '../actions' import $ from 'jquery' const DataInputView = React.createClass({ render: function() { return( <div className = 'dataInputView'> <Header/> <Petition /> <Footer /> </div> ) } }) const Petition = React.createClass({ getInitialState: function(){ return { setProfileClass: "untoggled", profileButtonSymbol: "+", setArrestClass: "untoggled", arrestButtonSymbol: "+", setChargeClass: "untoggled", chargeButtonSymbol: "+", setOverturnClass: "untoggled", overturnButtonSymbol: "+", setAgencyClass: "untoggled", agencyButtonSymbol: "+" } }, _toggleProfileButton: function(){ this.setState({ setProfileClass:this.state.profileButtonSymbol === '+' ? 'toggled' : 'untoggled', profileButtonSymbol: this.state.profileButtonSymbol === '+' ? '-' : '+' }) }, _toggleArrestButton: function(){ this.setState({ setArrestClass:this.state.arrestButtonSymbol === '+' ? 'toggled' : 'untoggled', arrestButtonSymbol: this.state.arrestButtonSymbol === '+' ? '-' : '+' }) }, _toggleChargeButton: function(){ this.setState({ setChargeClass:this.state.chargeButtonSymbol === '+' ? 'toggled' : 'untoggled', chargeButtonSymbol: this.state.chargeButtonSymbol === '+' ? '-' : '+' }) }, _toggleOverturnButton: function(){ this.setState({ setOverturnClass:this.state.overturnButtonSymbol === '+' ? 'toggled' : 'untoggled', overturnButtonSymbol: this.state.overturnButtonSymbol === '+' ? '-' : '+' }) }, _toggleAgencyButton: function(){ this.setState({ setAgencyClass:this.state.agencyButtonSymbol === '+' ? 'toggled' : 'untoggled', agencyButtonSymbol: this.state.agencyButtonSymbol === '+' ? '-' : '+' }) }, _handleRadioInput: function(inputArray) { for(var i = 0; i < inputArray.length; i++) { var genderObj = inputArray[i] if(genderObj.checked) { return genderObj.value } } }, _formatDate: function(dateString) { var splitDateArray = dateString.split('-') var formattedDateString = splitDateArray.join('') var formattedDateNumber = parseInt(formattedDateString) return formattedDateNumber }, _courtBool: function(courtInputArray) { var courtObj = { county: false, municipal: false, district: false } for(var i = 0; i < courtInputArray.length; i++) { var courtInputObj = courtInputArray[i] if(courtInputObj.checked) { var courtTrueValue = courtInputObj.value } } for(var prop in courtObj) { if(prop === courtTrueValue) { courtObj[prop] = true } } return courtObj }, _handleSaveAndLogout: function(evt) { evt.preventDefault() this._handlePetitionSubmit(evt) ACTIONS._logoutUser() }, _handleSubmitAndDestroy: function(evt) { console.log(evt) evt.preventDefault() // this._handlePetitionSubmit(evt) ACTIONS._destroyUser() }, _handlePetitionSubmit: function(evt) { evt.preventDefault() ACTIONS._submitPetition({ legal_name: document.getElementsByClassName('legalName')[0].value, dob: this._formatDate(document.getElementsByClassName('dob')[0].value), ssn: document.getElementsByClassName('ssn')[0].value, dl: document.getElementsByClassName('dl')[0].value, address: document.getElementsByClassName('currentAddress')[0].value, city: document.getElementsByClassName('currentCity')[0].value, state: document.getElementsByClassName('currentState')[0].value, county: document.getElementsByClassName('currentCounty')[0].value, zip: document.getElementsByClassName('currentZip')[0].value, sex: this._handleRadioInput(document.getElementsByClassName('gender')), race: this._handleRadioInput(document.getElementsByClassName('race')), offense_date:this._formatDate(document.getElementsByClassName('offenseDate')[0].value), offense_county: document.getElementsByClassName('arrestCounty')[0].value, arresting_agency: document.getElementsByClassName('arrestingAgency')[0].value, arrest_date: this._formatDate(document.getElementsByClassName('arrestDate')[0].value), a_address: document.getElementsByClassName('TOAAddress')[0].value, a_city: document.getElementsByClassName('TOACity')[0].value, a_state: document.getElementsByClassName('TOAState')[0].value, a_county: document.getElementsByClassName('TOACounty')[0].value, charged: this._handleRadioInput(document.getElementsByClassName('charged')), charge_date:this._formatDate(document.getElementsByClassName('chargeDate')[0].value), charged_offenses: document.getElementsByClassName('offenses')[0].value, charge_cause_number: document.getElementsByClassName('cause')[0].value, court_name: document.getElementsByClassName('courtName')[0].value, court_city: document.getElementsByClassName('courtCity')[0].value, court_county: document.getElementsByClassName('courtCounty')[0].value, county_court_at_law: this._courtBool(document.getElementsByClassName('court')).county, municipal_court: this._courtBool(document.getElementsByClassName('court')).municipal, district_court: this._courtBool(document.getElementsByClassName('court')).district, acquittal: this._handleRadioInput(document.getElementsByClassName('acquittal')), acquittal_date:this._formatDate(document.getElementsByClassName('acquittalDate')[0].value), dismissal: this._handleRadioInput(document.getElementsByClassName('dismiss')), dismissal_date:this._formatDate(document.getElementsByClassName('dismissDate')[0].value), convicted: this._handleRadioInput(document.getElementsByClassName('convicted')), conviction_date:this._formatDate(document.getElementsByClassName('convictionDate')[0].value), pardon:this._handleRadioInput(document.getElementsByClassName('pardon')), pardon_date:this._formatDate(document.getElementsByClassName('pardonDate')[0].value), overturned:this._handleRadioInput(document.getElementsByClassName('overturn')), overturned_date:this._formatDate(document.getElementsByClassName('overturnDate')[0].value), probation:this._handleRadioInput(document.getElementsByClassName('overturn')), deferred_adjudication:this._handleRadioInput(document.getElementsByClassName('adjudication')), user_id: parseInt(localStorage.currentUser) }) }, render: function() { var toggleProfileClass = { className: this.state.setProfileClass } var toggleArrestClass = { className: this.state.setArrestClass } var toggleChargeClass = { className: this.state.setChargeClass } var toggleOverturnClass = { className: this.state.setOverturnClass } var toggleAgencyClass = { className: this.state.setAgencyClass } return( <div className = 'petition'> <form> {/* PERSONAL PROFILE*/} <h3 onClick={this._toggleProfileButton}>{this.state.profileButtonSymbol} Personal Profile</h3> <div id = 'profile' className={toggleProfileClass.className}> <p>Full legal name:</p><input type ='text' className = 'legalName'/> <p>Date of birth:</p><input type = 'date' className = 'dob'/> <p>Social Security Number (include dashes):</p><input type = 'password' className = 'ssn' /> <p>Driver's License (leave blank if not applicable):</p><input type = 'text' className = 'dl' /> <p>Race:</p> <input type = 'radio' className = 'race' value = 'Hispanic or Latino' />Hispanic or Latino <br /> <input type = 'radio' className = 'race' value = 'American Indian or Alaska Native' />American Indian or Alaska Native <br /> <input type = 'radio' className = 'race' value = 'Asian' />Asian <br /> <input type = 'radio' className = 'race' value = 'Black or African American' />Black or African American <br /> <input type = 'radio' className = 'race' value = 'Native Hawaiian or Other Pacific Islander' />Native Hawaiian or Other Pacific Islander <br /> <input type = 'radio' className = 'race' value = 'White' />White <br /> <p>Gender:</p> <input type = 'radio' value = 'male' className = 'gender' name = 'gender'/>Male<br/> <input type = 'radio' value = 'female' className = 'gender' name = 'gender'/>Female <div className = 'address'>Current address: <input type = 'text' placeholder = 'address' className = 'currentAddress'/> <input type = 'text' placeholder = 'city' className = 'currentCity'/> <input type = 'text' placeholder = 'state' className = 'currentState'/> <input type = 'text' placeholder = 'zipcode' className = 'currentZip'/> <input type = 'text' placeholder = 'county' className = 'currentCounty'/> </div> </div> {/* ARREST PROFILE*/} <h3 onClick={this._toggleArrestButton}>{this.state.arrestButtonSymbol}Arrest</h3> <div id = 'arrest' className={toggleArrestClass.className}> <div className = 'address'>Address at time of the arrest: <input type = 'text' placeholder = 'address' className = 'TOAAddress'/> <input type = 'text' placeholder = 'city' className = 'TOACity'/> <input type = 'text' placeholder = 'state' className = 'TOAState'/> <input type = 'text' placeholder = 'zipcode' className = 'TOAZip'/> <input type = 'text' placeholder = 'county' className = 'TOACounty'/> </div> <p>Date of the offense (may be different than the date of the arrest):</p><input type = 'date' className = 'offenseDate'/> <p>Date of the arrest:</p><input type = 'date' className = 'arrestDate'/> <p>Location of the arrest: <input type = 'text' placeholder = 'city' className = 'arrestCity'/><br/> <input type = 'text' placeholder = 'county' className = 'arrestCounty'/> </p> <p>Agency that arrested you:</p><input type = 'text' className = 'arrestingAgency'/> <p>Arrest Offense (exactly as it is written on your record):</p><input type = 'text' className = 'arrestOffense' /> </div> {/* CHARGE PROFILE*/} <h3 onClick={this._toggleChargeButton}>{this.state.chargeButtonSymbol}Charge</h3> <div id = 'charge' className={toggleChargeClass.className}> <p>Charged:</p> <input type = 'radio' className = 'charged' value = 'yes'/>Yes<br/> <input type = 'radio' className = 'charged' value = 'no'/>No <p>Date of charge:</p><input type = 'date' className = 'chargeDate'/> <p>List all the offenses:</p> <textarea placeholder = 'Offenses' className = 'offenses'></textarea> <p>Court where charges were filed:</p> County: <input type = 'text' className = 'courtCounty'/> City: <input type = 'text' className = 'courtCity'/> Name: <input type = 'text' className = 'courtName'/> <p>Court Type:</p> <input type = 'radio' className = 'court' value = 'county'/>County<br/> <input type = 'radio' className = 'court' value = 'municipal'/>Municipal<br/> <input type = 'radio' className = 'court' value = 'district'/>District <p>Cause # (exactly as written on criminal history):</p><input type = 'text' className = 'cause' /> </div> {/* OVERTURN PROFILE*/} <h3 onClick={this._toggleOverturnButton}>{this.state.overturnButtonSymbol}Disposition</h3> <div id = 'overturn' className={toggleOverturnClass.className}> <p>Convicted:</p> <input type = 'radio' className = 'convicted' value = 'yes' name = 'convicted'/>Yes<br/> <input type = 'radio' className = 'convicted' value = 'no' name = 'convicted'/>No<br/> <input type = 'date' className = 'convictionDate' /> <p>Dismissed:</p> <input type = 'radio' className = 'dismiss' value = 'yes' name = 'dismiss'/>Yes<br/> <input type = 'radio' className = 'dismiss' value = 'no' name = 'dismiss'/>No<br/> <input type = 'date' className = 'dismissDate' /> <p>Pardoned:</p> <input type = 'radio' className = 'pardon' value = 'yes' name = 'pardon'/>Yes<br/> <input type = 'radio' className = 'pardon' value = 'no' name = 'pardon'/>No<br/> <input type = 'date' className = 'pardonDate' /> <p>Overturned:</p> <input type = 'radio' className = 'overturn' value = 'yes' name = 'overturn'/>Yes<br/> <input type = 'radio' className = 'overturn' value = 'no' name = 'overturn'/>No<br/> <input type = 'date' className = 'overturnDate' /> <p>Acquitted:</p> <input type = 'radio' className = 'acquittal' value = 'yes' name = 'acquittal'/>Yes<br/> <input type = 'radio' className = 'acquittal' value = 'no' name = 'acquittal'/>No<br/> <input type = 'date' className = 'acquittalDate' /> <p>Assigned Probation:</p> <input type = 'radio' className = 'probation' value = 'yes' name = 'probation'/>Yes<br/> <input type = 'radio' className = 'probation' value = 'no' name = 'probation'/>No <p>Assigned Deferred Adjudication:</p> <input type = 'radio' className = 'adjudication' value = 'yes' name = 'adjudication' />Yes<br/> <input type = 'radio' className = 'adjudication' value = 'no' name = 'adjudication'/>No </div> {/* AGENCY PROFILE*/} <h3 onClick={this._toggleAgencyButton}>{this.state.agencyButtonSymbol}Agency</h3> <div id = 'agency' className={toggleAgencyClass.className}>Address of arresting agency: <input type = 'text' placeholder = 'address' className = 'agency'/> <input type = 'text' placeholder = 'city' className = 'agency'/> <input type = 'text' placeholder = 'state' className = 'agency'/> <input type = 'text' placeholder = 'zipcode' className = 'agency'/> <input type = 'text' placeholder = 'county' className = 'agency'/> </div> <p>ONCE YOU HIT SUBMIT YOUR FORMS WILL BE GENERATED AND EMAILED TO THE ADDRESS YOU PROVIDED. ALL INFORMATION WILL BE REMOVED FROM THIS SITE</p> <button type= 'submit' onClick = {this._handleSubmitAndDestroy}>Submit</button> <button type= 'submit' onClick = {this._handleSaveAndLogout}>Save and Logout</button> </form> </div> ) } }) export default DataInputView
src/svg-icons/action/supervisor-account.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSupervisorAccount = (props) => ( <SvgIcon {...props}> <path d="M16.5 12c1.38 0 2.49-1.12 2.49-2.5S17.88 7 16.5 7C15.12 7 14 8.12 14 9.5s1.12 2.5 2.5 2.5zM9 11c1.66 0 2.99-1.34 2.99-3S10.66 5 9 5C7.34 5 6 6.34 6 8s1.34 3 3 3zm7.5 3c-1.83 0-5.5.92-5.5 2.75V19h11v-2.25c0-1.83-3.67-2.75-5.5-2.75zM9 13c-2.33 0-7 1.17-7 3.5V19h7v-2.25c0-.85.33-2.34 2.37-3.47C10.5 13.1 9.66 13 9 13z"/> </SvgIcon> ); ActionSupervisorAccount = pure(ActionSupervisorAccount); ActionSupervisorAccount.displayName = 'ActionSupervisorAccount'; ActionSupervisorAccount.muiName = 'SvgIcon'; export default ActionSupervisorAccount;
src/components/panels/index.js
mr47/react-redux-kit
/** * Created by mr470 on 02.04.2016. */ "use strict"; import React, { Component } from 'react'; class LeftPanel extends Component{ render() { const { children } = this.props; return ( <div className="column column-25"> {children} </div> ); } } class RightPanel extends Component{ render() { const { children } = this.props; return ( <div className="column column-75"> {children} </div> ); } } export { RightPanel, LeftPanel }
src/pages/chou-chou.js
vitorbarbosa19/ziro-online
import React from 'react' import BrandGallery from '../components/BrandGallery' export default () => ( <BrandGallery brand='Chou Chou' /> )
client/src/screens/new-group.screen.js
srtucker22/chatty
import { _ } from 'lodash'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { ActivityIndicator, Button, Image, StyleSheet, Text, View, } from 'react-native'; import { graphql, compose } from 'react-apollo'; import AlphabetListView from 'react-native-alpha-listview'; import update from 'immutability-helper'; import Icon from 'react-native-vector-icons/FontAwesome'; import { connect } from 'react-redux'; import SelectedUserList from '../components/selected-user-list.component'; import USER_QUERY from '../graphql/user.query'; // eslint-disable-next-line const sortObject = o => Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {}); const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', }, cellContainer: { alignItems: 'center', flex: 1, flexDirection: 'row', flexWrap: 'wrap', paddingHorizontal: 12, paddingVertical: 6, }, cellImage: { width: 32, height: 32, borderRadius: 16, }, cellLabel: { flex: 1, fontSize: 16, paddingHorizontal: 12, paddingVertical: 8, }, selected: { flexDirection: 'row', }, loading: { justifyContent: 'center', flex: 1, }, navIcon: { color: 'blue', fontSize: 18, paddingTop: 2, }, checkButtonContainer: { paddingRight: 12, paddingVertical: 6, }, checkButton: { borderWidth: 1, borderColor: '#dbdbdb', padding: 4, height: 24, width: 24, }, checkButtonIcon: { marginRight: -4, // default is 12 }, }); const SectionHeader = ({ title }) => { // inline styles used for brevity, use a stylesheet when possible const textStyle = { textAlign: 'center', color: '#fff', fontWeight: '700', fontSize: 16, }; const viewStyle = { backgroundColor: '#ccc', }; return ( <View style={viewStyle}> <Text style={textStyle}>{title}</Text> </View> ); }; SectionHeader.propTypes = { title: PropTypes.string, }; const SectionItem = ({ title }) => ( <Text style={{ color: 'blue' }}>{title}</Text> ); SectionItem.propTypes = { title: PropTypes.string, }; class Cell extends Component { constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.state = { isSelected: props.isSelected(props.item), }; } componentWillReceiveProps(nextProps) { this.setState({ isSelected: nextProps.isSelected(nextProps.item), }); } toggle() { this.props.toggle(this.props.item); } render() { return ( <View style={styles.cellContainer}> <Image style={styles.cellImage} source={{ uri: 'https://reactjs.org/logo-og.png' }} /> <Text style={styles.cellLabel}>{this.props.item.username}</Text> <View style={styles.checkButtonContainer}> <Icon.Button backgroundColor={this.state.isSelected ? 'blue' : 'white'} borderRadius={12} color={'white'} iconStyle={styles.checkButtonIcon} name={'check'} onPress={this.toggle} size={16} style={styles.checkButton} /> </View> </View> ); } } Cell.propTypes = { isSelected: PropTypes.func, item: PropTypes.shape({ username: PropTypes.string.isRequired, }).isRequired, toggle: PropTypes.func.isRequired, }; class NewGroup extends Component { static navigationOptions = ({ navigation }) => { const { state } = navigation; const isReady = state.params && state.params.mode === 'ready'; return { title: 'New Group', headerRight: ( isReady ? <Button title="Next" onPress={state.params.finalizeGroup} /> : undefined ), }; }; constructor(props) { super(props); let selected = []; if (this.props.navigation.state.params) { selected = this.props.navigation.state.params.selected; } this.state = { selected: selected || [], friends: props.user ? _.groupBy(props.user.friends, friend => friend.username.charAt(0).toUpperCase()) : [], }; this.finalizeGroup = this.finalizeGroup.bind(this); this.isSelected = this.isSelected.bind(this); this.toggle = this.toggle.bind(this); } componentDidMount() { this.refreshNavigation(this.state.selected); } componentWillReceiveProps(nextProps) { const state = {}; if (nextProps.user && nextProps.user.friends && nextProps.user !== this.props.user) { state.friends = sortObject( _.groupBy(nextProps.user.friends, friend => friend.username.charAt(0).toUpperCase()), ); } if (nextProps.selected) { Object.assign(state, { selected: nextProps.selected, }); } this.setState(state); } componentWillUpdate(nextProps, nextState) { if (!!this.state.selected.length !== !!nextState.selected.length) { this.refreshNavigation(nextState.selected); } } refreshNavigation(selected) { const { navigation } = this.props; navigation.setParams({ mode: selected && selected.length ? 'ready' : undefined, finalizeGroup: this.finalizeGroup, }); } finalizeGroup() { const { navigate } = this.props.navigation; navigate('FinalizeGroup', { selected: this.state.selected, friendCount: this.props.user.friends.length, userId: this.props.user.id, }); } isSelected(user) { return ~this.state.selected.indexOf(user); } toggle(user) { const index = this.state.selected.indexOf(user); if (~index) { const selected = update(this.state.selected, { $splice: [[index, 1]] }); return this.setState({ selected, }); } const selected = [...this.state.selected, user]; return this.setState({ selected, }); } render() { const { user, loading } = this.props; // render loading placeholder while we fetch messages if (loading || !user) { return ( <View style={[styles.loading, styles.container]}> <ActivityIndicator /> </View> ); } return ( <View style={styles.container}> {this.state.selected.length ? <View style={styles.selected}> <SelectedUserList data={this.state.selected} remove={this.toggle} /> </View> : undefined} {_.keys(this.state.friends).length ? <AlphabetListView style={{ flex: 1 }} data={this.state.friends} cell={Cell} cellHeight={30} cellProps={{ isSelected: this.isSelected, toggle: this.toggle, }} sectionListItem={SectionItem} sectionHeader={SectionHeader} sectionHeaderHeight={22.5} /> : undefined} </View> ); } } NewGroup.propTypes = { loading: PropTypes.bool.isRequired, navigation: PropTypes.shape({ navigate: PropTypes.func, setParams: PropTypes.func, state: PropTypes.shape({ params: PropTypes.object, }), }), user: PropTypes.shape({ id: PropTypes.number, friends: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.number, username: PropTypes.string, })), }), selected: PropTypes.arrayOf(PropTypes.object), }; const userQuery = graphql(USER_QUERY, { options: ownProps => ({ variables: { id: ownProps.auth.id } }), props: ({ data: { loading, user } }) => ({ loading, user, }), }); const mapStateToProps = ({ auth }) => ({ auth, }); export default compose( connect(mapStateToProps), userQuery, )(NewGroup);
src/containers/ContactList.js
jp7internet/react-apz
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link, withRouter } from 'react-router-dom'; import Button from '../components/Button'; import { contactDelete, contactFetch } from '../actions'; class ContactList extends Component { componentWillMount() { this.props.onLoad(); } render() { return ( <div> <Link to="/new" className="btn btn-primary"> Create Contact </Link> <table className="table"> <thead> <tr> <th>Name</th> <th>Phone</th> <th>Email</th> <th colSpan={2}></th> </tr> </thead> <tbody> { this.props.contactList.map(({ id, name, phone, email }, index) => ( <tr key={index}> <td>{name}</td> <td>{phone}</td> <td>{email}</td> <td><Link to={`/edit/${id}`} className="btn btn-primary">Edit</Link></td> <td> <Button buttonType="btn-danger" onClick={() => this.props.onClickDelete(id)}> Delete </Button> </td> </tr> )) } </tbody> </table> </div> ); } } const mapStateToProps = state => ({ ...state.contacts }); const mapDispatchToProps = dispatch => ({ onClickDelete: id => dispatch(contactDelete(id)), onLoad: () => dispatch(contactFetch()) }); export default connect(mapStateToProps, mapDispatchToProps)(withRouter(ContactList));
src/svg-icons/content/weekend.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentWeekend = (props) => ( <SvgIcon {...props}> <path d="M21 10c-1.1 0-2 .9-2 2v3H5v-3c0-1.1-.9-2-2-2s-2 .9-2 2v5c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2v-5c0-1.1-.9-2-2-2zm-3-5H6c-1.1 0-2 .9-2 2v2.15c1.16.41 2 1.51 2 2.82V14h12v-2.03c0-1.3.84-2.4 2-2.82V7c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ContentWeekend = pure(ContentWeekend); ContentWeekend.displayName = 'ContentWeekend'; ContentWeekend.muiName = 'SvgIcon'; export default ContentWeekend;
docs/app/Examples/collections/Message/Variations/MessageExampleFloating.js
shengnian/shengnian-ui-react
import React from 'react' import { Message } from 'shengnian-ui-react' const MessageExampleFloating = () => ( <Message floating> Way to go! </Message> ) export default MessageExampleFloating
react/features/toolbox/components/Toolbox.web.js
KalinduDN/kalindudn.github.io
/* @flow */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import UIEvents from '../../../../service/UI/UIEvents'; import { setDefaultToolboxButtons, setToolboxAlwaysVisible } from '../actions'; import { abstractMapStateToProps, showCustomToolbarPopup } from '../functions'; import Notice from './Notice'; import PrimaryToolbar from './PrimaryToolbar'; import SecondaryToolbar from './SecondaryToolbar'; declare var APP: Object; declare var config: Object; declare var interfaceConfig: Object; /** * Implements the conference toolbox on React/Web. */ class Toolbox extends Component { /** * App component's property types. * * @static */ static propTypes = { /** * Indicates if the toolbox should always be visible. */ _alwaysVisible: React.PropTypes.bool, /** * Handler dispatching setting default buttons action. */ _setDefaultToolboxButtons: React.PropTypes.func, /** * Handler dispatching reset always visible toolbox action. */ _setToolboxAlwaysVisible: React.PropTypes.func, /** * Represents conference subject. */ _subject: React.PropTypes.string, /** * Flag showing whether to set subject slide in animation. */ _subjectSlideIn: React.PropTypes.bool, /** * Property containing toolbox timeout id. */ _timeoutID: React.PropTypes.number }; /** * Invokes reset always visible toolbox after mounting the component and * registers legacy UI listeners. * * @returns {void} */ componentDidMount(): void { this.props._setToolboxAlwaysVisible(); APP.UI.addListener( UIEvents.SHOW_CUSTOM_TOOLBAR_BUTTON_POPUP, showCustomToolbarPopup); // FIXME The redux action SET_DEFAULT_TOOLBOX_BUTTONS and related source // code such as the redux action creator setDefaultToolboxButtons and // _setDefaultToolboxButtons were introduced to solve the following bug // in the implementation of features/toolbar at the time of this // writing: getDefaultToolboxButtons uses interfaceConfig which is not // in the redux store at the time of this writing yet interfaceConfig is // modified after getDefaultToolboxButtons is called. // SET_DEFAULT_TOOLBOX_BUTTONS represents/implements an explicit delay // of the invocation of getDefaultToolboxButtons until, heuristically, // all existing changes to interfaceConfig have been applied already in // our known execution paths. this.props._setDefaultToolboxButtons(); } /** * Unregisters legacy UI listeners. * * @returns {void} */ componentWillUnmount(): void { APP.UI.removeListener( UIEvents.SHOW_CUSTOM_TOOLBAR_BUTTON_POPUP, showCustomToolbarPopup); } /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render(): ReactElement<*> { return ( <div className = 'toolbox'> { this._renderSubject() } { this._renderToolbars() } <div id = 'sideToolbarContainer' /> </div> ); } /** * Returns React element representing toolbox subject. * * @returns {ReactElement} * @private */ _renderSubject(): ReactElement<*> | null { const { _subjectSlideIn, _subject } = this.props; const classNames = [ 'subject' ]; if (!_subject) { return null; } if (_subjectSlideIn) { classNames.push('subject_slide-in'); } else { classNames.push('subject_slide-out'); } // XXX: Since chat is now not reactified we have to dangerously set // inner HTML into the component. This has to be refactored while // reactification of the Chat.js const innerHtml = { __html: _subject }; return ( <div className = { classNames.join(' ') } // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML = { innerHtml } id = 'subject' /> ); } /** * Renders primary and secondary toolbars. * * @returns {ReactElement} * @private */ _renderToolbars(): ReactElement<*> | null { // In case we're not in alwaysVisible mode the toolbox should not be // shown until timeoutID is initialized. if (!this.props._alwaysVisible && this.props._timeoutID === null) { return null; } return ( <div className = 'toolbox-toolbars'> <Notice /> <PrimaryToolbar /> <SecondaryToolbar /> </div> ); } } /** * Maps parts of Redux actions to component props. * * @param {Function} dispatch - Redux action dispatcher. * @returns {{ * _setDefaultToolboxButtons: Function, * _setToolboxAlwaysVisible: Function * }} * @private */ function _mapDispatchToProps(dispatch: Function): Object { return { /** * Dispatches a (redux) action to set the default toolbar buttons. * * @returns {Object} Dispatched action. */ _setDefaultToolboxButtons() { dispatch(setDefaultToolboxButtons()); }, /** * Dispatches a (redux) action to reset the permanent visibility of * the Toolbox. * * @returns {Object} Dispatched action. */ _setToolboxAlwaysVisible() { dispatch(setToolboxAlwaysVisible( config.alwaysVisibleToolbar === true || interfaceConfig.filmStripOnly)); } }; } /** * Maps parts of toolbox state to component props. * * @param {Object} state - Redux state. * @private * @returns {{ * _alwaysVisible: boolean, * _audioMuted: boolean, * _subjectSlideIn: boolean, * _videoMuted: boolean * }} */ function _mapStateToProps(state: Object): Object { const { alwaysVisible, subject, subjectSlideIn, timeoutID } = state['features/toolbox']; return { ...abstractMapStateToProps(state), /** * Indicates if the toolbox should always be visible. * * @private * @type {boolean} */ _alwaysVisible: alwaysVisible, /** * Property containing conference subject. * * @private * @type {string} */ _subject: subject, /** * Flag showing whether to set subject slide in animation. * * @private * @type {boolean} */ _subjectSlideIn: subjectSlideIn, /** * Property containing toolbox timeout id. * * @private * @type {number} */ _timeoutID: timeoutID }; } export default connect(_mapStateToProps, _mapDispatchToProps)(Toolbox);
src/_store/__tests__/AppConfigProvider-test.js
qingweibinary/binary-next-gen
import React from 'react'; import configureStore from 'redux-mock-store'; import { expect } from 'chai'; import { fromJS } from 'immutable'; import { shallow, render } from 'enzyme'; import AppConfigProvider from '../AppConfigProvider'; describe('<AppConfigProvider />', () => { const ChildComponent = () => <div>Hello, World</div>; const middlewares = []; // add your middlewares like `redux-thunk` const mockStore = configureStore(middlewares); const getState = { appConfig: fromJS({ theme: 'dark', language: 'EN' }) }; const store = mockStore(getState, []); it('should render children', () => { const wrapper = shallow( <AppConfigProvider store={store}> <ChildComponent /> </AppConfigProvider>); expect(wrapper.render().text()).to.contain('World'); }); it('should render theme-wrapper', () => { const wrapper = render( <AppConfigProvider store={store}> <ChildComponent /> </AppConfigProvider>); expect(wrapper.find('#theme-wrapper').hasClass('inverse')).to.be.true; }); });
src/svg-icons/action/play-for-work.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPlayForWork = (props) => ( <SvgIcon {...props}> <path d="M11 5v5.59H7.5l4.5 4.5 4.5-4.5H13V5h-2zm-5 9c0 3.31 2.69 6 6 6s6-2.69 6-6h-2c0 2.21-1.79 4-4 4s-4-1.79-4-4H6z"/> </SvgIcon> ); ActionPlayForWork = pure(ActionPlayForWork); ActionPlayForWork.displayName = 'ActionPlayForWork'; ActionPlayForWork.muiName = 'SvgIcon'; export default ActionPlayForWork;
client/src/components/Dashboard.js
jobn/iceman
// @flow import React, { Component } from 'react'; export default class Dashboard extends Component<*> { render() { return ( <h1>Dashboard</h1> ); } }
plugins/subschema-plugin-contentwrapper/src/index.js
jspears/subschema-devel
import React, { Component } from 'react'; import PropTypes from 'subschema-prop-types'; import { FREEZE_OBJ } from 'subschema-utils'; function strip(obj) { return !obj ? FREEZE_OBJ : Object.keys(obj).reduce(function (ret, key) { if (key == 'dataType' || key == 'fieldAttrs' || obj[key] == null) { return ret; } ret[key] = obj[key]; return ret; }, {}); } export class ContentWrapper extends Component { static defaultProps = { type : 'span', content: '' }; static propTypes = { content : PropTypes.expression, type : PropTypes.domType, value : PropTypes.any, onChange : PropTypes.any, title : PropTypes.any, className : PropTypes.cssClass, id : PropTypes.any, name : PropTypes.any, fieldAttrs: PropTypes.any }; render() { const { type, content, dataType, children, context, path, fieldAttrs, title, ...props } = this.props; const allProps = { ...strip(fieldAttrs), title: title === false ? void(0) : title, ...props, }; if (typeof type == 'string') { return React.createElement(type, { ...allProps, dangerouslySetInnerHTML: { __html: content } }); } const Type = type; return <Type {...allProps}/>; } } export default ({ types: { ContentWrapper } })
examples/docs/src/Containers/GettingStarted.js
react-material-design/react-material-design
import React from 'react'; const GettingStarted = () => ( <div> <h1>Getting Started</h1> <p>More to come...</p> <p>To install run: yarn add react-material-design</p> <p>Once installed import the react-material-design components you'll be usings like so: import {'{'} FAB {'}'} from 'react-material-design';</p> </div> ); export default GettingStarted;
src/decorators/withViewport.js
magnusbae/arcadian-rutabaga
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = {width: 1366, height: 768}; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = {width: window.innerWidth, height: window.innerHeight}; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport, }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({viewport: value}); // eslint-disable-line react/no-set-state } }; } export default withViewport;
src/admin/components/Profesor.js
zeljkoX/e-learning
import React from 'react'; import {State, History} from 'react-router'; import { Menu, Mixins, Styles, RaisedButton, TextField, SelectField } from 'material-ui'; import Content from '../../components/layout/Content'; import ContentHeader from '../../components/layout/ContentHeader'; class Profesor extends React.Component { render() { var profesori = [ { payload: '1', text: 'Never' }, { payload: '2', text: 'Every Night' }, { payload: '3', text: 'Weeknights' }, { payload: '4', text: 'Weekends' }, { payload: '5', text: 'Weekly' }, ]; var menu = [{name:'Uredi', link:'profesori/edit'},{name:'Brisi', link:'profesori/remove'}]; return ( <Content> <ContentHeader title='Odredjen profesor' menu={menu}/> <form style={{margin: '0 auto', position: 'relative', width: 600}}> <TextField hintText="Ime" disabled={true} floatingLabelText="Ime" style={{display: 'block', width: 350, margin: '0 auto'}}/> <TextField hintText="Prezime" disabled={true} floatingLabelText="Prezime" style={{display: 'block', width: 350, margin: '0 auto'}} /> <TextField hintText="Email" disabled={true} floatingLabelText="Email" style={{display: 'block', width: 350, margin: '0 auto'}} /> <TextField hintText="Sifra" disabled={true} floatingLabelText="Sifra" style={{display: 'block', width: 350, margin: '0 auto'}} /> <TextField hintText="Skype" disabled={true} floatingLabelText="Skype" style={{display: 'block', width: 350, margin: '0 auto'}} /> <SelectField floatingLabelText="Profesor" hintText="Odaberite profesora" style={{display: 'block', width: 350, margin: '0 auto'}} menuItems={profesori} /> <SelectField floatingLabelText="Kurs" hintText="Odaberite profesora" style={{display: 'block', width: 350, margin: '0 auto'}} menuItems={profesori} /> </form> </Content> ); } } export default Profesor;
src/slides/stream-of-events.js
philpl/talk-observe-the-future
import React from 'react' import { Appear, Image, Text, S, Slide } from 'spectacle' import Marbles from '../components/marbles' export default ( <Slide transition={[ 'slide' ]}> <Marbles/> </Slide> )
src/components/ScoreGraph.js
tgevaert/react-redux-hearts
import React from 'react'; import { connect } from 'react-redux'; import { getPlayers, getScoreTotals } from '../reducers'; const GraphRowLabel = ({label}) => (<div className={"graph label"}>{label}</div>); const GraphLine = ({size}) => { const colors = ["#388e3c", "#ffd600", "#e65100", "#d50000", "#d50000"]; const barStyle = { flexBasis: Math.max(Math.min(size, 100), 0) + "%", backgroundColor: colors[Math.max(Math.floor(size / 25), 0)], }; return ( <div className={"graph row"}> <div className={"graph row bar"} style={barStyle}>{size}</div> <div className={"graph row blank"}></div> </div> ); }; const ScoreGraphPresentation = ({playerNames, scores}) => { const graphRowLabels = playerNames.map((playerName, i) => <GraphRowLabel key={i} label={playerName} />); const graphLines = scores.map((score, i) => <GraphLine key={i} size={score} />); return ( <div className={"graph"}> <div className={"labels"}> {graphRowLabels} </div> <div className={"bars"}> {graphLines} </div> </div> ) } const mapStateToProps = (state) => { const playerNames = getPlayers(state).map((player) => player.name); const scores = getScoreTotals(state); return {playerNames: playerNames, scores: scores}; } export default connect(mapStateToProps)(ScoreGraphPresentation);
yycomponent/breadcrumb/Breadcrumb.js
77ircloud/yycomponent
import React from 'react'; import { Breadcrumb as _Breadcrumb } from 'antd'; class Breadcrumb extends React.Component{ constructor(props){ super(props); } render(){ return (<_Breadcrumb {...this.props}/>); } } export default Breadcrumb
test/integration/IconButton/IconButton.spec.js
matthewoates/material-ui
/* eslint-env mocha */ import React from 'react'; import {shallow} from 'enzyme'; import {assert} from 'chai'; import IconButton from 'src/IconButton'; import FontIcon from 'src/FontIcon'; import getMuiTheme from 'src/styles/getMuiTheme'; describe('<IconButton />', () => { const muiTheme = getMuiTheme(); const shallowWithContext = (node) => shallow(node, {context: {muiTheme}}); it('should render children with custom color', () => { const wrapper = shallowWithContext( <IconButton> <FontIcon className="material-icons" color="red">home</FontIcon> </IconButton> ); assert.ok(wrapper.find(FontIcon), 'should contain the FontIcon child'); assert.strictEqual(wrapper.find(FontIcon).node.props.color, 'red', 'FontIcon should have color set to red'); assert.strictEqual( wrapper.find(FontIcon).node.props.style.color, undefined, 'FontIcon style object has no color property' ); }); });
imports/ui/components/footer/Footer/Footer.js
pletcher/cltk_frontend
import React from 'react'; import FlatButton from 'material-ui/FlatButton'; import IconButton from 'material-ui/IconButton'; import PropTypes from 'prop-types'; import baseTheme from 'material-ui/styles/baseThemes/lightBaseTheme'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; export default class Footer extends React.Component { getChildContext() { return { muiTheme: getMuiTheme(baseTheme) }; } render() { const date = new Date(); const year = date.getFullYear(); const styles = { circleButton: { width: 'auto', height: 'auto', }, circleButtonIcon: { color: '#ffffff', }, }; return ( <footer className="bg-dark"> <div className="container"> <div className="row"> <div className="col-md-8 col-md-offset-2 col-sm-9 col-sm-offset-1 text-center"> <h3 className="logo">CLTK Archive</h3> <div className="footer-nav"> <FlatButton label="HOME" href="/" /> <FlatButton label="READ" href="/browse" /> <FlatButton label="SEARCH" href="/search" /> <FlatButton label="CONTRIBUTE" target="_blank" href="http://github.com/cltk/cltk" rel="noopener noreferrer" /> <FlatButton label="CLTK.ORG" href="//cltk.org/" target="_blank" rel="noopener noreferrer" /> </div> </div> </div> <div className="row"> <div className="col-sm-12 text-center"> <ul className="list-inline social-list mb0"> <li> <IconButton style={styles.circleButton} iconStyle={styles.circleButtonIcon} href="http://github.com/cltk" iconClassName="mdi mdi-github-circle" /> </li> <li> <IconButton style={styles.circleButton} iconStyle={styles.circleButtonIcon} href="http://twitter.com/@cltkarchive" iconClassName="mdi mdi-twitter" /> </li> <li> <IconButton style={styles.circleButton} iconStyle={styles.circleButtonIcon} href="http://plus.google.com/+cltkarchive" iconClassName="mdi mdi-google-plus" /> </li> </ul> <span className="copyright-information fade-1-4"> Copyright Classical Languages ToolKit, {year}. All of the media presented on this site originating from the CLTK are available through the Creative Commons Attribution 4.0 International, Free Culture License. Media originating from other sources are specific to the contributor. Review specific corpora information here: <a href="https://github.com/cltk" target="_blank">https://github.com/cltk</a>. </span> </div> </div> </div> </footer> ); } }; Footer.childContextTypes = { muiTheme: PropTypes.object.isRequired, };
app/javascript/mastodon/components/__tests__/avatar_overlay-test.js
rainyday/mastodon
import React from 'react'; import renderer from 'react-test-renderer'; import { fromJS } from 'immutable'; import AvatarOverlay from '../avatar_overlay'; describe('<AvatarOverlay', () => { const account = fromJS({ username: 'alice', acct: 'alice', display_name: 'Alice', avatar: '/animated/alice.gif', avatar_static: '/static/alice.jpg', }); const friend = fromJS({ username: 'eve', acct: '[email protected]', display_name: 'Evelyn', avatar: '/animated/eve.gif', avatar_static: '/static/eve.jpg', }); it('renders a overlay avatar', () => { const component = renderer.create(<AvatarOverlay account={account} friend={friend} />); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); });
modules/plugins/italic/ItalicButton.js
devrieda/arc-reactor
import React from 'react'; import MenuButton from '../../components/MenuButton'; import ToggleMarkup from '../../helpers/Manipulation/ToggleMarkup'; import SelectedContent from '../../helpers/SelectedContent'; const ItalicButton = React.createClass({ statics: { getName: () => "italic", isVisible: (content, selection) => { const selContent = new SelectedContent(selection, content); return !selContent.isHeader(); } }, propTypes: MenuButton.propTypes, getDefaultProps() { return { type: "em", text: "Italic", icon: "fa-italic" }; }, handlePress() { const guids = this.props.selection.guids(); const offsets = this.props.selection.offsets(); const position = this.props.selection.position(); const result = this._toggleMarkup().execute(guids, offsets, { type: this.props.type }); return { content: result.content, position: position }; }, _toggleMarkup() { return new ToggleMarkup(this.props.content); }, render() { return ( <MenuButton {...this.props} onPress={this.handlePress} /> ); } }); export default ItalicButton;
ux/editor/TextEditorView.js
rameshvk/j0
'use strict'; require('./TextEditorView.less'); import React from 'react'; import ReactDOM from 'react-dom'; import BaseComponent from '../BaseComponent'; import Caret from './Caret'; import InvisibleInput from './InvisibleInput'; import TextSelectionView from './TextSelectionView'; import getTextNodeInfoForPoint from '../../dom/getTextNodeInfoForPoint'; import MouseModel from './MouseModel'; import AttentionManager from './AttentionManager'; export default class TextEditorView extends BaseComponent { constructor(props) { super(props); this._onMouseDown = ee => this.onMouseDown(ee); this._caret = Caret.create({isActive: false, isCollapsed: true}); this._mouseModel = null; this._attentionManager = new AttentionManager(); } componentDidMount() { this._mouseModel = new MouseModel(this.props.selection, ReactDOM.findDOMNode(this)); this._attentionManager.startTracking(ReactDOM.findDOMNode(this)); // TODO: do this via events this.props.selection.setAttentionManager(this._attentionManager); } componentWillUnmount() { this._mouseModel.cleanup(); } onMouseDown(ee) { const clickCount = this._mouseModel.onMouseDown(ee); if (clickCount && !this.props.isActive) { this.props.onActivate(ee); } } _renderInput(isActive, selection) { return InvisibleInput.create({key: 1, isActive, selection}); } _renderCaret(isActive) { return React.cloneElement(this.props.caret || this._caret, {key: 0, isActive}); } render() { const isActive = this.props.isActive; const selection = this.props.selection; return React.DOM.div( { className: 'j0editor ' + (isActive ? 'active ' : '') + (this.props.className || ''), onMouseDown: this._onMouseDown }, this.props.children, this.props.selectionOverlays, TextSelectionView.create({ className: 'j0selections ' + (isActive? 'active' : ''), selection, anchorMarker: [], focusMarker: [this._renderInput(isActive, selection), this._renderCaret(isActive, selection)] }) ); } } TextEditorView.propTypes = { className: React.PropTypes.string, selection: React.PropTypes.object.isRequired, selectionOverlays: React.PropTypes.array, caret: React.PropTypes.element, isActive: React.PropTypes.bool.isRequired, onActivate: React.PropTypes.func.isRequired };
web/src/presentation/get-retro-properties.js
mgwalker/retros
import React from 'react'; import CategoryTime from './set-retro-category-time'; function displayTime(minutes) { const wholeMinutes = Math.floor(minutes); const seconds = Math.round((minutes - wholeMinutes) * 60); return `${wholeMinutes} minutes${seconds > 0 ? ` and ${seconds} seconds` : ''}`; } function GetRetroProperties(props) { return ( <div className="usa-grid"> <h1>Setup Retro Properties</h1> <div className="usa-grid"> <p> Now we need to setup the timing properties of your retro. You can specify a total length of time the retro should run and we&apos;ll automatically fill in the length of time to display each category and voting, or you can fill in those individual values yourself. This time is evenly divided for each category. Your retro cannot be shorter than {displayTime(props.minimumTime)}, so that participants can answer each category for at least one minute, and vote on each for at least 30 seconds. </p> <h2>Total retro time, in minutes:</h2> <p> <input type="number" min={props.minimumTime} step="1.0" value={props.totalTime} onChange={props.changeTotalTime}></input> </p> <button className="usa-button-big" onClick={props.acceptProperties}>Accept</button> Create a standup that runs for {displayTime(props.totalTime)} </div> <hr /> <div className="usa-grid"> <p> If you want finer-grained control, you can set the times for each category below. Note that answer times must be at least one minute and voting times must be at least 0.5 minutes (30 seconds). </p> {props.categories.map(c => <CategoryTime category={c} times={props.categoryTimes[c]} key={`retro_props_category_${c}`} onChangeSelfTime={props.changeCategorySelfTime(c)} onChangeVoteTime={props.changeCategoryVoteTime(c)} /> )} <button className="usa-button-big" onClick={props.acceptProperties}>Accept</button> Create a standup that runs for {displayTime(props.totalTime)} </div> </div> ); } GetRetroProperties.propTypes = { categories: React.PropTypes.array.isRequired, minimumTime: React.PropTypes.number.isRequired, totalTime: React.PropTypes.string.isRequired, categoryTimes: React.PropTypes.object.isRequired, changeTotalTime: React.PropTypes.func.isRequired, changeCategorySelfTime: React.PropTypes.func.isRequired, changeCategoryVoteTime: React.PropTypes.func.isRequired, acceptProperties: React.PropTypes.func.isRequired }; export default GetRetroProperties;
js/ClientApp.js
JoeMarion/react-netflix
import React from 'react' import { render } from 'react-dom' import '../public/style.css' const App = React.createClass({ render () { return ( <div className='app'> <div className='landing'> <h1>svideo</h1> <input type='text' placeholder='Search' /> <a>or Browse All</a> </div> </div> ) } }) render(<App />, document.getElementById('app'))
src/SvgIcon/SvgIcon.spec.js
ichiohta/material-ui
/* eslint-env mocha */ import React from 'react'; import {spy} from 'sinon'; import {shallow} from 'enzyme'; import {assert} from 'chai'; import SvgIcon from './SvgIcon'; import getMuiTheme from '../styles/getMuiTheme'; describe('<SvgIcon />', () => { const muiTheme = getMuiTheme(); const shallowWithContext = (node) => shallow(node, {context: {muiTheme}}); const path = <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />; it('renders children by default', () => { const wrapper = shallowWithContext( <SvgIcon>{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); }); it('renders children and color', () => { const wrapper = shallowWithContext( <SvgIcon color="red">{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); assert.equal(wrapper.node.props.style.fill, 'red', 'should have color set to red'); }); it('renders children and hoverColor when mouseEnter', () => { const onMouseEnter = spy(); const wrapper = shallowWithContext( <SvgIcon className="material-icons" color="red" hoverColor="green" onMouseEnter={onMouseEnter} > {path} </SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); assert.equal(wrapper.node.props.style.fill, 'red', 'should have color set to red'); wrapper.simulate('mouseEnter'); assert.equal(wrapper.node.props.style.fill, 'green', 'should have color set to green after hover'); assert.equal(onMouseEnter.calledOnce, true, 'should have called onMouseEnter callback function'); }); it('renders children and call onMouseEnter callback', () => { const onMouseEnter = spy(); const wrapper = shallowWithContext( <SvgIcon onMouseEnter={onMouseEnter} hoverColor="green">{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); wrapper.simulate('mouseEnter'); assert.equal(onMouseEnter.calledOnce, true, 'should have called onMouseEnter callback function'); }); it('renders children and call onMouseEnter callback even when hoverColor is not set', () => { const onMouseEnter = spy(); const wrapper = shallowWithContext( <SvgIcon onMouseEnter={onMouseEnter}>{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); wrapper.simulate('mouseEnter'); assert.equal(onMouseEnter.calledOnce, true, 'should have called onMouseEnter callback function'); }); it('renders children and call onMouseLeave callback', () => { const onMouseLeave = spy(); const wrapper = shallowWithContext( <SvgIcon onMouseLeave={onMouseLeave} hoverColor="green">{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); wrapper.simulate('mouseLeave'); assert.equal(onMouseLeave.calledOnce, true, 'should have called onMouseLeave callback function'); }); it('renders children and call onMouseLeave callback even when hoverColor is not set', () => { const onMouseLeave = spy(); const wrapper = shallowWithContext( <SvgIcon onMouseLeave={onMouseLeave}>{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); wrapper.simulate('mouseLeave'); assert.equal(onMouseLeave.calledOnce, true, 'should have called onMouseLeave callback function'); }); it('renders children and overwrite styles', () => { const style = { backgroundColor: 'red', }; const wrapper = shallowWithContext( <SvgIcon style={style}>{path}</SvgIcon> ); assert.equal(wrapper.get(0).props.style.backgroundColor, style.backgroundColor, 'should have backgroundColor to red'); }); });
node-siebel-rest/siebel-claims-native/screens/AddClaim.js
Pravici/node-siebel
import React, { Component } from 'react'; import { StyleSheet, View, TouchableHighlight, Text, Image, ActivityIndicator, Button, } from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; import { MaterialIcons } from '@expo/vector-icons'; import { callPostApi } from '../utils/rest'; import myConfig from '../config/Config'; import colors from '../utils/colors'; import TouchableDetailListItem from '../components/TouchableDetailListItem'; export default class AddClaim extends Component { static navigationOptions = ({ navigation: { navigate } }) => ({ title: 'Add Accident Claim', headerLeft: ( <MaterialIcons name="menu" size={24} style={{ color: colors.black, marginLeft: 10 }} onPress={() => navigate('DrawerToggle')} /> ), }); state = { claim: [], error: false, adding: "false", lossDate:new Date(), }; async postNewClaim(url, data) { const jsondata = await callPostApi(url, data); console.log('json:', jsondata); return jsondata['Id']; } setDateOfIncident(selectedDate) { this.setState({lossDate: selectedDate}); console.log('lossDate', selectedDate); } getFormattedDate(date) { var mm = date.getMonth() + 1; var dd = date.getDate(); var yyyy = date.getFullYear(); return mm + '/' + dd +'/' + yyyy +' '+ date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(); } async updateSiebel() { try { var url = `${myConfig.simUrl}/claims/addClaim/${myConfig.customer}`; //var url = `https://win-b1ejslvnv0l.siebel-pravici.com:9301/siebel/v1.0/data/Demo INS Claims/INS Claims/`; console.log(url); data = { "Id": "New claim", "Asset Id": "1-3H01", "Location Description": "parking lot Thom Thumb store facing Renner Rd", "Loss Date - Non UTC": this.getFormattedDate(this.state.lossDate), }; // simdata = { // claimType: 'accident', // accidentType: 'other car', // location: 'text field', // lossDate: '10/10/17', // reportedDate: '10/10/2017', // policyNumber: 'KM-VEH-005', // }; this.setState({adding: "adding",}); //const claim = callPostApi(url, data, this.postNewClaim); const claim = await this.postNewClaim(url, data); this.setState({claim: claim, error: false, adding: "true,"}); const { navigation: { navigate } } = this.props; navigate('ReviewClaims'); } catch (e) { this.setState({ error: e.message, adding: "false", }); } } render() { const { navigation: { navigate } } = this.props; const { adding, error } = this.state; return ( <View style={styles.container}> {adding == "adding" && <ActivityIndicator size="large" />} {error && <Text>{error}</Text>} {adding == "false" && !error && ( <View style={styles.container}> <TouchableDetailListItem icon="info" title="Accident Type " rightIcon="chevron-right" /> <TouchableDetailListItem icon="date-range" title="Date & Location" rightIcon="chevron-right" onPress={() => navigate('DatePicker', { show : true , returnData : this.setDateOfIncident.bind(this)})}/> <TouchableDetailListItem icon="camera" title="Pictures of the Incident" rightIcon="chevron-right" onPress = {() => navigate('PhotoPage', { claim: this.state.claimNumber })} /> <TouchableDetailListItem icon="verified-user" title="Contact Info" rightIcon="chevron-right" /> <TouchableDetailListItem icon="traffic" title="Other Driver's Info" rightIcon="chevron-right"/> <TouchableHighlight onPress={() => this.updateSiebel()} underlayColor={colors.grey} style={styles.touchContainer} > <View> <Text style={[styles.buttonStyle, styles.mediumText]}>Submit Claim</Text> </View> </TouchableHighlight> </View> )} </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, }, touchContainer: { paddingLeft: 24, backgroundColor: 'steelblue', paddingTop: 10, }, buttonStyle: { height: 40, alignItems: 'center', }, mediumText: { textAlign: 'center', fontSize: 20, }, });
src/containers/Contact/Contact.js
Anshul-HL/blitz-windermere
import React, { Component } from 'react'; import { groupBy } from 'utils/extenders'; const addressList = [ { id: '1', title: 'Our Corporate Office', address: [ '3th floor, Bikaner Pinnacle,', 'No.1 Rhenius street,', 'Off Richmond Road,', 'Bangalore - 560025' ], city: 'Bangalore', landMark: 'Behind Cafe Coffee Day on Richmond Road' }, { id: '2', title: 'Gopalan Square', address: [ '4th floor, Gopalan Signature Mall,', 'Old Madras Road,', 'Bangalore - 560093' ], city: 'Bangalore' }, { id: '3', title: 'Yelahanka Square', address: [ 'Mukund Pandurangi,', '#1234, Mother Dairy Road,', 'Yelahanka Newtown,', 'Bangalore - 560064' ], city: 'Bangalore' }, { id: '4', title: 'Kanakapura Square', address: [ '#2054, 1st Main Road,', '1st Floor, SMLV Plaza', 'BCCHS Layout, Raghuvanahalli,', 'Kanakpura,', 'Bangalore' ], city: 'Bangalore' }, { id: '5', title: 'Chennai Square', address: [ 'Door #46,', 'Chennai - Bangalore Trunk Road,', 'Nazarethpet, Poonamallee,', 'Chennai - 600123' ], city: 'Chennai', }, { id: '6', title: 'Hyderabad Square', address: [ '8-2-699/4, Shop no.4,', '1st floor, K.R Towers,', 'Road no.12, Banjara Hills', 'Hyderabad - 500043' ], city: 'Hyderabad', }/* , { id: '6', title: 'Mumbai Showroom', address: [ '2nd Floor, Tirumala Platinum,', 'Near Gachibowli Flyover,', 'Gachibowli,', 'Hyderabad - 500032' ] }, { id: '7', title: 'Hyderabad Showroom', address: [ '2nd Floor, Tirumala Platinum,', 'Near Gachibowli Flyover,', 'Gachibowli,', 'Hyderabad - 500032' ] }, { id: '8', title: 'Hyderabad Showroom', address: [ '2nd Floor, Tirumala Platinum,', 'Near Gachibowli Flyover,', 'Gachibowli,', 'Hyderabad - 500032' ] }, { id: '9', title: 'Hyderabad Showroom', address: [ '2nd Floor, Tirumala Platinum,', 'Near Gachibowli Flyover,', 'Gachibowli,', 'Hyderabad - 500032' ] }, { id: '10', title: 'Hyderabad Showroom', address: [ '2nd Floor, Tirumala Platinum,', 'Near Gachibowli Flyover,', 'Gachibowli,', 'Hyderabad - 500032' ] }*/ ]; const showRoomTimings = { start: '11am', end: '7pm' }; export default class Contact extends Component { render() { const styles = require('./Contact.scss'); const addressGroups = groupBy(addressList, address => address.city); console.log(addressGroups); return ( <div className={styles.contactContainer}> <h2>Contact us</h2> <div className={styles.addressContainer + ' col-md-12 col-xs-12'}> <p><span className={styles.heading}>SHOWROOM HOURS</span> Open all days {showRoomTimings.start} - {showRoomTimings.end}</p> { addressGroups.map( group => { return ( <div className="col-md-12"> <h6 className={styles.heading}>{group.key}</h6> { group.data.map( address => { return ( <div key={address.id} className={ styles.addressCard + ' col-md-4 col-xs-12'} > <h6 className={styles.heading}>{address.title}</h6> {address.address.map((line) => { return (<p key={line}>{line}</p>); })} <p className={address.landMark ? '' : 'hidden'}><span className="bold">LandMark: </span>{address.landMark}</p> </div> ); }) } </div>); }) } </div> </div> ); } }
client/app/partials/app-nav-bar/index.js
nebulae-io/coteries
import React, { Component } from 'react'; import { IndexLink, Link } from 'react-router'; import cns from 'classnames'; import Flex from 'components/flex'; import styles from './style.scss'; function mapStateToProps(state) { return {}; } function mapDispatchToProps(dispatch) { return { todoActions: bindActionCreators(todoActionCreators, dispatch), counterActions: bindActionCreators(counterActionCreators, dispatch) }; } class AppNavBar extends Component { render() { let linkProps = { activeClassName: styles.activedNavItem, className: cns(styles.navItem, 'link link--flat') }; return ( <Flex className={styles.navBar} row justifyContent='space-between' {...this.props}> <Flex tag='ul' row> <IndexLink to='/' {...linkProps}>{__('terms.home')}</IndexLink> <Link to='/places' {...linkProps}>{__('terms.places')}</Link> <Link to='/events' {...linkProps}>{__('terms.events')}</Link> <Link to='/stuffs' {...linkProps}>{__('terms.stuffs')}</Link> </Flex> </Flex> ); } } export default AppNavBar;
node_modules/react-bootstrap/es/Alert.js
jkahrs595/website
import _Object$values from 'babel-runtime/core-js/object/values'; import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, bsStyles, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; import { State } from './utils/StyleConfig'; var propTypes = { onDismiss: React.PropTypes.func, closeLabel: React.PropTypes.string }; var defaultProps = { closeLabel: 'Close alert' }; var Alert = function (_React$Component) { _inherits(Alert, _React$Component); function Alert() { _classCallCheck(this, Alert); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Alert.prototype.renderDismissButton = function renderDismissButton(onDismiss) { return React.createElement( 'button', { type: 'button', className: 'close', onClick: onDismiss, 'aria-hidden': 'true', tabIndex: '-1' }, React.createElement( 'span', null, '\xD7' ) ); }; Alert.prototype.renderSrOnlyDismissButton = function renderSrOnlyDismissButton(onDismiss, closeLabel) { return React.createElement( 'button', { type: 'button', className: 'close sr-only', onClick: onDismiss }, closeLabel ); }; Alert.prototype.render = function render() { var _extends2; var _props = this.props; var onDismiss = _props.onDismiss; var closeLabel = _props.closeLabel; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['onDismiss', 'closeLabel', 'className', 'children']); var _splitBsProps = splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var dismissable = !!onDismiss; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'dismissable')] = dismissable, _extends2)); return React.createElement( 'div', _extends({}, elementProps, { role: 'alert', className: classNames(className, classes) }), dismissable && this.renderDismissButton(onDismiss), children, dismissable && this.renderSrOnlyDismissButton(onDismiss, closeLabel) ); }; return Alert; }(React.Component); Alert.propTypes = propTypes; Alert.defaultProps = defaultProps; export default bsStyles(_Object$values(State), State.INFO, bsClass('alert', Alert));
client/src/Title.js
mit-teaching-systems-lab/swipe-right-for-cs
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import './Title.css'; import logoSrc from './img/swipe.gif'; import {Interactions} from './shared/data.js'; import Swipeable from './components/Swipeable.js'; import Delay from './components/Delay.js'; import SwipeCue from './components/SwipeCue.js'; class Title extends Component { constructor(props) { super(props); this.onSwipeRight = this.onSwipeRight.bind(this); } // prefetch image before animation starts componentDidMount() { const image = new Image(); image.src = logoSrc; } onSwipeRight() { const {onInteraction, onDone} = this.props; onInteraction(Interactions.play()); onDone(); } render() { const swipeHeight = 128; return ( <div className="Title"> <p className="Title-intro"> Swipe Right for CS! </p> <Delay wait={250}> <Swipeable style={{width: '100%'}} height={swipeHeight} onSwipeRight={this.onSwipeRight}> <div className="Title-swipe"> <SwipeCue style={{position: 'absolute', top: (swipeHeight/2)}} /> <img className="Title-logo" alt="Logo" src={logoSrc} height={128} width={128} /> <div>Swipe right to play!</div> </div> </Swipeable> </Delay> </div> ); } } Title.propTypes = { onInteraction: PropTypes.func.isRequired, onDone: PropTypes.func.isRequired }; export default Title;
docs/src/app/components/pages/components/DatePicker/ExampleInline.js
spiermar/material-ui
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;
bayty/src/components/LoginForm.js
Asmaklf/bayty
import React, { Component } from 'react'; import { Text } from 'react-native'; import { connect } from 'react-redux'; import { emailChanged, passwordChanged, loginUser } from '../actions'; import { Card, CardSection, Button, Input, Spinner } from './common'; class LoginForm extends Component { onEmailChange(text) { this.props.emailChanged(text); } onPasswordChange(text) { this.props.passwordChanged(text); } onButtonPress() { const { email, password } = this.props; this.props.loginUser({ email, password }); } renderButton() { if (this.props.loading) { return <Spinner size="large" />; } return ( <Button onPress={this.onButtonPress.bind(this)}> Login </Button> ); } render() { return ( <Card> <CardSection> <Input label="Email" placeholder="[email protected]" onChangeText={this.onEmailChange.bind(this)} value={this.props.email} /> </CardSection> <CardSection> <Input secureTextEntry label="Password" placeholder="password" onChangeText={this.onPasswordChange.bind(this)} value={this.props.password} /> </CardSection> <Text style={styles.errorTextStyle}> {this.props.error} </Text> <CardSection> {this.renderButton()} </CardSection> </Card> ); } } const mapStateToProps = state => { return { email: state.auth.email, password: state.auth.password, error: state.auth.error, loading: state.auth.loading }; }; const styles = { errorTextStyle: { fontSize: 20, alignSelf: 'center', color: 'red' } }; export default connect(mapStateToProps, { emailChanged, passwordChanged, loginUser })(LoginForm);
docs/src/Anchor.js
pandoraui/react-bootstrap
import React from 'react'; const Anchor = React.createClass({ propTypes: { id: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]) }, render() { return ( <a id={this.props.id} href={'#' + this.props.id} className="anchor"> <span className="anchor-icon">#</span> {this.props.children} </a> ); } }); export default Anchor;
app/components/dashboard/home/CustomTagCloud.js
mchlltt/mementoes
// Import dependencies and components. import React from 'react'; import {TagCloud} from 'react-tagcloud'; // Create and export component class. // I created this custom component because the default TagCloud refreshed anytime the page state changed. export default class CustomTagCloud extends TagCloud { constructor(props) { super(props); this.state = {}; } // This method was the main purpose/fix. It checks whether the tags themselves have actually updated. shouldComponentUpdate(nextProps) { return this.props.tags !== nextProps.tags; } render() { return ( <TagCloud tags={this.props.tags} maxSize={this.props.maxSize} minSize={this.props.minSize} colorOptions={this.props.colorOptions} onClick={this.props.onClick} /> ) } }
client/app/bundles/HelloWorld/components/general_components/table/sortable_table/table_sorting_mixin.js
ddmck/Empirical-Core
// This React mixin handles client-side sorting. // Use it ljke so: // Call defineSorting() in componentDidMount() of your component. // Call sortResults() when a sort changes (use as a handler function) // Call applySorting() on your data before displaying it in render(). import React from 'react' import _ from 'underscore' import naturalCmp from 'underscore.string/naturalCmp' export default { getInitialState: function() { return { currentSort: {}, sortConfig: {} }; }, // Sign = 1 or -1 depending on whether the sort is normal or reverse order numericSort: function(sign, fieldName, a, b) { return (a[fieldName] - b[fieldName]) * sign; }, // Sign = 1 or -1 depending on whether the sort is normal or reverse order naturalSort: function(sign, fieldName, a, b) { return s.naturalCmp(a[fieldName], b[fieldName]) * sign; }, // config = {field: string, sortFunc: function, ...} // currentSort = {field: string, direction: string ('asc' or 'desc')} defineSorting: function(config, currentSort) { // Convert string configuration to functions. _.each(config, function(value, key) { if (!_.isFunction(value)) { switch(value) { case 'numeric': config[key] = this.numericSort; break case 'natural': config[key] = this.naturalSort; break; default: throw "Sort function named '" + value + "' not recognized"; } } }.bind(this)); this.setState({ sortConfig: config, currentSort: currentSort }); }, applySorting: function(results) { var sortDirection = this.state.currentSort.direction, sortByFieldName = this.state.currentSort.field; if (!sortDirection && !sortByFieldName) { return results; } // Flip the sign of the return value to sort in reverse var sign = (sortDirection === 'asc' ? 1 : -1); var sortFunc = this.state.sortConfig[sortByFieldName]; if (!sortFunc) { throw "Sort function not defined for '" + sortByFieldName + "' field"; } // Partially apply arguments so that the new func has signature -> (a, b) var appliedSort = _.partial(sortFunc, sign, sortByFieldName); results.sort(appliedSort); return results; }, sortResults: function(after, sortByFieldName, sortDirection) { this.setState({ currentSort: { field: sortByFieldName, direction: sortDirection } }, after); } };
actor-apps/app-web/src/app/components/activity/GroupProfileMembers.react.js
fengchenlianlian/actor-platform
import _ from 'lodash'; import React from 'react'; import { PureRenderMixin } from 'react/addons'; import DialogActionCreators from 'actions/DialogActionCreators'; import LoginStore from 'stores/LoginStore'; import AvatarItem from 'components/common/AvatarItem.react'; const GroupProfileMembers = React.createClass({ propTypes: { groupId: React.PropTypes.number, members: React.PropTypes.array.isRequired }, mixins: [PureRenderMixin], onClick(id) { DialogActionCreators.selectDialogPeerUser(id); }, onKickMemberClick(groupId, userId) { DialogActionCreators.kickMember(groupId, userId); }, render() { let groupId = this.props.groupId; let members = this.props.members; let myId = LoginStore.getMyId(); let membersList = _.map(members, (member, index) => { let controls; let canKick = member.canKick; if (canKick === true && member.peerInfo.peer.id !== myId) { controls = ( <div className="controls pull-right"> <a onClick={this.onKickMemberClick.bind(this, groupId, member.peerInfo.peer.id)}>Kick</a> </div> ); } return ( <li className="profile__list__item row" key={index}> <a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}> <AvatarItem image={member.peerInfo.avatar} placeholder={member.peerInfo.placeholder} size="small" title={member.peerInfo.title}/> </a> <div className="col-xs"> <a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}> <span className="title"> {member.peerInfo.title} </span> </a> {controls} </div> </li> ); }, this); return ( <ul className="profile__list profile__list--members"> <li className="profile__list__item profile__list__item--header">{members.length} members</li> {membersList} </ul> ); } }); export default GroupProfileMembers;
src/components/rows/input/AnnualLeave.js
hikurangi/day-rate-calculator
import React from 'react'; import { TableRow, TableRowColumn } from '@material-ui/core/Table'; import TextField from '@material-ui/core/TextField'; const AnnualLeave = ({ handleChange }) => { return ( <TableRow> <TableRowColumn> <h3>Your total number of annual leave days</h3> </TableRowColumn> <TableRowColumn> <TextField name="annualLeave" type="number" hintText="Your total number of annual leave days" onChange={handleChange} /> </TableRowColumn> </TableRow> ); }; export default AnnualLeave;
src/index.js
datchley/react-scale-text
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import warn from 'warning'; import { generate as shortId } from 'shortid'; import shallowEqual from './shallow-equal'; import getFillSize from './get-fillsize'; import { getStyle, css } from './dom-utils'; class ScaleText extends Component { constructor(props) { super(props); this.state = { size: null }; this._resizing = false; this._invalidChild = false; this._mounted = false; this._handleResize = () => { if (!this._resizing) { requestAnimationFrame(this.handleResize.bind(this)); } this._resizing = true; }; } componentDidMount() { const { children } = this.props; this._mounted = true; this._invalidChild = React.Children.count(children) > 1; warn(!this._invalidChild, `'ScaleText' expects a single node as a child, but we found ${React.Children.count(children)} children instead. No scaling will be done on this subtree` ); if (this.shouldResize()) { this.resize(); window.addEventListener('resize', this._handleResize); } } componentDidUpdate(prevProps) { // compare children's props for change if (!shallowEqual(prevProps.children.props, this.props.children.props) || prevProps.children !== this.props.children || prevProps !== this.props) { this.resize(); } } componentWillUnmount() { if (!this.shouldResize()) { window.removeEventListener('resize', this._handleResize); } } shouldResize() { return !this._invalidChild; } handleResize() { this._resizing = false; this.resize(); } resize() { const { minFontSize, maxFontSize, widthOnly } = this.props; if (!this._mounted || !this._wrapper) return; if (this.ruler) { this.clearRuler(); } this.createRuler(); const fontSize = getFillSize( this.ruler, minFontSize || Number.NEGATIVE_INFINITY, maxFontSize || Number.POSITIVE_INFINITY, widthOnly ); this.setState({ size: parseFloat(fontSize, 10), complete: true }, () => { this.clearRuler(); }); } createRuler() { // Create copy of wrapper for sizing this.ruler = this._wrapper.cloneNode(true); this.ruler.id = shortId(); css(this.ruler, { position: 'absolute', top: '0px', left: 'calc(100vw * 2)', width: getStyle(this._wrapper, 'width'), height: getStyle(this._wrapper, 'height') }); document.body.appendChild(this.ruler); } clearRuler() { if (this.ruler) { document.body.removeChild(this.ruler); } this.ruler = null; } render() { const { size: fontSize } = this.state; const { children, widthOnly } = this.props; const overflowStyle = widthOnly ? { overflowY: 'visible', overflowX: 'hidden', height: 'auto' } : { overflow: 'hidden' }; const child = React.isValidElement(children) ? React.Children.only(children) : (<span>{children}</span>); const style = { fontSize: fontSize ? `${fontSize.toFixed(2)}px` : 'inherit', width: '100%', height: '100%', ...overflowStyle // overflow: 'hidden' }; const childProps = { fontSize: fontSize ? parseFloat(fontSize.toFixed(2)) : 'inherit' }; return ( <div className="scaletext-wrapper" ref={(c) => { this._wrapper = c; }} style={style} > { React.cloneElement(child, childProps) } </div> ); } } ScaleText.propTypes = { children: PropTypes.node.isRequired, minFontSize: PropTypes.number.isRequired, maxFontSize: PropTypes.number.isRequired, widthOnly: PropTypes.bool }; ScaleText.defaultProps = { minFontSize: Number.NEGATIVE_INFINITY, maxFontSize: Number.POSITIVE_INFINITY, widthOnly: false }; // export default ScaleText; module.exports = ScaleText;
examples/src/components/CustomRender.js
pedroseac/react-select
import React from 'react'; import Select from 'react-select'; var DisabledUpsellOptions = React.createClass({ displayName: 'DisabledUpsellOptions', propTypes: { label: React.PropTypes.string, }, getInitialState () { return {}; }, setValue (value) { this.setState({ value }); console.log('Support level selected:', value.label); }, renderLink: function() { return <a style={{ marginLeft: 5 }} href="/upgrade" target="_blank">Upgrade here!</a>; }, renderOption: function(option) { return <span style={{ color: option.color }}>{option.label} {option.link}</span>; }, renderValue: function(option) { return <strong style={{ color: option.color }}>{option.label}</strong>; }, render: function() { var options = [ { label: 'Basic customer support', value: 'basic', color: '#E31864' }, { label: 'Premium customer support', value: 'premium', color: '#6216A3' }, { label: 'Pro customer support', value: 'pro', disabled: true, link: this.renderLink() }, ]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select placeholder="Select your support level" options={options} optionRenderer={this.renderOption} onChange={this.setValue} value={this.state.value} valueRenderer={this.renderValue} /> <div className="hint">This demonstates custom render methods and links in disabled options</div> </div> ); } }); module.exports = DisabledUpsellOptions;
packages/v4/src/content/extensions/extensions-data-list.js
patternfly/patternfly-org
import React from 'react'; import { DataList, DataListItem, DataListItemRow, DataListItemCells, DataListCell, Title } from '@patternfly/react-core'; export const ExtensionsDataList = (props) => ( <DataList aria-label="Community extensions"> {props.data.map(item => { const links = item.links.map((link, index) => { return ( <span key={index} className="pf-c-extensions__link"> <a href={link.href} target="_blank" rel="noopener noreferrer">{link.name}</a> </span> ); }); return ( <DataListItem aria-labelledby="simple-item1"> <DataListItemRow> <DataListItemCells dataListCells={[ <DataListCell key="primary content" width={2}> <Title headingLevel="h3">{item.component}</Title> <span className="pf-c-extensions__component-description">{item.description}</span> </DataListCell>, <DataListCell key="secondary content">{links}</DataListCell> ]} /> </DataListItemRow> </DataListItem> ) })} </DataList> );
www/components/add-poo.js
capaj/postuj-hovna
import React from 'react' import ImgUploader from './img-uploader' import GoogleMap from './google-map' import {photo} from '../services/moonridge' import backend from '../services/moonridge' export default class AddPoo extends React.Component { constructor(...props) { super(...props) this.state = {} } addImage = (imageData) => { this.setState({error: null, image: imageData}) } submit = () => { console.log('submit', this) this.setState({inProgress: true}) var imgBase64 = this.state.image var image = imgBase64.substr(imgBase64.indexOf(',') + 1) backend.rpc('savePhoto')(image).then(photoId => { const GPS = this.state.loc var toCreate = { loc: [GPS.lat, GPS.lng], photoIds: [photoId], type: 'poo' } return photo.create(toCreate).then(created => { location.hash = `/poo/${created._id}` }) }, err => { this.setState({error: err}) console.log('err', err) }) } addLoc = (GPS) => { this.setState({loc: GPS}) } render() { var submitBtn var state = this.state if (state.loc && state.image && !state.inProgress) { submitBtn = <div className='post button ok clickable' onClick={this.submit}> <span className='glyphicon glyphicon-ok'/> </div> } var alert if (state.error) { alert = <div className='alert'> {state.error} </div> } var map if (state.loc) { map = <GoogleMap center={state.loc} zoom={17} containerClass='small-map'></GoogleMap> } return <div className='container add-form'> <div className='post item'> {map} </div> <ImgUploader onGPSRead={this.addLoc} onImageRead={this.addImage} icon={'img/poo-plain.svg'}/> {submitBtn} {alert} </div> } } AddPoo.defaultProps = { zoom: 9 }
readable/src/containers/PostDetail.js
custertian/readable
import React from 'react' import {Link} from 'react-router-dom' import {connect} from 'react-redux' import { Button, Card, Layout, Menu, Breadcrumb, Input, Tree } from 'antd' const {TextArea} = Input; const {Header, Content, Footer} = Layout const TreeNode = Tree.TreeNode class PostDetail extends React.Component { onSelect = (selectedKeys, info) => { console.log('selected', selectedKeys, info); } render() { const {post, select} = this.props console.log(post) if (!post) { // this.loading = true return <div>Loading ...</div> } return ( <Layout className="layout"> <Header> <div className="logo"/> <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['2']} style={{ lineHeight: '64px', fontSize: '20px' }}> <Menu.Item key="1">Readable[Detail]</Menu.Item> </Menu> </Header> <Content style={{ padding: '0 50px' }}> <Breadcrumb style={{ margin: '12px 0' }}> <Breadcrumb.Item> <Link to='/'>Home</Link> </Breadcrumb.Item> <Breadcrumb.Item> <Link to='/'>Posts</Link> </Breadcrumb.Item> <Breadcrumb.Item>detail</Breadcrumb.Item> </Breadcrumb> <div style={{ background: '#fff', padding: 24, minHeight: 280 }}> {post.map((post) => { if (post.id === select) { return ( <Card style={{ fontSize: 20 }} key={post.id}> <div> <p>Title: {post.title}</p> <p>Body: {post.body}</p> <p>timestamp: {post.timestamp}</p> <p>Vote score: {post.voteScore}</p> <p>Author: {post.author}</p> <p>comments number: </p> </div> </Card> ) } })} <div style={{ margin: '24px 0' }}> <TextArea rows={6} placeholder="请输入评论..." size="large"/> <Button type="primary" ghost style={{ margin: '24px 0', float: 'right' }}>comment</Button> </div> <Tree showLine defaultExpandedKeys={['0-0-0']} onSelect={this.onSelect}> <TreeNode title="parent 1" key="0-0"> <TreeNode title="parent 1-0" key="0-0-0"> <TreeNode title="leaf" key="0-0-0-0"/> <TreeNode title="leaf" key="0-0-0-1"/> <TreeNode title="leaf" key="0-0-0-2"/> </TreeNode> <TreeNode title="parent 1-1" key="0-0-1"> <TreeNode title="leaf" key="0-0-1-0"/> </TreeNode> <TreeNode title="parent 1-2" key="0-0-2"> <TreeNode title="leaf" key="0-0-2-0"/> <TreeNode title="leaf" key="0-0-2-1"/> </TreeNode> </TreeNode> </Tree> </div> </Content> <Footer style={{ textAlign: 'center' }}> Custer Tian ©2017 Created by Custer Tian </Footer> </Layout> ) } } const mapStateToProps = (state, ownProps) => { console.log('state', state) console.log('ownProps', ownProps.match.params.post_id) console.log('post', state.posts[ownProps.match.params.post_id]) return {post: state.posts, select: ownProps.match.params.post_id} } export default connect(mapStateToProps)(PostDetail)
src/SparklinesBars.js
konsumer/react-sparklines
import React from 'react'; export default class SparklinesBars extends React.Component { static propTypes = { style: React.PropTypes.object }; static defaultProps = { style: { fill: 'slategray' } }; render() { const { points, width, height, margin, style } = this.props; const barWidth = points.length >= 2 ? points[1].x - points[0].x : 0; return ( <g> {points.map((p, i) => <rect key={i} x={p.x} y={p.y} width={barWidth} height={height - p.y} style={style} /> )} </g> ) } }
app/javascript/mastodon/features/compose/components/upload_button.js
cybrespace/mastodon
import React from 'react'; import IconButton from '../../../components/icon_button'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; const messages = defineMessages({ upload: { id: 'upload_button.label', defaultMessage: 'Add media (JPEG, PNG, GIF, WebM, MP4, MOV)' }, }); const makeMapStateToProps = () => { const mapStateToProps = state => ({ acceptContentTypes: state.getIn(['media_attachments', 'accept_content_types']), }); return mapStateToProps; }; const iconStyle = { height: null, lineHeight: '27px', }; export default @connect(makeMapStateToProps) @injectIntl class UploadButton extends ImmutablePureComponent { static propTypes = { disabled: PropTypes.bool, onSelectFile: PropTypes.func.isRequired, style: PropTypes.object, resetFileKey: PropTypes.number, acceptContentTypes: ImmutablePropTypes.listOf(PropTypes.string).isRequired, intl: PropTypes.object.isRequired, }; handleChange = (e) => { if (e.target.files.length > 0) { this.props.onSelectFile(e.target.files); } } handleClick = () => { this.fileElement.click(); } setRef = (c) => { this.fileElement = c; } render () { const { intl, resetFileKey, disabled, acceptContentTypes } = this.props; return ( <div className='compose-form__upload-button'> <IconButton icon='camera' title={intl.formatMessage(messages.upload)} disabled={disabled} onClick={this.handleClick} className='compose-form__upload-button-icon' size={18} inverted style={iconStyle} /> <label> <span style={{ display: 'none' }}>{intl.formatMessage(messages.upload)}</span> <input key={resetFileKey} ref={this.setRef} type='file' multiple={false} accept={acceptContentTypes.toArray().join(',')} onChange={this.handleChange} disabled={disabled} style={{ display: 'none' }} /> </label> </div> ); } }
src/components/account/recover-password-page/index.js
datea/datea-webapp-react
import React from 'react'; import Button from '@material-ui/core/Button'; import {Tr, translatable} from '../../../i18n'; import {observer, inject} from 'mobx-react'; import AccountFormContainer from '../account-form-container'; import TextField from '@material-ui/core/TextField'; import DIcon from '../../../icons'; import './recover-password.scss'; @inject('store') @translatable @observer export default class RecoverPasswordPage extends React.Component { render() { const form = this.props.store.recoverPassView; return ( <AccountFormContainer className="recover-password-page"> {!form.success && <div> <div className="account-form-header with-icon"> <DIcon name="daterito6" /> <h3 className="title"><Tr id="RECOVER_PASSWORD.PAGE_TITLE" /></h3> </div> <div className="recover-password-content"> <div className="info-text"><Tr id="RECOVER_PASSWORD.INFO_TEXT" /></div> {!!form.error && <div className="error-msg"><Tr id={form.error} /></div> } <div className="form"> <div className="input-row"> <TextField name="email" required className="email-field" fullWidth={true} label={<Tr id="LOGIN_PAGE.EMAIL_PH" />} onChange={ev => form.setEmail(ev.target.value)} value={form.email} /> </div> <div className="form-btns"> <Button variant="raised" color="primary" type="submit" onClick={form.submit} disabled={!form.isValid}> <Tr id="SUBMIT" /> </Button> </div> </div> </div> </div> } {form.success && <div> <div className="account-form-header with-icon"> <DIcon name="daterito2" /> <h3 className="title"><Tr id="ACCOUNT_MSG.PASS_RESET_SENT_TITLE" /></h3> </div> <div className="recover-password-content reset-success"> <div className="info-text"><Tr id="ACCOUNT_MSG.PASS_RESET_SENT" /></div> <div className="info-text"><Tr id="ACCOUNT_MSG.CLOSE_TAB" /></div> <div className="form-btns"> <Button variant="raised" color="primary" onClick={form.resubmit}> <Tr id="RESUBMIT" /> </Button> </div> {form.resubmitted && <div className="resubmit-success green-text"><Tr id="ACCOUNT_MSG.PASS_RESET_RESENT" /></div> } {!!form.error && <div className="error-msg"><Tr id={form.error} /></div> } </div> </div> } </AccountFormContainer> ) } }
packages/bonde-admin/src/components/data-grid/hocs/col-hoc.js
ourcities/rebu-client
import React from 'react' import classnames from 'classnames' export default (WrappedComponent) => { return class PP extends React.Component { render () { const colProps = { className: classnames('flex-auto', this.props.className) } return ( <WrappedComponent {...this.props} {...colProps} /> ) } } }
app/containers/EditUserProfile.js
alexko13/block-and-frame
import React from 'react'; import userHelpers from '../utils/userHelpers'; import authHelpers from '../utils/authHelpers'; import MenuBar from '../components/MenuBar'; import UserProfileForm from '../components/users/UserProfileForm'; import ImageUpload from '../components/users/Uploader'; import EditSuccess from '../components/users/EditSuccess'; // TODO: Confirm profile deletion, msg about success, redirect user to home. class UserProfile extends React.Component { constructor(props) { super(props); this.state = { email: '', username: '', bio: '', location: '', isTraveling: null, sucess: false, instagram: '', instagramProfilePic: '', }; this.onNameChange = this.onNameChange.bind(this); this.onEmailChange = this.onEmailChange.bind(this); this.onLocationChange = this.onLocationChange.bind(this); this.onLocationSelect = this.onLocationSelect.bind(this); this.onBioChange = this.onBioChange.bind(this); this.onTravelingChange = this.onTravelingChange.bind(this); this.handleProfileSubmit = this.handleProfileSubmit.bind(this); this.handleDeleteUser = this.handleDeleteUser.bind(this); this.preventDefaultSubmit = this.preventDefaultSubmit.bind(this); } componentDidMount() { userHelpers.getCurrentUserData() .then((user) => { console.log('user in comp did mount', user.data); this.setState({ email: user.data.email, username: user.data.username, bio: user.data.bio, location: user.data.location, isTraveling: user.data.is_traveling, avatarId: user.data.avatar_id, instagramProfilePic: user.data.instagram_profile_pic, instagram: user.data.instagram_username, }); }); } onNameChange(e) { this.setState({ username: e.target.value }); } onEmailChange(e) { this.setState({ email: e.target.value }); } onLocationChange(value) { this.setState({ location: value }); } onLocationSelect(location) { this.setState({ location: location.label }); } onBioChange(e) { this.setState({ bio: e.target.value }); } onTravelingChange(e) { this.setState({ isTraveling: e.target.checked }); } handleProfileSubmit() { userHelpers.updateUser(this.state) .then((user) => { console.log(user); this.setState({ success: true, duplicateEmail: false, }); }) .catch((err) => { if (err.data.constraint === 'users_email_unique') { this.setState({ success: false, duplicateEmail: true, }); } console.log(err); }); } handleDeleteUser() { userHelpers.deleteUser(). then((info) => { console.log(info); authHelpers.logout(); this.context.router.push('/signup'); }) .catch((err) => { console.log(err); }); } preventDefaultSubmit(e) { e.preventDefault(); } render() { return ( <div> <MenuBar /> <div className="ui container top-margin-bit"> <h1 className="ui dividing header" id="editprofileheader"> Edit Profile: </h1> </div> <div className="ui raised text container segment"> <div className="ui container centered"> <ImageUpload avatarId={this.state.avatarId} instagramProfilePic={this.state.instagramProfilePic} /> <UserProfileForm username={this.state.username} email={this.state.email} location={this.state.location} bio={this.state.bio} isTraveling={this.state.isTraveling} onNameChange={this.onNameChange} onEmailChange={this.onEmailChange} onLocationChange={this.onLocationChange} onLocationSelect={this.onLocationSelect} onBioChange={this.onBioChange} onTravelingChange={this.onTravelingChange} onDeleteUser={this.handleDeleteUser} onProfileSubmit={this.handleProfileSubmit} preventDefaultSubmit={this.preventDefaultSubmit} /> <EditSuccess success={this.state.success} duplicateEmail={this.state.duplicateEmail} /> </div> </div> </div> ); } } UserProfile.contextTypes = { router: React.PropTypes.object.isRequired, }; export default UserProfile;
src/components/App.js
jozanza/pixels
import React from 'react'; import { compose, mapProps, withHandlers, withState } from 'recompose'; import styled, { ThemeProvider } from 'styled-components'; import * as actionCreators from '../actionCreators'; import ArtboardSection from './ArtboardSection'; import ToolbarSection from './ToolbarSection'; import MenuWrapper from './MenuWrapper'; import ToolMenu from './ToolMenu'; import LayersMenu from './LayersMenu'; import DocumentMenu from './DocumentMenu'; import PreviewMenu from './PreviewMenu'; import theme from '../theme'; import { toDataURI } from '../utils'; const transformProps = props => { return { ...props, selectedTool: { name: props.tool, ...props.toolbar[props.tool] } }; }; const enhance = compose( mapProps(transformProps), withState('bottomMenuHeight', 'setBottomMenuHeight', '25vh'), withHandlers(actionCreators) ); export default enhance(props => ( <ThemeProvider theme={theme}> <main> <ArtboardSection {...props} /> <ToolbarSection {...props}> <ToolMenu active={props.panel === 'tool'} {...props} /> <LayersMenu active={props.panel === 'layers'} {...props} /> <PreviewMenu active={props.panel === 'preview'} {...props} /> {/* <DocumentMenu active={props.panel === 'document'} {...props} /> */} </ToolbarSection> </main> </ThemeProvider> ));
packages/fyndiq-ui-test/stories/component-modal.js
fyndiq/fyndiq-ui
import React from 'react' import { storiesOf, action } from '@storybook/react' import Button from 'fyndiq-component-button' import Modal, { ModalButton, confirm, Confirm, ConfirmWrapper, } from 'fyndiq-component-modal' import { Warning } from 'fyndiq-icons' import './component-modal.css' storiesOf('Modal', module) .addWithInfo('default', () => <ModalButton>Content</ModalButton>) .addWithInfo('custom modal styles', () => ( <ModalButton button="Open Custom Modal"> <Modal overlayClassName="test-overlay--red" wrapperClassName="test-wrapper--black" > Content with black background on a red transparent overlay </Modal> </ModalButton> )) .addWithInfo('custom button', () => ( <ModalButton button={<Button type="primary">Open Modal</Button>}> Content </ModalButton> )) .addWithInfo('custom close button', () => ( <ModalButton> <Modal> {({ onClose }) => <button onClick={onClose}>Close modal</button>} </Modal> </ModalButton> )) .addWithInfo('forced modal', () => ( <ModalButton button="Open forced modal"> <Modal forced> {({ onClose }) => ( <div style={{ padding: 20 }}> You cannot close me by clicking outside or pressing ESC. The only way to close me is to use a custom close button.<br /> <button onClick={onClose}>Close modal</button> </div> )} </Modal> </ModalButton> )) .addWithInfo('confirm dialog', () => ( <React.Fragment> <ConfirmWrapper /> <Button onClick={async () => { const validate = await confirm( <Confirm type="warning" icon={<Warning />} title="Do you really want to delete that thing?" message="If you delete it, there is no way back" validateButton="Delete" />, ) if (validate) { action('validated')() } else { action('not validated')() } }} > Delete something </Button> </React.Fragment> ))
packages/material-ui-icons/src/SettingsInputAntenna.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let SettingsInputAntenna = props => <SvgIcon {...props}> <path d="M12 5c-3.87 0-7 3.13-7 7h2c0-2.76 2.24-5 5-5s5 2.24 5 5h2c0-3.87-3.13-7-7-7zm1 9.29c.88-.39 1.5-1.26 1.5-2.29 0-1.38-1.12-2.5-2.5-2.5S9.5 10.62 9.5 12c0 1.02.62 1.9 1.5 2.29v3.3L7.59 21 9 22.41l3-3 3 3L16.41 21 13 17.59v-3.3zM12 1C5.93 1 1 5.93 1 12h2c0-4.97 4.03-9 9-9s9 4.03 9 9h2c0-6.07-4.93-11-11-11z" /> </SvgIcon>; SettingsInputAntenna = pure(SettingsInputAntenna); SettingsInputAntenna.muiName = 'SvgIcon'; export default SettingsInputAntenna;
src/NodeInputListItem.js
falcon-client/hawk
import React from 'react'; export default class NodeInputListItem extends React.Component { constructor(props) { super(props); this.state = { hover: false }; } onMouseUp(e) { e.stopPropagation(); e.preventDefault(); this.props.onMouseUp(this.props.index); } onMouseOver() { this.setState({ hover: true }); } onMouseOut() { this.setState({ hover: false }); } noop(e) { e.stopPropagation(); e.preventDefault(); } render() { const { name } = this.props.item; const { hover } = this.state; return ( <li> <a onClick={e => this.noop(e)} onMouseUp={e => this.onMouseUp(e)} href="#" > <i className={hover ? 'fa fa-circle-o hover' : 'fa fa-circle-o'} onMouseOver={() => { this.onMouseOver(); }} onMouseOut={() => { this.onMouseOut(); }} /> {name} </a> </li> ); } }
src/containers/Asians/TabControls/BreakCategorySettings/BreakCategoryRounds/index.js
westoncolemanl/tabbr-web
import React from 'react' import { connect } from 'react-redux' import CreateRounds from './CreateRounds' import ViewRounds from './ViewRounds' export default connect(mapStateToProps)(({ breakCategory, breakRounds, disabled }) => { const filterBreakRounds = breakRoundToMatch => breakRoundToMatch.breakCategory === breakCategory._id const breakRoundsThisBreakCategory = breakRounds.filter(filterBreakRounds) if (breakRoundsThisBreakCategory.length === 0) { return <CreateRounds breakCategory={breakCategory} /> } else { return <ViewRounds breakCategory={breakCategory} disabled={disabled} /> } }) function mapStateToProps (state, ownProps) { return { tournament: state.tournaments.current.data, breakRounds: Object.values(state.breakRounds.data) } }
stories/list/index.js
shulie/dh-component
import React from 'react'; import { storiesOf, action, linkTo } from '@kadira/storybook'; import withReadme from 'storybook-readme/with-readme'; import { List, Menu, Dropdown, Icon, Avatar} from '../../src'; import listReadme from './list.md'; const addWithInfoOptions = { inline: true, propTables: false }; const menu = ( <Menu> <Menu.Item> <span>菜单1</span> </Menu.Item> <Menu.Item> <span>菜单2</span> </Menu.Item> </Menu> ); const suffix = ( <Dropdown overlay={menu} trigger="click"> <Icon type="list-circle"/> </Dropdown> ); storiesOf('列表组件', module) .addDecorator(withReadme(listReadme)) .addWithInfo('默认列表', () => ( <List mode="only" itemClassName="wjb-" itemStyles={{color: 'red'}}> <List.Item key="1" onClick={action('onClick')}> 我是默认列表 </List.Item> <List.Item key="2" onClick={action('onClick')}> 我是默认列表 </List.Item> <List.Item key="3" onClick={action('onClick')}> 我是默认列表 </List.Item> </List> ), addWithInfoOptions) .addWithInfo('单行选择', () => ( <List mode="only" selectedKeys={['1']} onChange={action('onChange')}> <List.Item key="1"> 我可以被操作选择</List.Item> <List.Item key="2"> 我可以被操作选择</List.Item> <List.Item key="3"> 我可以被操作选择</List.Item> </List> ), addWithInfoOptions) .addWithInfo('单行选择不可变', () => ( <List mode="only" immutable icon onChange={action('onChange')}> <List.Item key="1"> 我可以被操作选择, 但是不可变</List.Item> <List.Item key="2"> 我可以被操作选择, 但是不可变</List.Item> <List.Item key="3"> 我可以被操作选择, 但是不可变</List.Item> </List> ), addWithInfoOptions) .addWithInfo('多行选择', () => ( <List mode="multiple" icon onChange={action('onChange')}> <List.Item key="1"> 来点我一下</List.Item> <List.Item key="2"> 来点我一下</List.Item> <List.Item key="3"> 来点我一下</List.Item> </List> ), addWithInfoOptions) .addWithInfo('前缀图标', () => ( <List> <List.Item key="1" prefix={<Avatar />}>Avatar的前置图标</List.Item> <List.Item key="2" prefix={<Avatar src="http://7xr8fr.com1.z0.glb.clouddn.com/IMG_2197.JPG"/>} > Avatar用户传入图片 </List.Item> <List.Item key="3" prefix={<Avatar>OK</Avatar>} > Avatar自定义中间元素 </List.Item> <List.Item key="4" prefix={<Avatar radius={false}>中国</Avatar>} > 我是方形的前置元素 </List.Item> </List> ), addWithInfoOptions) .addWithInfo('后缀图标', () => ( <List> <List.Item key="1" suffix={suffix}> Avatar用户传入图片</List.Item> <List.Item key="2" suffix={suffix}> Avatar用户传入图片</List.Item> <List.Item key="3" suffix={suffix}> Avatar用户传入图片</List.Item> <List.Item key="4" suffix={suffix}> Avatar用户传入图片</List.Item> <List.Item key="5" suffix={suffix}> Avatar用户传入图片</List.Item> </List> ), addWithInfoOptions)
frontend/src/components/eois/modals/withdrawApplication/withdrawApplicationForm.js
unicef/un-partner-portal
import React from 'react'; import { reduxForm } from 'redux-form'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import TextFieldForm from '../../../forms/textFieldForm'; const messages = { label: 'Justification', placeholder: 'Provide justification of retraction', }; const styleSheet = () => ({ spread: { minWidth: 500, }, }); const WithdrawAward = (props) => { const { classes, handleSubmit } = props; return ( <form onSubmit={handleSubmit}> <TextFieldForm className={classes.spread} label={messages.label} placeholder={messages.placeholder} fieldName="withdraw_reason" textFieldProps={{ multiline: true, InputProps: { inputProps: { maxLength: '5000', }, }, }} /> </form > ); }; WithdrawAward.propTypes = { /** * callback for form submit */ handleSubmit: PropTypes.func.isRequired, classes: PropTypes.object, }; const formWithdrawAward = reduxForm({ form: 'withdrawApplication', })(WithdrawAward); export default withStyles(styleSheet)(formWithdrawAward);
__tests__/components/Collapsible-test.js
nickjvm/grommet
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React from 'react'; import renderer from 'react-test-renderer'; import Collapsible from '../../src/js/components/Collapsible'; // needed because this: // https://github.com/facebook/jest/issues/1353 jest.mock('react-dom'); describe('Collapsible', () => { it('has correct default options', () => { const component = renderer.create( <Collapsible /> ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); });
packages/components/src/Actions/ActionFile/File.stories.js
Talend/ui
import React from 'react'; import { action } from '@storybook/addon-actions'; import Action from '../Action'; const myAction = { label: 'Click me', 'data-feature': 'actionfile', icon: 'talend-upload', onChange: action('You changed me'), displayMode: 'file', }; export default { title: 'Buttons/File', decorators: [story => <div className="col-lg-offset-2 col-lg-8">{story()}</div>], }; export const Default = () => ( <div> <p>By default :</p> <Action id="default" {...myAction} /> <p>With hideLabel option</p> <Action id="hidelabel" {...myAction} hideLabel /> <p>In progress</p> <Action id="inprogress" {...myAction} inProgress /> <p>Disabled</p> <Action id="disabled" {...myAction} disabled /> <p>Reverse display</p> <Action id="reverseDisplay" {...myAction} iconPosition="right" /> <p>Transform icon</p> <Action id="reverseDisplay" {...myAction} iconTransform="rotate-180" /> <p>Custom tooltip</p> <Action id="default" {...myAction} tooltipLabel="Custom label here" /> <p>Bootstrap style</p> <Action id="default" {...myAction} bsStyle="primary" tooltipLabel="Custom label here" /> <Action id="default" {...myAction} className="btn-default btn-inverse" tooltipLabel="Custom label here" /> </div> );
client/accept-invite/controller.js
ironmanLee/my_calypso
/** * External Dependencies */ import React from 'react'; /** * Internal Dependencies */ import i18n from 'lib/mixins/i18n'; import titleActions from 'lib/screen-title/actions'; import Main from './main'; export default { acceptInvite( context ) { titleActions.setTitle( i18n.translate( 'Accept Invite', { textOnly: true } ) ); React.unmountComponentAtNode( document.getElementById( 'secondary' ) ); React.render( React.createElement( Main, context.params ), document.getElementById( 'primary' ) ); } };
src/svg-icons/action/settings-cell.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsCell = (props) => ( <SvgIcon {...props}> <path d="M7 24h2v-2H7v2zm4 0h2v-2h-2v2zm4 0h2v-2h-2v2zM16 .01L8 0C6.9 0 6 .9 6 2v16c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V2c0-1.1-.9-1.99-2-1.99zM16 16H8V4h8v12z"/> </SvgIcon> ); ActionSettingsCell = pure(ActionSettingsCell); ActionSettingsCell.displayName = 'ActionSettingsCell'; ActionSettingsCell.muiName = 'SvgIcon'; export default ActionSettingsCell;
test/custom-control-component-spec.js
maludwig/react-redux-form
/* eslint react/no-multi-comp:0 react/jsx-no-bind:0 */ import { assert } from 'chai'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import TestUtils from 'react-dom/test-utils'; import { Provider } from 'react-redux'; import { modelReducer, formReducer, Control } from '../src'; import { testCreateStore } from './utils'; describe('custom <Control /> components', () => { class CustomText extends Component { handleChange(e) { const { customOnChange } = this.props; const value = e.target.value.toUpperCase(); customOnChange(value); } render() { return ( <div> <input onChange={e => this.handleChange(e)} /> </div> ); } } CustomText.propTypes = { customOnChange: PropTypes.func }; class FamiliarText extends Component { render() { const { onChange } = this.props; return ( <div> <input onChange={e => onChange(e)} /> </div> ); } } FamiliarText.propTypes = { onChange: PropTypes.func }; class CustomCheckbox extends Component { render() { const { onChange, value } = this.props; return ( <span onClick={() => onChange(value)} /> ); } } CustomCheckbox.propTypes = { onChange: PropTypes.func, value: PropTypes.any, }; const MinifiedText = class MT extends Component { render() { const { onChange } = this.props; return ( <div> <input onChange={e => onChange(e)} /> </div> ); } }; MinifiedText.propTypes = { onChange: PropTypes.func }; it('should handle custom prop mappings', () => { const store = testCreateStore({ testForm: formReducer('test'), test: modelReducer('test', { foo: 'bar' }), }); const field = TestUtils.renderIntoDocument( <Provider store={store}> <Control model="test.foo" component={CustomText} mapProps={{ customOnChange: (props) => props.onChange, }} /> </Provider> ); const control = TestUtils.findRenderedDOMComponentWithTag(field, 'input'); control.value = 'testing'; TestUtils.Simulate.change(control); assert.equal( store.getState().test.foo, 'TESTING'); }); it('should handle string prop mappings', () => { const store = testCreateStore({ testForm: formReducer('test'), test: modelReducer('test', { foo: 'bar' }), }); const field = TestUtils.renderIntoDocument( <Provider store={store}> <Control.text model="test.foo" component={FamiliarText} /> </Provider> ); const control = TestUtils.findRenderedDOMComponentWithTag(field, 'input'); control.value = 'testing'; TestUtils.Simulate.change(control); assert.equal( store.getState().test.foo, 'testing'); }); it('should work with minified components (no displayName)', () => { const store = testCreateStore({ testForm: formReducer('test'), test: modelReducer('test', { foo: 'bar' }), }); const field = TestUtils.renderIntoDocument( <Provider store={store}> <Control.text model="test.foo" component={MinifiedText} /> </Provider> ); const control = TestUtils.findRenderedDOMComponentWithTag(field, 'input'); control.value = 'testing'; TestUtils.Simulate.change(control); assert.equal( store.getState().test.foo, 'testing'); }); it('should work with custom checkboxes', () => { const store = testCreateStore({ testForm: formReducer('test'), test: modelReducer('test', { foo: true }), }); const field = TestUtils.renderIntoDocument( <Provider store={store}> <Control.checkbox model="test.foo" component={CustomCheckbox} /> </Provider> ); const control = TestUtils.findRenderedDOMComponentWithTag(field, 'span'); TestUtils.Simulate.click(control); assert.equal( store.getState().test.foo, false); }); it('should work with custom checkboxes (multi)', () => { const store = testCreateStore({ testForm: formReducer('test'), test: modelReducer('test', { items: [1, 2, 3] }), }); const field = TestUtils.renderIntoDocument( <Provider store={store}> <div> <Control.checkbox model="test.items[]" value={1} component={CustomCheckbox} /> <Control.checkbox model="test.items[]" value={2} component={CustomCheckbox} /> <Control.checkbox model="test.items[]" value={3} component={CustomCheckbox} /> </div> </Provider> ); const fieldControls = TestUtils.scryRenderedDOMComponentsWithTag(field, 'span'); assert.deepEqual( store.getState().test.items, [1, 2, 3]); TestUtils.Simulate.click(fieldControls[0]); assert.sameMembers( store.getState().test.items, [2, 3]); TestUtils.Simulate.click(fieldControls[1]); assert.sameMembers( store.getState().test.items, [3]); TestUtils.Simulate.click(fieldControls[0]); assert.sameMembers( store.getState().test.items, [1, 3]); }); it('should pass event to asyncValidator', (done) => { const store = testCreateStore({ testForm: formReducer('test'), test: modelReducer('test', { foo: '' }), }); class TextInput extends React.Component { render() { /* eslint-disable no-unused-vars */ const { onChangeText, defaultValue, focus, touched, ...otherProps } = this.props; /* eslint-enable */ return ( <div> <input {...otherProps} onChange={onChangeText} /> </div> ); } } TextInput.propTypes = { onChangeText: PropTypes.func, defaultValue: PropTypes.string, focus: PropTypes.bool, touched: PropTypes.bool, }; const mapProps = { defaultValue: (props) => props.modelValue, onChangeText: (props) => props.onChange, onBlur: (props) => props.onBlur, onFocus: (props) => props.onFocus, }; const asyncIsUsernameInUse = (val) => new Promise((resolve) => { assert.equal(val, 'testing'); resolve(false); done(); }); const field = TestUtils.renderIntoDocument( <Provider store={store}> <Control model="test.foo" component={TextInput} mapProps={mapProps} asyncValidateOn="blur" asyncValidators={{ usernameAvailable: (val, asyncDone) => asyncIsUsernameInUse(val) .then(inUse => asyncDone(!inUse)) .catch(() => asyncDone(true)), }} /> </Provider> ); const input = TestUtils.findRenderedDOMComponentWithTag(field, 'input'); input.value = 'testing'; TestUtils.Simulate.change(input); TestUtils.Simulate.blur(input); }); it('should pass fieldValue in mapProps', () => { const store = testCreateStore({ testForm: formReducer('test'), test: modelReducer('test', { foo: '' }), }); class TextInput extends React.Component { render() { const { focus, touched, ...otherProps } = this.props; const className = [ focus ? 'focus' : '', touched ? 'touched' : '', ].join(' '); return ( <div> <input className={className} {...otherProps} onChange={this.props.onChangeText} /> </div> ); } } TextInput.propTypes = { onChangeText: PropTypes.func, focus: PropTypes.bool, touched: PropTypes.bool, }; const mapProps = { onChange: (props) => props.onChange, onBlur: (props) => props.onBlur, onFocus: (props) => props.onFocus, focus: ({ fieldValue }) => fieldValue.focus, touched: ({ fieldValue }) => fieldValue.touched, }; const field = TestUtils.renderIntoDocument( <Provider store={store}> <Control model="test.foo" component={TextInput} mapProps={mapProps} /> </Provider> ); const input = TestUtils.findRenderedDOMComponentWithTag(field, 'input'); TestUtils.Simulate.focus(input); assert.equal(input.className.trim(), 'focus'); TestUtils.Simulate.blur(input); assert.equal(input.className.trim(), 'touched'); }); it('should not pass default mapped props to custom controls', (done) => { const store = testCreateStore({ testForm: formReducer('test'), test: modelReducer('test', { foo: 'bar' }), }); const CustomControl = (props) => { assert.notProperty(props, 'onChange'); done(); return null; }; TestUtils.renderIntoDocument( <Provider store={store}> <Control.custom model="test.foo" component={CustomControl} /> </Provider> ); }); });
gatsby-strapi-tutorial/cms/admin/admin/src/containers/HomePage/BlockLink.js
strapi/strapi-examples
/** * * BlockLink */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import cn from 'classnames'; import PropTypes from 'prop-types'; import styles from './styles.scss'; function BlockLink({ content, isDocumentation, link, title }) { return ( <a className={cn( styles.blockLink, isDocumentation ? styles.blockLinkDocumentation : styles.blockLinkCode, )} href={link} target="_blank" > <FormattedMessage {...title} /> <FormattedMessage {...content}>{message => <p>{message}</p>}</FormattedMessage> </a> ); } BlockLink.propTypes = { content: PropTypes.object.isRequired, isDocumentation: PropTypes.bool.isRequired, link: PropTypes.string.isRequired, title: PropTypes.object.isRequired, }; export default BlockLink;
src/components/Counter/Counter.js
murrayjbrown/react-redux-rxjs-stampit-babylon-universal
import React from 'react'; import classes from './Counter.scss'; export const Counter = (props) => ( <div> <h2 className={classes.counterContainer}> Counter: {' '} <span className={classes['counter--green']}> {props.counter} </span> </h2> <button className="btn btn-default" onClick={props.increment}> Increment </button> {' '} <button className="btn btn-default" onClick={props.doubleAsync}> Double (Async) </button> </div> ); Counter.propTypes = { counter: React.PropTypes.number.isRequired, doubleAsync: React.PropTypes.func.isRequired, increment: React.PropTypes.func.isRequired }; export default Counter;
src/components/Box/Tools.js
falmar/react-adm-lte
import React from 'react' import PropTypes from 'prop-types' const Body = ({children}) => { return ( <div className='box-tools'> {children} </div> ) } Body.propTypes = { children: PropTypes.node } export default Body
src/components/Newsletter/index.js
fathomlondon/fathomlondon.github.io
import React from 'react'; export function Newsletter() { return ( <section className="newsletter bg-black white pt3 pt5-m"> <div id="mc_embed_signup" className="grid"> <div className="grid-item w-10 push-1"> <h3 className="f2">Our newsletter</h3> </div> <form className="grid-item w-10 push-1 validate justify-end" action="//fathomlondon.us16.list-manage.com/subscribe/post?u=9e5fce7688712fa6bf674d034&amp;id=adf3cf97ef" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" target="_blank" > <div id="mc_embed_signup_scroll"> <div className="mc-field-group"> <label htmlFor="mce-EMAIL" className="label light-grey"> Email Address </label> <input type="email" required placeholder="[email protected]" name="EMAIL" className="required email" id="mce-EMAIL" /> </div> <div id="mce-responses" className="clear"> <div className="response" id="mce-error-response" style={{ display: 'none' }} /> <div className="response" id="mce-success-response" style={{ display: 'none' }} /> </div> {/* real people should not fill this in and expect good things - do not remove this or risk form bot signups */} <div style={{ position: 'absolute', left: '-5000px' }} hidden> <input type="text" name="b_9e5fce7688712fa6bf674d034_adf3cf97ef" tabIndex="-1" /> </div> <div className="flex justify-end"> <input type="submit" value="Subscribe" name="subscribe" title="Subscribe" aria-label="Subscribe" id="mc-embedded-subscribe" className="button mt1 hover-bg-white hover-black" /> </div> </div> </form> </div> </section> ); }
src/components/common/Image.js
jaggerwang/zqc-app-demo
/** * 在球场 * zaiqiuchang.com */ import React from 'react' import {StyleSheet, View, Image, TouchableOpacity} from 'react-native' import flattenStyle from 'flattenStyle' import {COLOR} from '../../config' import * as helpers from '../../helpers' import * as components from '../' export default ({playIconVisible = false, duration, onPress, containerStyle, style, playIconStyle, ...props}) => { let child = <Image style={style} {...props} /> if (onPress) { let {width, height} = flattenStyle(style) let {fontSize} = flattenStyle([styles.playIcon, playIconStyle]) let left = Math.floor((width - fontSize) / 2) let top = Math.floor((height - fontSize) / 2) return ( <TouchableOpacity onPress={onPress} style={containerStyle}> {child} {playIconVisible ? <components.Icon name='play-circle-outline' style={[styles.playIcon, playIconStyle, {top, left}]} /> : null} {duration ? <components.Text style={styles.durationText}> {helpers.durationText(duration)} </components.Text> : null} </TouchableOpacity> ) } else { return ( <View style={containerStyle}> {child} </View> ) } } const styles = StyleSheet.create({ playIcon: { position: 'absolute', top: 0, left: 0, color: COLOR.textLightNormal, opacity: 0.8, backgroundColor: 'transparent', fontSize: 36 }, durationText: { position: 'absolute', bottom: 0, right: 0, color: COLOR.textLightNormal, fontSize: 12, padding: 5 } })
react/gameday2/components/embeds/EmbedDacast.js
fangeugene/the-blue-alliance
import React from 'react' import { webcastPropType } from '../../utils/webcastUtils' const EmbedDacast = (props) => { const channel = props.webcast.channel const file = props.webcast.file const iframeSrc = `https://iframe.dacast.com/b/${channel}/c/${file}` return ( <iframe src={iframeSrc} width="100%" height="100%" frameBorder="0" scrolling="no" player="vjs5" autoPlay="true" allowFullScreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen /> ) } EmbedDacast.propTypes = { webcast: webcastPropType.isRequired, } export default EmbedDacast
app/components/CompareImages.js
Kamahl19/image-min-app
import React from 'react'; export default React.createClass({ displayName: 'CompareImages', propTypes: { images: React.PropTypes.array.isRequired, }, getInitialState() { return { sliderCss: {}, leftImageCss: {}, imgCss: {}, enableMouseMoveListener: false, }; }, componentDidMount() { window.addEventListener('resize', this.initSlider); }, componentWillUnmount() { window.removeEventListener('resize', this.initSlider); }, onImgLoad(e) { this.imgWidth = e.target.naturalWidth; this.imgHeight = e.target.naturalHeight; this.initSlider(); }, initSlider() { if (!this.imgWidth || !this.imgHeight) { return; } let imgWidth; let imgHeight; let sliderWidth; let sliderHeight; const viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); const viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); if (this.imgWidth >= this.imgHeight) { imgWidth = '90vw'; imgHeight = 'auto'; sliderWidth = '90vw'; sliderHeight = Math.floor((1 - ((this.imgWidth - viewportWidth * 0.8) / this.imgWidth)) * this.imgHeight); } else { imgWidth = 'auto'; imgHeight = '90vh'; sliderWidth = Math.floor((1 - ((this.imgHeight - viewportHeight * 0.8) / this.imgHeight)) * this.imgWidth); sliderHeight = '90vh'; } this.setState({ imgCss: Object.assign({}, this.state.imgCss, { width: imgWidth, height: imgHeight, }), sliderCss: Object.assign({}, this.state.sliderCss, { width: sliderWidth, height: sliderHeight, }), leftImageCss: Object.assign({}, this.state.leftImageCss, { width: Math.floor(sliderWidth * 0.5), maxWidth: sliderWidth - 2, }), }); }, slideResize(e) { e.preventDefault(); if (this.state.enableMouseMoveListener) { const width = (e.offsetX === undefined) ? e.pageX - e.currentTarget.offsetLeft : e.offsetX; this.setState({ leftImageCss: Object.assign({}, this.state.leftImageCss, { width }) }); } }, enableSliderDrag(e) { e.preventDefault(); this.setState({ sliderCss: Object.assign({}, this.state.sliderCss, { cursor: 'ew-resize' }), enableMouseMoveListener: true, }); }, disableSliderDrag(e) { e.preventDefault(); this.setState({ sliderCss: Object.assign({}, this.state.sliderCss, { cursor: 'normal' }), enableMouseMoveListener: false, }); }, render() { return ( <div className="slider" ref="slider" style={this.state.sliderCss} onMouseMove={this.slideResize} onMouseDown={this.enableSliderDrag} onMouseUp={this.disableSliderDrag} > <div className="left image" style={this.state.leftImageCss}> <img src={this.props.images[0]} style={this.state.imgCss} onLoad={this.onImgLoad} /> </div> <div className="right image"> <img src={this.props.images[1]} style={this.state.imgCss} /> </div> </div> ); } });
src/dots.js
sanbornmedia/react-slick
'use strict'; import React from 'react'; import classnames from 'classnames'; var getDotCount = function (spec) { var dots; dots = Math.ceil(spec.slideCount / spec.slidesToScroll); return dots; }; export var Dots = React.createClass({ clickHandler: function (options, e) { // In Autoplay the focus stays on clicked button even after transition // to next slide. That only goes away by click somewhere outside e.preventDefault(); this.props.clickHandler(options); }, render: function () { var dotCount = getDotCount({ slideCount: this.props.slideCount, slidesToScroll: this.props.slidesToScroll }); // Apply join & split to Array to pre-fill it for IE8 // // Credit: http://stackoverflow.com/a/13735425/1849458 var dots = Array.apply(null, Array(dotCount + 1).join('0').split('')).map((x, i) => { var leftBound = (i * this.props.slidesToScroll); var rightBound = (i * this.props.slidesToScroll) + (this.props.slidesToScroll - 1); var className = classnames({ 'slick-active': (this.props.currentSlide >= leftBound) && (this.props.currentSlide <= rightBound) }); var dotOptions = { message: 'dots', index: i, slidesToScroll: this.props.slidesToScroll, currentSlide: this.props.currentSlide }; var onClick = this.clickHandler.bind(this, dotOptions); return ( <li key={i} className={className}> {React.cloneElement(this.props.customPaging(i), {onClick})} </li> ); }); return ( <ul className={this.props.dotsClass} style={{display: 'block'}}> {dots} </ul> ); } });
src/Announcer.js
thinkcompany/react-a11y-announcer
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class Announcer extends Component { constructor(props) { super(props); this.state = { text: '' } } static propTypes = { text: PropTypes.string, politeness: PropTypes.string } static defaultProps = { className: '', politeness: 'polite' } UNSAFE_componentWillReceiveProps(nextProps) { const currentAnnouncement = this.state.text; let nextAnnouncement = nextProps.text; if (nextAnnouncement === currentAnnouncement) { nextAnnouncement = nextAnnouncement + '\u00A0'; } this.setState(prevState => ({ text: nextAnnouncement })); } defaultStyles = { position: 'absolute', visibility: 'visible', overflow: 'hidden', display: 'block', width: '1px', height: '1px', margin: '-1px', border: '0', padding: '0', clip: 'rect(0px, 0px, 0px, 0px)', clipPath: 'polygon(0px 0px, 0px 0px, 0px 0px, 0px 0px)', whiteSpace: 'nowrap' } render() { const { className, text, politeness, ...props } = this.props; const styles = className ? {} : this.defaultStyles; return ( <div aria-atomic aria-live={politeness} style={styles} className={className} {...props} > { this.state.text.length ? <p>{this.state.text}</p> : null } </div> ) } } export default Announcer;
clients/packages/admin-client/src/mobilizations/templates/components/template-selectable-list.spec.js
nossas/bonde-client
/* eslint-disable no-unused-expressions */ import React from 'react'; import { expect } from 'chai'; import shallowWithIntl from '../../../intl/helpers/shallow-with-intl'; import { TemplateSelectableList } from '../../../mobilizations/templates/components'; import { IntlProvider } from 'react-intl'; const intlProvider = new IntlProvider({ locale: 'en' }, {}); const { intl } = intlProvider.getChildContext(); describe('client/mobilizations/templates/components/template-selectable-list', () => { let wrapper; const props = { templates: [{ id: 1 }, { id: 2 }], filterableTemplates: [], selectedIndex: 1, setSelectedIndex: () => {}, handleSelectItem: () => {}, }; beforeEach(() => { wrapper = shallowWithIntl( <TemplateSelectableList {...props} intl={intl} /> ); }); describe('#render', () => { it('should render without crash', () => { expect(wrapper).to.be.ok; }); }); });
app/components/hello/hello.js
dfmcphee/express-react
import React from 'react'; export default class Hello extends React.Component { constructor(props) { super(props); this.state = { message: 'Loading...' }; this.fetchMessage(); } fetchMessage() { fetch('/message.json') .then((response) => response.json()) .then((data) => this.setState({ message: data.message })); } render() { return ( <div className="hello"> <h1 className="hello__message">{this.state.message}</h1> </div> ); } }
src/Toggle/__tests__/Toggle.native.js
Fineighbor/ui-kit
/* eslint-env jest */ import React from 'react' import { shallow } from 'enzyme' import Toggle from '../index.ios.js' describe('Toggle.native', () => { it('renders a snapshot', () => { const wrapper = shallow( <Toggle /> ) expect(wrapper).toMatchSnapshot() }) it('renders a snapshot with tight', () => { const wrapper = shallow( <Toggle tight /> ) expect(wrapper).toMatchSnapshot() }) it('renders a snapshot with reverse', () => { const wrapper = shallow( <Toggle reverse /> ) expect(wrapper).toMatchSnapshot() }) it('renders a snapshot with label:Toggle', () => { const wrapper = shallow( <Toggle label='Toggle' /> ) expect(wrapper).toMatchSnapshot() }) it('renders a snapshot labelStyle', () => { const wrapper = shallow( <Toggle labelStyle={{ color: 'blue' }} /> ) expect(wrapper).toMatchSnapshot() }) it('renders a snapshot toggleStyle', () => { const wrapper = shallow( <Toggle toggleStyle={{ backgroundColor: 'blue' }} /> ) expect(wrapper).toMatchSnapshot() }) })
src/components/common/svg-icons/action/delete.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionDelete = (props) => ( <SvgIcon {...props}> <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/> </SvgIcon> ); ActionDelete = pure(ActionDelete); ActionDelete.displayName = 'ActionDelete'; ActionDelete.muiName = 'SvgIcon'; export default ActionDelete;
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js
skevy/react-router
import React from 'react'; import { Link } from 'react-router'; class Sidebar extends React.Component { render () { var assignments = COURSES[this.props.params.courseId].assignments return ( <div> <h3>Sidebar Assignments</h3> <ul> {assignments.map(assignment => ( <li key={assignment.id}> <Link to={`/course/${this.props.params.courseId}/assignments/${assignment.id}`}> {assignment.title} </Link> </li> ))} </ul> </div> ); } } export default Sidebar;
packages/ringcentral-widgets-docs/src/app/pages/Components/PresenceSettingSection/index.js
u9520107/ringcentral-js-widget
import React from 'react'; import { parse } from 'react-docgen'; import CodeExample from '../../../components/CodeExample'; import ComponentHeader from '../../../components/ComponentHeader'; import PropTypeDescription from '../../../components/PropTypeDescription'; import Demo from './Demo'; // eslint-disable-next-line import demoCode from '!raw-loader!./Demo'; // eslint-disable-next-line import componentCode from '!raw-loader!ringcentral-widgets/components/PresenceSettingSection'; const PresenceSettingSectionPage = () => { const info = parse(componentCode); return ( <div> <ComponentHeader name="PresenceSettingSection" description={info.description} /> <CodeExample code={demoCode} title="PresenceSettingSection Example" > <Demo /> </CodeExample> <PropTypeDescription componentInfo={info} /> </div> ); }; export default PresenceSettingSectionPage;
frontend/src/app/components/ExperimentRowCard.js
dannycoates/testpilot
import React from 'react'; import { Link } from 'react-router'; import classnames from 'classnames'; import { experimentL10nId } from '../lib/utils'; const ONE_DAY = 24 * 60 * 60 * 1000; const ONE_WEEK = 7 * ONE_DAY; const MAX_JUST_LAUNCHED_PERIOD = 2 * ONE_WEEK; const MAX_JUST_UPDATED_PERIOD = 2 * ONE_WEEK; export default class ExperimentRowCard extends React.Component { l10nId(pieces) { return experimentL10nId(this.props.experiment, pieces); } render() { const { hasAddon, experiment, enabled, isAfterCompletedDate } = this.props; const { description, title, thumbnail, subtitle, slug } = experiment; const installation_count = (experiment.installation_count) ? experiment.installation_count : 0; const isCompleted = isAfterCompletedDate(experiment); return ( <Link id="show-detail" to={`/experiments/${slug}`} onClick={(evt) => this.openDetailPage(evt)} className={classnames('experiment-summary', { enabled, 'just-launched': this.justLaunched(), 'just-updated': this.justUpdated(), 'has-addon': hasAddon })} > <div className="experiment-actions"> {enabled && <div data-l10n-id="experimentListEnabledTab" className="tab enabled-tab"></div>} {this.justLaunched() && <div data-l10n-id="experimentListJustLaunchedTab" className="tab just-launched-tab"></div>} {this.justUpdated() && <div data-l10n-id="experimentListJustUpdatedTab" className="tab just-updated-tab"></div>} </div> <div className="experiment-icon-wrapper" style={{ backgroundColor: experiment.gradient_start, backgroundImage: `linear-gradient(135deg, ${experiment.gradient_start}, ${experiment.gradient_stop}` }}> <div className="experiment-icon" style={{ backgroundImage: `url(${thumbnail})` }}></div> </div> <div className="experiment-information"> <header> <h3>{title}</h3> {subtitle && <h4 data-l10n-id={this.l10nId('subtitle')} className="subtitle">{subtitle}</h4>} <h4>{this.statusMsg()}</h4> </header> <p data-l10n-id={this.l10nId('description')}>{description}</p> { this.renderInstallationCount(installation_count, isCompleted) } { this.renderManageButton(enabled, hasAddon, isCompleted) } </div> </Link> ); } // this is set to 100, to accomodate Tracking Protection // which has been sending telemetry pings via installs from dev // TODO: figure out a non-hack way to toggle user counts when we have // telemetry data coming in from prod renderInstallationCount(installation_count, isCompleted) { if (installation_count <= 100 || isCompleted) return ''; return ( <span className="participant-count" data-l10n-id="participantCount" data-l10n-args={JSON.stringify({ installation_count })}>{installation_count}</span> ); } renderManageButton(enabled, hasAddon, isCompleted) { if (enabled && hasAddon) { return ( <div className="button card-control secondary" data-l10n-id="experimentCardManage">Manage</div> ); } else if (isCompleted) { return ( <div className="button card-control secondary" data-l10n-id="experimentCardLearnMore">Learn More</div> ); } return ( <div className="button card-control default" data-l10n-id="experimentCardGetStarted">Get Started</div> ); } justUpdated() { const { experiment, enabled, getExperimentLastSeen } = this.props; // Enabled trumps launched. if (enabled) { return false; } // If modified awhile ago, don't consider it "just" updated. const now = Date.now(); const modified = (new Date(experiment.modified)).getTime(); if ((now - modified) > MAX_JUST_UPDATED_PERIOD) { return false; } // If modified since the last time seen, *do* consider it updated. if (modified > getExperimentLastSeen(experiment)) { return true; } // All else fails, don't consider it updated. return false; } justLaunched() { const { experiment, enabled, getExperimentLastSeen } = this.props; // Enabled & updated trumps launched. if (enabled || this.justUpdated()) { return false; } // If created awhile ago, don't consider it "just" launched. const now = Date.now(); const created = (new Date(experiment.created)).getTime(); if ((now - created) > MAX_JUST_LAUNCHED_PERIOD) { return false; } // If never seen, *do* consider it "just" launched. if (!getExperimentLastSeen(experiment)) { return true; } // All else fails, don't consider it launched. return false; } statusMsg() { const { experiment } = this.props; if (experiment.completed) { const delta = (new Date(experiment.completed)).getTime() - Date.now(); if (delta < 0) { return ''; } else if (delta < ONE_DAY) { return <span className="eol-message" data-l10n-id="experimentListEndingTomorrow">Ending Tomorrow</span>; } else if (delta < ONE_WEEK) { return <span className="eol-message" data-l10n-id="experimentListEndingSoon">Ending Soon</span>; } } return ''; } openDetailPage(evt) { const { navigateTo, eventCategory, experiment, sendToGA } = this.props; const { title } = experiment; evt.preventDefault(); sendToGA('event', { eventCategory, eventAction: 'Open detail page', eventLabel: title }); navigateTo(`/experiments/${experiment.slug}`); } } ExperimentRowCard.propTypes = { experiment: React.PropTypes.object.isRequired, hasAddon: React.PropTypes.bool.isRequired, enabled: React.PropTypes.bool.isRequired, eventCategory: React.PropTypes.string.isRequired, getExperimentLastSeen: React.PropTypes.func.isRequired, sendToGA: React.PropTypes.func.isRequired, navigateTo: React.PropTypes.func.isRequired, isAfterCompletedDate: React.PropTypes.func };
src/routes/y-axis-assembly/YAxisAssembly.js
bigearth/www.clone.earth
import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './YAxisAssembly.css'; import { Grid, Row, Col, Image } from 'react-bootstrap'; import DocsTOC from '../../components/DocsTOC'; class YAxisAssembly extends React.Component { render() { return ( <Grid fluid> <Row className={s.root}> <Col xs={12} sm={12} md={2} lg={2} > <DocsTOC selected="/y-axis-assembly" /> </Col> <Col xs={12} sm={12} md={10} lg={10}> <Row> <Col xs={12} md={6}> <h2>Y Axis Assembly</h2> <h3 id='step1'>Step 1 Gather materials</h3> <h4>Tools</h4> <ul> <li>Adjustable wrench x2</li> <li>Needle nose pliers x1</li> <li>2 and 1.5mm Hex keys</li> </ul> <h4>3D printed parts</h4> <ul> <li>Y axis corners x4</li> <li>Y motor holder x1</li> <li>Y idler x1</li> <li>Y belt holder x1</li> </ul> <h4>Hardware</h4> <ul> <li> Rods <ul> <li>M10 threaded rod 35 cm x2</li> <li>M8 Chrome rod 33 cm x2</li> <li>M8 threaded rod 20 cm x4</li> </ul> </li> <li> Nuts &amp; Bolts <ul> <li>M3x10 screw x2</li> <li>M3x12 screw x2</li> <li>M3x16 screw x2</li> <li>M3x25 screw x1</li> <li>M10 nuts x14</li> <li>M10 washers x12</li> <li>M8 nuts x22</li> <li>M8 washers x22</li> <li>Idler Bearing x1 </li> <li>M3 locknut x3</li> <li>M3 washer x2</li> <li>GT2 pulley x1</li> <li>Linear bearings x3</li> </ul> </li> <li> Electronics <ul> <li>Y axis endstop x1</li> <li>Nema 17 stepper motor x1</li> </ul> </li> <li> Miscellaneous <ul> <li>Y axis carriage x1</li> <li>Zip tie 10 cm x4</li> <li>GT2 belt 97 cm x1</li> </ul> </li> </ul> </Col> <Col xs={12} md={6}> <p> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/hardware.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/hardware.jpg' /> </a> </p> <p>Watch how this is assembled.</p> <ul> <li> <a href='https://www.youtube.com/watch?v=dEyroKoFHkw'>Clone Y Axis Assembly pt 1</a> </li> <li> <a href='https://www.youtube.com/watch?v=lSSVv5N3OVk'>Clone Y Axis Assembly pt 2</a> </li> <li> <a href='https://www.youtube.com/watch?v=mc5PCTaUUeY'>Clone Y Axis Assembly pt 3</a> </li> <li> <a href='https://www.youtube.com/watch?v=De_r0noNFU'>Clone Y Axis Assembly pt 4</a> </li> <li> <a href='https://www.youtube.com/watch?v=UCKhUHuvsJs'>Clone Y Axis Assembly pt 5</a> </li> <li> <a href='https://www.youtube.com/watch?v=WLLdzBGMX2A'>Clone Y Axis Assembly pt 6</a> </li> </ul> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='step2'>Step 2 Assemble the Y-axis rods</h3> <h4>Hardware</h4> <ul> <li>M10 threaded rod 35 cm x2</li> <li>M10 washers x12</li> <li>M10 nuts x14</li> </ul> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-2-a.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-2-a.jpg' /> </a> </Col> </Row> <Row className={s.root}> <Col xs={12} md={6}> <ol> <li>Place the nuts, washers and y corners on the threaded rod.</li> <li className={s.blueHighlight}>Tighten the 2 nuts against each other counter-nut.</li> <li className={s.redHighlight}>Confirm that there is 10 cm distance between the counter nuts and the y axis corner.</li> </ol> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-2-b.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-2-b.jpg' /> </a> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='step3'>Step 3 Assemble the Y-axis stage rear</h3> <h4>Hardware</h4> <ul> <li>M8 threaded rod 20 cm x2</li> <li>M8 washers x8</li> <li>M8 nuts x4</li> </ul> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-3-a.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-3-a.jpg' /> </a> </Col> </Row> <Row className={s.root}> <Col xs={12} md={6}> <ol> <li>Screw the nuts and place washers and Y-motor-holder on threaded rod.</li> <li>Y-motor-mount should be somewhere in the middle of the threaded rod. The precise position doesn&rsquo;t matter at this time.</li> <li>Ensure the correct orientation of Y-motor-holder.</li> </ol> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-3-b.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-3-b.jpg' /> </a> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='step4'>Step 4 Assemble the Y-axis stage front</h3> <h4>Hardware</h4> <ul> <li>M8 threaded rod x2</li> <li>M8 washers x8</li> <li>M8 nuts x6</li> </ul> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-4-a.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-4-a.jpg' /> </a> </Col> </Row> <Row className={s.root}> <Col xs={12} md={6}> <ol> <li>Screw the nuts and place washers and Y-idler on threaded rod.</li> <li>Y-idler should be somewhere in the middle of the threaded rod. The precise position doesn&rsquo;t matter at this time.</li> </ol> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-4-b.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-4-b.jpg' /> </a> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='step5'>Step 5 Fully assemble the Y-axis stage</h3> <h4>Hardware</h4> <ul> <li>M8 washers x8</li> <li>M8 nuts x8</li> </ul> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-5-a.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-5-a.jpg' /> </a> </Col> </Row> <Row className={s.root}> <Col xs={12} md={6}> <ol> <li>Insert Y-axis stage front and back into Y-axis side elements and lock it with washers and nuts.</li> <li>Ensure the correct placement. Y-axis rear stage has to be closer to the double-nuts.</li> </ol> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-5-b.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-5-b.jpg' /> </a> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='step6'>Step 6 Prepare for the Y-axis stage</h3> <h4>Hardware</h4> <ul> <li>Aluminum Frame x1</li> <li>Y axis stage from previous steps</li> </ul> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-6-a.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-6-a.jpg' /> </a> </Col> </Row> <Row className={s.root}> <Col xs={12} md={6}> <ol> <li>Insert the Y-axis stage into the frame as close to Y-corners as possible.</li> <li>Adjust and tighten the M8n nuts.</li> <li>Rotate the Y-axis stage and repeat.</li> <li>After adjusting, the Y-axis stage should cause minimum movement while inserted into the frame.</li> <li>Tighten the M8n nuts gently or you&squo;ll risk damaging the 3D printed parts.</li> <li>It is incredibly important that the axis is perfectly rectangular at this stage of construction, all rods need to be perfectly straight and level. If not, you&rsquo;ll have troubles calibrating later on.</li> </ol> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-6-b.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-6-b.jpg' /> </a> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='step7'>Step 7 Assemble the Y carriage</h3> <h4>Hardware</h4> <ul> <li>Y Carriage x1</li> <li>Zip ties x3</li> <li>Linear bearings x3</li> </ul> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-7-a.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-7-a.jpg' /> </a> </Col> </Row> <Row className={s.root}> <Col xs={12} md={6}> <ol> <li>Insert zipties into the Y-carriage as shown on the picture.</li> <li>Place the linear bearings in cutouts.</li> <li>On side with two bearings slide bearings to the center, towards each other as close as possible.</li> </ol> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-7-b.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-7-b.jpg' /> </a> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='step8'>Step 8 Assemble the Y idler</h3> <h4>Hardware</h4> <ul> <li>M3x25 screw x1</li> <li>M3 washer x2</li> <li>bearing housing x1</li> <li>M3 lock nut x1</li> </ul> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-8-a.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-8-a.jpg' /> </a> </Col> </Row> <Row className={s.root}> <Col xs={12} md={6}> <ol> <li>To tighten the Y-idler, use the pliers and 2mm Hex key.</li> <li>Tighten the screw gently, just half turn max after the washers touch the 3D printed part.</li> </ol> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-8-b.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-8-b.jpg' /> </a> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='step9'>Step 9 Y axis motor</h3> <h4>Hardware</h4> <ul> <li>Stepper motor x1</li> <li>M3x10 screw x2</li> </ul> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-9-a.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-9-a.jpg' /> </a> </Col> </Row> <Row className={s.root}> <Col xs={12} md={6}> <ol> <li>Using the 2mm Hex key, secure the motor to the 3D printed part. Motor cables must be facing threaded rods.</li> <li>Tighten the motor gently to avoid damage to the 3D printed part.</li> </ol> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-9-b.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-9-b.jpg' /> </a> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='step10'>Step 10 Y Endstop</h3> <h4>Hardware</h4> <ul> <li>M3x16 screw x2</li> <li>Endstop x1</li> </ul> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-10-a.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-10-a.jpg' /> </a> </Col> </Row> <Row className={s.root}> <Col xs={12} md={6}> <ol> <li>To tighten the Y-endstop use 1.5mm Hex key.</li> </ol> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-10-b.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-10-b.jpg' /> </a> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='step11'>Step 11 Y belt holder</h3> <h4>Hardware</h4> <ul> <li>M3x12 screw x2</li> </ul> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-11-a.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-11-a.jpg' /> </a> </Col> </Row> <Row className={s.root}> <Col xs={12} md={6}> <ol> <li>Place Y-belt holder on the Y-carriage.</li> <li>Be aware of the orientation of Y-belt holder (belt entry should face towards single bearing).</li> </ol> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-11-b.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-11-b.jpg' /> </a> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='step12'>Step 12 Y carriage rods</h3> <h4>Hardware</h4> <ul> <li>Chrome rod 33 cm x2</li> </ul> </Col> <Col xs={12} md={6}> <a href=''> </a> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-12-a.jpg' /> </Col> </Row> <Row className={s.root}> <Col xs={12} md={6}> <ol> <li>Insert the 8mm smooth rods into the linear bearings on Y-carriage.</li> </ol> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-12-b.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-12-b.jpg' /> </a> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='step13'>Step 13 Assemble the Y axis stage</h3> <h4>Hardware</h4> <ul> <li>Assembled y carriage</li> <li>Assembled y stage</li> </ul> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-13-a.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-13-a.jpg' /> </a> </Col> </Row> <Row className={s.root}> <Col xs={12} md={6}> <ol> <li>Insert the assembled Y-carriage into the Y-axis stage.</li> <li>Insert zipties into holes in Y-corners.</li> <li>Using pliers, tighten the zipties as shown in the picture.</li> </ol> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-13-b.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-13-b.jpg' /> </a> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='step14'>Step 14 Add Y motor pulley</h3> <h4>Hardware</h4> <ul> <li>Assembled y motor</li> <li>GT2 pulley x1</li> </ul> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-14-a.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-14-a.jpg' /> </a> </Col> </Row> <Row className={s.root}> <Col xs={12} md={6}> <ol> <li>Add pulley to motor shaft and tighten.</li> </ol> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-14-b.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-14-b.jpg' /> </a> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='step15'>Step 15 Add belt to y axis</h3> <h4>Hardware</h4> <ul> <li>Pulley timing belt x1</li> </ul> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-15-a.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-15-a.jpg' /> </a> </Col> </Row> <Row className={s.root}> <Col xs={12} md={6}> <ol> <li>Run around y idler.</li> <li>Run around y motor</li> <li>Loop around y carriage holder.</li> </ol> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-15-b.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-15-b.jpg' /> </a> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-15-c.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/step-15-c.jpg' /> </a> </Col> </Row> <hr /> <Row className={s.root}> <Col xs={12} md={6}> <h3 id='allDone'>All Done!</h3> <p>Congratulations! Now on to the next step.</p> </Col> <Col xs={12} md={6}> <a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/done.jpg'> <Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/y-axis/done.jpg' /> </a> </Col> </Row> </Col> </Row> </Grid> ); } } export default withStyles(s)(YAxisAssembly);
src/svg-icons/image/timer-3.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTimer3 = (props) => ( <SvgIcon {...props}> <path d="M11.61 12.97c-.16-.24-.36-.46-.62-.65-.25-.19-.56-.35-.93-.48.3-.14.57-.3.8-.5.23-.2.42-.41.57-.64.15-.23.27-.46.34-.71.08-.24.11-.49.11-.73 0-.55-.09-1.04-.28-1.46-.18-.42-.44-.77-.78-1.06-.33-.28-.73-.5-1.2-.64-.45-.13-.97-.2-1.53-.2-.55 0-1.06.08-1.52.24-.47.17-.87.4-1.2.69-.33.29-.6.63-.78 1.03-.2.39-.29.83-.29 1.29h1.98c0-.26.05-.49.14-.69.09-.2.22-.38.38-.52.17-.14.36-.25.58-.33.22-.08.46-.12.73-.12.61 0 1.06.16 1.36.47.3.31.44.75.44 1.32 0 .27-.04.52-.12.74-.08.22-.21.41-.38.57-.17.16-.38.28-.63.37-.25.09-.55.13-.89.13H6.72v1.57H7.9c.34 0 .64.04.91.11.27.08.5.19.69.35.19.16.34.36.44.61.1.24.16.54.16.87 0 .62-.18 1.09-.53 1.42-.35.33-.84.49-1.45.49-.29 0-.56-.04-.8-.13-.24-.08-.44-.2-.61-.36-.17-.16-.3-.34-.39-.56-.09-.22-.14-.46-.14-.72H4.19c0 .55.11 1.03.32 1.45.21.42.5.77.86 1.05s.77.49 1.24.63.96.21 1.48.21c.57 0 1.09-.08 1.58-.23.49-.15.91-.38 1.26-.68.36-.3.64-.66.84-1.1.2-.43.3-.93.3-1.48 0-.29-.04-.58-.11-.86-.08-.25-.19-.51-.35-.76zm9.26 1.4c-.14-.28-.35-.53-.63-.74-.28-.21-.61-.39-1.01-.53s-.85-.27-1.35-.38c-.35-.07-.64-.15-.87-.23-.23-.08-.41-.16-.55-.25-.14-.09-.23-.19-.28-.3-.05-.11-.08-.24-.08-.39s.03-.28.09-.41c.06-.13.15-.25.27-.34.12-.1.27-.18.45-.24s.4-.09.64-.09c.25 0 .47.04.66.11.19.07.35.17.48.29.13.12.22.26.29.42.06.16.1.32.1.49h1.95c0-.39-.08-.75-.24-1.09-.16-.34-.39-.63-.69-.88-.3-.25-.66-.44-1.09-.59-.43-.15-.92-.22-1.46-.22-.51 0-.98.07-1.39.21-.41.14-.77.33-1.06.57-.29.24-.51.52-.67.84-.16.32-.23.65-.23 1.01s.08.68.23.96c.15.28.37.52.64.73.27.21.6.38.98.53.38.14.81.26 1.27.36.39.08.71.17.95.26s.43.19.57.29c.13.1.22.22.27.34.05.12.07.25.07.39 0 .32-.13.57-.4.77-.27.2-.66.29-1.17.29-.22 0-.43-.02-.64-.08-.21-.05-.4-.13-.56-.24-.17-.11-.3-.26-.41-.44-.11-.18-.17-.41-.18-.67h-1.89c0 .36.08.71.24 1.05.16.34.39.65.7.93.31.27.69.49 1.15.66.46.17.98.25 1.58.25.53 0 1.01-.06 1.44-.19.43-.13.8-.31 1.11-.54.31-.23.54-.51.71-.83.17-.32.25-.67.25-1.06-.02-.4-.09-.74-.24-1.02z"/> </SvgIcon> ); ImageTimer3 = pure(ImageTimer3); ImageTimer3.displayName = 'ImageTimer3'; ImageTimer3.muiName = 'SvgIcon'; export default ImageTimer3;
docs/app/Examples/collections/Form/FieldVariations/FormExampleRequiredFieldShorthand.js
shengnian/shengnian-ui-react
import React from 'react' import { Form } from 'shengnian-ui-react' const FormExampleRequiredFieldShorthand = () => ( <Form> <Form.Checkbox inline label='I agree to the terms and conditions' required /> </Form> ) export default FormExampleRequiredFieldShorthand
examples/js/selection/select-hook-table.js
dana2208/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-alert: 0 */ /* eslint guard-for-in: 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(5); function onRowSelect(row, isSelected) { let rowStr = ''; for (const prop in row) { rowStr += prop + ': "' + row[prop] + '"'; } alert(`is selected: ${isSelected}, ${rowStr}`); } function onSelectAll(isSelected, currentDisplayAndSelectedData) { alert(`is select all: ${isSelected}`); alert('Current display and selected data: '); for (let i = 0; i < currentDisplayAndSelectedData.length; i++) { alert(currentDisplayAndSelectedData[i]); } } const selectRowProp = { mode: 'checkbox', clickToSelect: true, onSelect: onRowSelect, onSelectAll: onSelectAll }; export default class SelectHookTable extends React.Component { render() { return ( <BootstrapTable data={ products } selectRow={ selectRowProp }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
app/containers/UpgradeDialog/index.js
VonIobro/ab-web
import React from 'react'; import { Receipt } from 'poker-helper'; import { createStructuredSelector } from 'reselect'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Form, Field, SubmissionError, reduxForm } from 'redux-form/immutable'; import { makeSelectAccountData } from '../../containers/AccountProvider/selectors'; import { getWeb3 } from '../../containers/AccountProvider/utils'; import NoWeb3Message from '../../containers/Web3Alerts/NoWeb3'; import UnsupportedNetworkMessage from '../../containers/Web3Alerts/UnsupportedNetwork'; import SubmitButton from '../../components/SubmitButton'; import FormGroup from '../../components/Form/FormGroup'; import { CheckBox } from '../../components/Input'; import Label from '../../components/Label'; import H2 from '../../components/H2'; import A from '../../components/A'; import { Icon } from '../../containers/Dashboard/styles'; import { accountUnlocked } from '../AccountProvider/actions'; import { ABI_PROXY } from '../../app.config'; import { waitForTx } from '../../utils/waitForTx'; import { promisifyWeb3Call } from '../../utils/promisifyWeb3Call'; import * as accountService from '../../services/account'; const validate = (values) => { const errors = {}; if (!values.get('accept')) { errors.accept = 'Required'; } return errors; }; /* eslint-disable react/prop-types */ const renderCheckBox = ({ input, label, type }) => ( <FormGroup> <Label> <CheckBox {...input} placeholder={label} type={type} /> {label} </Label> </FormGroup> ); /* eslint-enable react/prop-types */ class UpgradeDialog extends React.Component { constructor(props) { super(props); this.state = { success: false, }; this.handleSubmit = this.handleSubmit.bind(this); } componentWillReceiveProps(nextProps) { if (nextProps.submitting === false && this.props.submitting === true && !nextProps.invalid) { this.setState({ success: true }); this.props.accountUnlocked(); } } async handleSubmit() { const { account } = this.props; const proxyContract = getWeb3(true).eth.contract(ABI_PROXY).at(account.proxy); const unlockTx = promisifyWeb3Call(proxyContract.unlock); try { const unlockRequest = new Receipt().unlockRequest(account.injected).sign(`0x${account.privKey}`); const unlock = await accountService.unlock(unlockRequest); const txHash = await unlockTx( ...Receipt.parseToParams(unlock), { from: account.injected }, ); await waitForTx(getWeb3(), txHash); } catch (e) { setImmediate(() => this.props.change('accept', false)); throw new SubmissionError({ _error: `Error: ${e.message || e}` }); } } render() { const { success } = this.state; const { invalid, submitting, handleSubmit, onSuccessButtonClick, account, } = this.props; return ( <div> <H2> Unlock your account &nbsp; <A href="http://help.acebusters.com/quick-guide-to-acebusters/winning-the-pots/how-to-upgrade-to-a-shark-account" target="_blank" > <Icon className="fa fa-info-circle" aria-hidden="true" /> </A> </H2> {!account.injected && <NoWeb3Message /> } {account.injected && !account.onSupportedNetwork && <UnsupportedNetworkMessage /> } <Form onSubmit={handleSubmit(this.handleSubmit)}> {account.injected && !submitting && !success && <div> <p>This will unlock your account</p> <Field name="accept" type="checkbox" component={renderCheckBox} label="I understand that it will be my sole responsible to secure my account and balance" /> </div> } {submitting && <p>Account unlock tx pending...</p> } {success && <p>Account unlocked successful</p>} {!success && <SubmitButton disabled={!account.injected || !account.onSupportedNetwork || invalid} submitting={submitting} > Unlock </SubmitButton> } {success && <SubmitButton type="button" onClick={onSuccessButtonClick}> Ok </SubmitButton> } </Form> </div> ); } } UpgradeDialog.propTypes = { account: PropTypes.object, invalid: PropTypes.bool, submitting: PropTypes.bool, handleSubmit: PropTypes.func, accountUnlocked: PropTypes.func, change: PropTypes.func, onSuccessButtonClick: PropTypes.func, }; UpgradeDialog.defaultProps = { }; const mapStateToProps = createStructuredSelector({ account: makeSelectAccountData(), }); export default connect(mapStateToProps, { accountUnlocked })( reduxForm({ form: 'upgrade', validate, })(UpgradeDialog) );
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/Apis/Details/Permission.js
sambaheerathan/carbon-apimgt
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react' import {Row, Col} from 'antd'; class Permission extends React.Component { constructor(props) { super(props); this.state = { api: props.api } } render() { return ( <div> <div> <div className="wrapper wrapper-content"> <h2> API Name : {this.state.api.name} </h2> <div className="divTable"> <div className="divTableBody"> <div className="gutter-example"> <Row gutter={16}> <Col className="gutter-row" span={6}> <div className="gutter-box">Group Name</div> </Col> <Col className="gutter-row" span={6}> <div className="gutter-box">Read</div> </Col> <Col className="gutter-row" span={6}> <div className="gutter-box">Update</div> </Col> <Col className="gutter-row" span={6}> <div className="gutter-box">Delete</div> </Col> </Row> </div> </div> </div> </div> </div> </div> ) } } export default Permission
src/index.js
melihberberolu/yemeksepeti-task
import React from 'react'; import { render } from "react-dom"; import App from './App'; import registerServiceWorker from './registerServiceWorker'; require("./assets/sass/main.scss"); render( <App />, document.getElementById("app") ); registerServiceWorker();
src/TabPane.js
roderickwang/react-bootstrap
import React from 'react'; import deprecationWarning from './utils/deprecationWarning'; import Tab from './Tab'; const TabPane = React.createClass({ componentWillMount() { deprecationWarning( 'TabPane', 'Tab', 'https://github.com/react-bootstrap/react-bootstrap/pull/1091' ); }, render() { return ( <Tab {...this.props} /> ); } }); export default TabPane;
packages/react-ui-components/src/Dialog/index.story.js
mstruebing/PackageFactory.Guevara
import React from 'react'; import {storiesOf, action} from '@storybook/react'; import {withKnobs, text, boolean} from '@storybook/addon-knobs'; import {StoryWrapper} from './../_lib/storyUtils'; import Dialog from '.'; import Button from './../Button'; storiesOf('Dialog', module) .addDecorator(withKnobs) .addWithInfo( 'default', 'Dialog', () => ( <StoryWrapper> <Dialog isOpen={boolean('Is opened?', true)} title={text('Title', 'Hello title!')} onRequestClose={action('onRequestClose')} actions={[ <Button key="foo">An action button</Button> ]} style="wide" > {text('Inner content', 'Hello world!')} </Dialog> </StoryWrapper> ), {inline: true, source: false} ) .addWithInfo( 'narrow', 'Dialog', () => ( <StoryWrapper> <Dialog isOpen={boolean('Is opened?', true)} title={text('Title', 'Hello title!')} onRequestClose={action('onRequestClose')} actions={[ <Button key="foo">An action button</Button> ]} style="narrow" > {text('Inner content', 'Hello world!')} </Dialog> </StoryWrapper> ), {inline: true, source: false} );
app/components/FullRoster.js
BeAce/react-babel-webpack-eslint-boilerplate
import React from 'react'; const FullRoster = () => (<div> <ul>api12</ul> </div>); export default FullRoster;
app/components/users/UserForm.js
MakingSense/mern-seed
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router'; import Formsy from 'formsy-react'; import autoBind from '../../lib/autoBind'; import { Input, Textarea } from 'formsy-react-components'; class UserForm extends Component { constructor(props, context) { super(props, context); this.state = { canSubmit: false }; autoBind(this, { bindOnly: ['enableButton', 'disableButton', 'submit', 'resetForm'] }); } enableButton() { this.setState({ canSubmit: true }); } disableButton() { this.setState({ canSubmit: false }); } submit(model) { this.props.onSave(model); } resetForm() { this.refs.form.reset(); } render() { return ( <div> <Formsy.Form ref="form" className="horizontal" onValidSubmit={this.submit} onValid={this.enableButton} onInvalid={this.disableButton}> <Input formNoValidate required name="name" label="Name" placeholder="Name" value={this.props.user.name || ''} /> <Input formNoValidate required name="email" label="Email" placeholder="Email" value={this.props.user.email || ''} validations="isEmail" validationError="This is not a valid email" /> <div> <button type="button" onClick={this.resetForm}>Reset</button> &nbsp; <input type="submit" disabled={!this.state.canSubmit} value={this.props.saving ? 'Saving... ' : 'Save'} /> &nbsp; <Link to="/app/users">Cancel</Link> </div> </Formsy.Form> </div> ); } } UserForm.propTypes = { onSave: PropTypes.func.isRequired, saving: PropTypes.bool.isRequired, user: PropTypes.object.isRequired }; export default UserForm;
src/components/UI/Tabs/Tabs.js
bocasfx/Q
import React from 'react'; import './Tabs.css'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { setSelection } from '../../../actions/Selection'; import PropTypes from 'prop-types'; class Tabs extends React.Component { static propTypes = { selection: PropTypes.object, children: PropTypes.node, setSelection: PropTypes.func, } constructor(props) { super(props); this.state = { selected: 0, }; this.renderTitles = this.renderTitles.bind(this); } componentWillReceiveProps(nextProps) { if (nextProps.selection.objType === 'streams') { this.setState({ selected: 1, }); } else { this.setState({ selected: 0, }); } } onClick(idx, event) { event.preventDefault(); this.setState({ selected: idx, }); this.props.setSelection(this.props.children[idx].props.label.toLowerCase()); } renderTitles() { return this.props.children.map((child, idx) => { let selectedClass = idx === this.state.selected ? 'tabs-selected' : null; return ( <a href="#" onClick={this.onClick.bind(this, idx)} key={idx}> <div className={selectedClass}> {child.props.label} </div> </a> ); }); } render() { return ( <div className="tabs-container"> <div className="tabs-labels"> {this.renderTitles()} </div> <div className="tabs-content"> {this.props.children[this.state.selected]} </div> </div> ); } } const mapStateToProps = (state) => { return { selection: state.selection, }; }; const mapDispatchToProps = (dispatch) => { return { setSelection: bindActionCreators(setSelection, dispatch), }; }; export default connect(mapStateToProps, mapDispatchToProps)(Tabs);
web/portal/src/components/Form/Radio/index.js
trendmicro/serverless-survey-forms
import React, { Component } from 'react'; import Question from '../Question'; class Radio extends Component { render() { const { data, onClick } = this.props; return ( <div className="question" onClick={onClick} > <Question id={data.order} text={data.label} required={data.required} /> <div className="radioGrp"> {this._renderRadioItem()} </div> </div> ); } _renderRadioItem() { const { data } = this.props; const items = data.data.map((itm, idx) => { const label = itm.label; const input = itm.input; return ( <div className="radioItem ut-radio" key={idx} > <input type="radio" /> <label> {label} </label> { itm.hasOwnProperty('input') ? <input type="text" className="input input--medium ut-input" placeholder={input} /> : '' } <div className="subdescription">{itm.example || ''}</div> </div> ); }); return items; } } export default Radio;
__tests__/index.ios.js
amostap/react-native-todo
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
components/header.js
waigo/waigo.github.io
import React from 'react'; import { Link } from 'react-router'; import { prefixLink } from 'gatsby-helpers'; import Headroom from 'react-headroom'; import { config } from 'config'; import Classnames from 'classnames'; const NAV = [ { label: 'Guide', title: 'Documentation guide', link: prefixLink(config.docsLink), tag: 'guide', }, { label: 'API', title: 'API docs', link: prefixLink(config.apiLink), tag: 'api', }, { label: <i className="twitter" />, title: 'Twitter', link: config.twitterUrl, tag: 'twitter', type: 'social', external: true, }, { label: <i className="github" />, title: 'Github', link: config.githubUrl, tag: 'github', type: 'social', external: true, }, { label: <i className="discuss" />, title: 'Discuss', link: config.discussUrl, tag: 'discuss', type: 'social', external: true, }, ]; export default class Header extends React.Component { constructor (props) { super(props); this.state = { mobileActive: null, }; _.bindAll(this, '_toggleMobileMenu'); } render () { const activeNav = this.props.activeNav; let header = null; if (this.props.show) { const navItems = NAV.map((item) => { let lnk; if (item.external) { lnk = (<a title={item.title} href={item.link} className={Classnames({active: activeNav === item.tag})}> {item.label} </a>); } else { lnk = (<Link title={item.title} to={item.link} className={Classnames({active: activeNav === item.tag})}> {item.label} </Link>); } return ( <li key={item.tag} className={Classnames(item.type)}>{lnk}</li> ); }); header = ( <header> <section className="brand"> <Link to={prefixLink('/')}> Waigo.js </Link> </section> <button className="mobile-toggle" onClick={this._toggleMobileMenu}> <i className={Classnames('menu', {open: this.state.mobileActive})} /> </button> <ul className={Classnames('nav', { active: this.state.mobileActive})}> {navItems} </ul> </header> ); } return ( <Headroom> {header} </Headroom> ); } _toggleMobileMenu (e) { e.preventDefault(); this.setState({ mobileActive: !this.state.mobileActive, }); } } Header.propTypes = { activeNav: React.PropTypes.string, show: React.PropTypes.bool, }; Header.defaultProps = { activeNav: null, show: true, };
react/src/containers/Login/Login.js
hnquang112/laradock
import React from 'react'; import {Btn} from '../../components/Controls/Button/Button'; import History from '../../routes/History'; class Login extends React.Component { // this method is only to trigger route guards , remove and use your own logic handleLogin = () => { localStorage.setItem('token','token'); History.push('/') } render(){ return( <div className="container my-5"> <h1>Login Page</h1> <Btn text='Login' handleClick={this.handleLogin}/> </div> ) } } export default Login;
07/src/App.js
viddamao/front-end-demo
import React, { Component } from 'react'; import './App.css'; class App extends Component { render() { return ( <div className="wrapper"> <h1 className="todo-title">React-Todos</h1> <p>implements a todo list with React</p> <div className="App"> </div> </div> ); } } export default App;
imports/ui/components/resident-details/accounts/transaction/transaction-pa.js
gagpmr/app-met
import React from 'react'; import * as Styles from '/imports/modules/styles.js'; import { UpdateResident } from '/imports/api/residents/methods.js'; export class TransactionPa extends React.Component { constructor(props) { super(props); } removeBill(e) { e.preventDefault(); var resid = e.currentTarget.dataset.resid; var billId = e.currentTarget.dataset.billid; var data = { ResidentId: resid, DeleteTransactionPaBill: true, BillId: billId } UpdateResident.call({ data: data }, (error, result) => { if (error) { Bert.alert(error, 'danger'); } }); } render() { if (this.props.resident.TxnPaBills) { return ( <table style={ Styles.TableHeader } className="table table-bordered table-condensed table-striped"> <thead> <tr> <td style={ Styles.PaddingThreeCenterBold }> Sr </td> <td style={ Styles.PaddingThreeCenterBold }> Span </td> <td style={ Styles.PaddingThreeCenterBold }> R-Rent </td> <td style={ Styles.PaddingThreeCenterBold }> Water </td> <td style={ Styles.PaddingThreeCenterBold }> Electricity </td> <td style={ Styles.PaddingThreeCenterBold }> FSMD </td> <td style={ Styles.PaddingThreeCenterBold }> Misc </td> <td style={ Styles.PaddingThreeCenterBold }> Admn </td> <td style={ Styles.PaddingThreeCenterBold }> Total </td> <td colSpan="2" style={ Styles.PaddingThreeCenterBold }> Actions </td> </tr> </thead> <tbody> { this.props.resident.TxnPaBills.map((doc) => <tr key={ doc._id }> <td style={ Styles.PaddingThreeCenter }> { doc.SrNo } </td> <td style={ Styles.PaddingThreeCenter }> { doc.BillPeriod } </td> <td style={ Styles.PaddingThreeCenter }> { doc.RoomRent } </td> <td style={ Styles.PaddingThreeCenter }> { doc.WaterCharges } </td> <td style={ Styles.PaddingThreeCenter }> { doc.ElectricityCharges } </td> <td style={ Styles.PaddingThreeCenter }> { doc.FoodSubsidyMesDevChrgs } </td> <td style={ Styles.PaddingThreeCenter }> { doc.Miscellaneous } </td> <td style={ Styles.PaddingThreeCenter }> { doc.Admission } </td> <td style={ Styles.PaddingThreeCenter }> { doc.Total } </td> <td style={ Styles.PaddingThreeCenterBold }> <a onClick={ this.removeBill } data-resid={ this.props.resident._id } data-billid={ doc._id } data-toggle="tooltip" title="Delete From Transaction" href=""> <i className="fa fa-trash-o" aria-hidden="true"></i> </a> </td> </tr>) } </tbody> </table> ); } else { return null; } } }; TransactionPa.propTypes = { resident: React.PropTypes.object };