Recent Entries 10
- pattern minor 61d agoA simple MP3 player with React.jsI've been learning React.js for the last few days and am working on a simple MP3 player. I have a few years experience with JavaScript, however, I am just trying to get used to the idea of components in React.js. I would also like to be following best practices as I may use the application/code as a portfolio piece. What I have made is working correctly. However, I was wondering if you can look through my code and see if I could do anything better/more efficiently. Also, I have the following specific questions: - In the `MusicPlayer` component I have an array of objects with information on different sounds. I am aware I have this "sounds" array set up as a "state" and I was wondering is there another way to incorporate this array perhaps as a property (seeing as it won't be changing state throughout the application). Or do you think it is ok, the way I have done it? - As you can see towards the end of the code I have this: ``` ReactDOM.render( , document.getElementById('app') ); ``` I was wondering is there a way to detect the HTML has finished being "rendered" so that I can use JavaScript `document.getElementById` on one of the elements. At the moment I am using `window.onload` for this. Full code: ``` var Sound = React.createClass({ //make a component for individual sounds //these will be html list items getInitialState: function () { return {isSelected: false} }, render: function () { return ( {this.props.soundTitle} {this.props.soundLength} ); } }); var MusicPlayer = React.createClass({ //this will be our main component i.e a parent to the Sound component and also the Controls component (defined below) getInitialState: function () { //return an object with an array of all of our sounds. The sounds array itself will not change state. //also retu
- snippet minor 61d agoClass to create HTML heading tags in ReactI have a class which is part of my page layout. It is creating header tag elements (`h1` - `h5`). Could someone tell me how I could improve it (I know it should be improved, but don't know how)? I have problem with rewriting almost the same code in switch cases. Would rather to create some kind of `` code, but couldn't. ``` import React, {Component} from 'react'; import PropTypes from 'prop-types'; export class TypographyHeader extends Component { createHeader() { let txt = this.props.text; let spaceIndex = txt.indexOf(' '); let p2 = txt.substr(spaceIndex); txt = {txt.substr(0, spaceIndex)} ; switch(this.props.headerType) { case 1: return {txt} {p2}; case 2: return {txt} {p2}; case 3: return {txt} {p2}; case 4: return {txt} {p2}; case 5: return {txt} {p2}; } return {txt} {p2}; } render() { return ( {this.createHeader()} ); } } TypographyHeader.propTypes = { headerType: PropTypes.oneOf([1, 2, 3, 4, 5]).isRequired, text: PropTypes.string.isRequired, }; ```
- pattern minor 61d agoSuppress console output from React in Jest testing output but not in browser outputI have a React app that I am testing with the built-in jest testing tools. In the process of debugging, I sometimes send data to the console (e.g. `console.log`, `console.error`, etc.) from my code-under-test. This shows up both in the browser console as well as in the testing output in the terminal which is what I sometimes want. However, sometimes I want to send such debugging messages to either: - the testing terminal or - the browser, but not both. I know how to do #1: just include the `console.log` in the jest test code rather than in the code-under-test. However, if I want to do #2, I'm not quite sure what to do. I tried the following in the code-under-test: ``` if (!jest) { console.log('some browser-only output'); } ``` That does suppress the output in the test, which otherwise behaves normally, i.e. no error is thrown during testing. However, it does not output anything in the browser but instead throws an error: `"Uncaught ReferenceError: jest is not defined"`, i.e. there is no `let jest = ...` or `const jest = ...` anywhere in the code. I did come up with a solution: ``` try { jest; } catch(e) { console.log('some browser-only output'); } ``` This gives me the desired results. However, the solution feels very hack-y: It requires throwing an error in order to work, which just "smells" wrong, even for a debugging tool. So, is there a better way for me to check whether `jest` exists without throwing an error? Or another way to see if testing is underway, again without throwing an error?
- pattern minor 61d agoUnit tests for React component to submit an input form with validationI'm very new to front-end/unit testing and have been having a difficult time understanding the point altogether, but I managed to push my way through testing literally everything I could possibly think of. Anyways, if anyone has the time I'd love a review of my component and tests for said component. Component ``` import React, { Component } from 'react'; import './InputForm.css'; class InputForm extends Component { constructor(props) { super(props); this.onFormSubmit = this.onFormSubmit.bind(this); this.validate = this.validate.bind(this); this.onInputChange = this.onInputChange.bind(this); this.state = { fields: {}, fieldErrors: {}, }; } onInputChange(e) { const fields = this.state.fields; const newFields = {}; newFields[e.target.name] = e.target.value; this.setState({ fields: {...fields, ...newFields} }); } validate(formData) { const errors = {}; if (!formData.name || formData.name === '' || formData.name === null) { errors.name = 'Please enter your name.'; } return errors; } onFormSubmit(e) { e.preventDefault(); const formData = this.state.fields const fieldErrors = this.validate(formData); this.setState({ fieldErrors }); if (Object.keys(fieldErrors).length) return; const name = this.state.fields.name; this.props.handleFormSubmit(name); this.setState({ fields: {}, fieldErrors: {}, }) } render() { return ( this.onFormSubmit(e)}> this.onInputChange(e)} /> {this.state.fieldErrors.name} ); } } InputForm.propTypes = { handleFormSubmit: React.PropTypes.func.isRequired, }; export default InputForm; ``` Tests ``` // dependencies import React from 'react'; import { shallow, mount } from 'enzyme'; import { spy } from 'sinon'; // components import InputForm from './InputForm'; describe('', () => { let props, wr
- pattern minor 61d agoSimple Tic-Tac-Toe game in React.jsI'm relatively new to react and attempted to create a simple Tic-Tac-Toe game. Would be great if i could get some feedback on this. Again, at this point using only React (no Redux). main.js - main file which adds our App component to the DOM ``` import React from 'react'; import ReactDOM from 'react-dom'; import App from './container/App'; document.addEventListener('DOMContentLoaded', function() { ReactDOM.render( React.createElement(App), document.getElementById('mount') ); }); ``` App.js - root component that contains the Board and Dashboard. One specific question I had here was: when I receive the `reset()` event from my Dashboard App, what's the best practice on how I can end up triggering the `reset()` of `Board`? ``` import React, { Component } from 'react'; import Board from './Board' import Dashboard from './Dashboard' export default class App extends Component { constructor(props) { super(props) this.state = { winner: '' } } reset() { console.log('how do i pass reset to Board...?') } hasWinner(winner) { this.setState({ winner: winner }) } render() { return ( ) } } ``` Board.js - `Board` component that contains `Cell` components! Please ignore the `checkWinner()` method for the purpose of this review. ``` import React, { Component } from 'react'; import Cell from './Cell' import styles from '../css/board.css' export default class Board extends Component { constructor(props) { super(props) let board = this.createBoard(); this.state = { board: board, currentPlayer: 'X' } } createBoard() { let board = new Array(this.props.rows); for ( var row = 0 ; row ); } } return board; } reset() { let board = this.createBo
- pattern minor 61d agoA box for commentsI made this as a practice application to learn React. It is simply a box where someone can enter their name and a comment and submit it, and display other comments. This animated GIF illustrates what it looks like: Note: Please don't be too critical of the looks, I haven't spent a lot of time styling it with CSS. Also those small vertical lines shown with the typing were introduced by imgur when I uploaded the gif to it, those don't appear on the actual page. There is not a data persistence server/layer to speak of, as it is not meant to be actually deployed, so I simply keep the data into a regular array of objects, like so: ``` var comments = [ { id: 1, author: "John Q. Commenter", text: "This is the first comment.", timestamp: new Date() }, { id: 2, author: "Jane A. Opinionated", text: "This is the second comment.", timestamp: new Date() }, /* Test for empty comment */ { id: 3 } ] ``` I went with a Component/Container design approach, where the container is responsible for the business logic, and the container is only responsible for rendering the appearance of the objects on the page. There are 4 components together in this hierarchy: ``` CommentBox |- CommentList |- Comment |- CommentForm ``` The data flow for comments is essentially: `CommentForm -> comments (array) -> CommentList -> Comment`. I will focus on the React files only, but if you are curious about the rest you can look at the repository on GitHub. Note that I left out the `import React from 'react'` and `export default` lines because every file begins and ends with those, respectively. index.jsx This is the entry point: ``` import CommentBox from './containers/CommentBoxContainer' class App extends React.Component { render() { return ( ) } } ReactDOM.render( , document.getElementById('app') ) ``` CommentBox This component is meant to hold all the other elements together: ``` import CommentL
- pattern minor 61d agoCalling a promise recursivelyI'm trying to call a promise recursively. If I get a `responseData` with a key error I want to call the promise again and again until I don't get it. ``` _getUser (url) { console.log('fetching url', url) return fetch(`$(url)/api`, { method: 'POST', headers: {}, body: '{"key" : "body"}' }) .then((response) => response.json()) .then((responseData) => { console.log('Getting responseData', responseData) if (responseData[0].error) { alert(responseData[0].error.description) return _getUser(url) } else alert('User Created') }) .catch((error) => { console.log(error) }) } ``` Is this the best way to call a promise recursively to do what I want?
- pattern minor 61d agoReact modal visibility and content toggling based on action clickedLearning React, I have created a basic `App Component` and `Modal Component`, the App Component renders 2 actions - hold and cancel, and a Modal based on the state `modalVisible`. I've kept the Modal Component light opting to pass the events back to the App Component (not sure if this is recommended), my reasoning is that this component could then be used by multiple actions. Would be great to get your thoughts in order to learn and improve! ``` /** * App Component * Holds actions, controls modal display using the state modalVisible. */ var AppComponent = React.createClass({ getInitialState() { return { modalVisible: false } }, _onModalYesClicked() { console.log('onYesClicked::contact the server'); this.toggleModal(); }, _onModalNoClicked() { console.log('onNoClicked:contact the server'); this.toggleModal(); }, toggleModal({title = null, description = null, cancelLabel = 'No', submitLabel = 'Yes'} = {}) { this.setState({ modalVisible: !this.state.modalVisible, title: title, description: description, cancelLabel: cancelLabel, submitLabel: submitLabel }); }, onCancelClicked() { console.log('onCancelClicked'); this.toggleModal({ title: 'Cancel', description: 'Would you like to commit to cancelling?' }); }, onHoldClicked() { console.log('onHoldClicked'); this.toggleModal({ title: 'Hold', description: 'Are you sure you would like to hold the order?' }); }, render() { var modal = undefined; if(this.state.modalVisible) { modal = } return ( Cancel Hold {modal} ) } }); /** * Modal Component * Uses props to tell parent component the action to take o
- pattern minor 61d agoBuilding a multi-panel display with React and BootstrapThe exercise is part of a React course in which I'm currently enrolled. Description: The way it shall look on desktop-screen: How it shall look on mobile: Here's my solution: HTML ``` ``` JSX ``` // Manager bundles the single components together. var React = require('react'); var ReactDOM = require('react-dom'); var PanelWithoutHeading = require('./components/PanelWithoutHeading.jsx'); var PanelCentered = require('./components/PanelCentered.jsx'); var PanelColoredHeading = require('./components/PanelColoredHeading.jsx'); var PanelLarge = require('./components/PanelLarge.jsx'); var largePanelVals = [ { headline: 15080, text: 'Shot Views' }, { headline: 12000, text: 'Likes' }, { headline: 5100, text: 'Comments' } ]; var PanelManager = React.createClass({ render: function() { return ( ); } }); // Render the bundle into HTML. ReactDOM.render(, document.getElementById('display')); // -- THE COMPONENTS ---------------------------- // 1. Component var React = require('react'); var PanelCentered = React.createClass({ render: function() { var divStyle = { 'marginTop': '10px' } ; var panelStyles = { 'background': this.props.backgroundColor, 'textAlign': 'center', 'color': 'white', 'minHeight': '100px' }; var h3Styles = { fontSize: '36px' }; return ( { this.props.headline } { this.props.text } ); } }); module.exports = PanelCentered; // 2. Component var React = require('react'); var PanelColoredHeading = React.createClass({ render: function() { var divStyle =
- pattern minor 61d agoReact Native - Combining login and signup pages into one componentI have been building an app in React Native and have decided that since my `Login` and `Signup` components share much of the same code, it would be best to create an `AuthState` component and pass `login={true}` or `login={false}` as props to trigger `renderLogin()` or `renderSignup()` in `AuthState`. However, in doing so, I think I have written extraneous code. I tried to minimize this by writing a `renderEmailAndPasswordForms()` function that gets included in `renderLogin()` and `renderSignup()` but I am sure there's better ways to clean all of this up. Can someone point me in the right direction? Here is my code: login.js ``` import React, { Component } from 'react'; // Components import AuthShared from '../auth_shared'; export default class Login extends Component { render() { return ( ); } } ``` signup.js ``` import React, { Component } from 'react'; // Components import AuthShared from '../auth_shared'; export default class SignUp extends Component { render() { return ( ); } } ``` auth_shared.js ``` import React, { Component } from 'react'; import { AlertIOS, Dimensions, Image, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import { Actions } from 'react-native-router-flux'; import firebaseApp from 'TextbookSwap/firebase_setup'; import styles from 'TextbookSwap/app_styles'; // Components import HeaderImage from './header_image'; // For Firebase Auth const auth = firebaseApp.auth(); export default class Login extends Component { constructor(props) { super(props); this.state = { firstName: '', lastName: '', email: '', password: '', passwordConfirmation: '' } } componentDidMount() { let user = auth.currentUser; if (user) { console.log(msg) Actions.home } else { return; } } render()