How to use setState in React

Issue #662 Use spread operator import React, { Component, useState, useEffect } from 'react'; const [state, setState] = useState({ message: '', chats: [], sending: false }) setState(prevState => ({ ...prevState, message: '', sending: false })) Updated at 2020-06-12 21:23:42

June 12, 2020 路 1 min 路 Khoa Pham

How to handle evens in put with React

Issue #661 Use Bulma css <input class="input is-rounded" type="text" placeholder="Say something" value={value} onChange={(e) => { onValueChange(e.target.value) }} onKeyDown={(e) => { if (e.key === 'Enter') { onSend(e) } }} />

June 12, 2020 路 1 min 路 Khoa Pham

How to handle events for input with React

Issue #661 Use Bulma css <input class="input is-rounded" type="text" placeholder="Say something" value={value} onChange={(e) => { onValueChange(e.target.value) }} onKeyDown={(e) => { if (e.key === 'Enter') { onSend(e) } }} /> Updated at 2020-06-16 07:30:52

June 12, 2020 路 1 min 路 Khoa Pham

How to auto scroll to top in react router 5

Issue #659 Use useLocation https://reacttraining.com/react-router/web/guides/scroll-restoration import React, { useEffect } from 'react'; import { BrowserRouter as Router, Switch, Route, Link, useLocation, withRouter } from 'react-router-dom' function _ScrollToTop(props) { const { pathname } = useLocation(); useEffect(() => { window.scrollTo(0, 0); }, [pathname]); return props.children } const ScrollToTop = withRouter(_ScrollToTop) function App() { return ( <div> <Router> <ScrollToTop> <Header /> <Content /> <Footer /> </ScrollToTop> </Router> </div> ) } Updated at 2020-06-04 05:58:47

June 4, 2020 路 1 min 路 Khoa Pham

How to use dynamic route in react router 5

Issue #658 Declare routes, use exact to match exact path as finding route is from top to bottom. For dynamic route, I find that we need to use render and pass the props manually. Declare Router as the rooter with Header, Content and Footer. Inside Content there is the Switch, so header and footer stay the same across pages import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom' function Content() { return ( <Switch> <Route exact path="/about"> <About /> </Route> <Route exact path="/"> <Home /> </Route> <Route path='/book/:id' render={(props) => { return ( <BookDetail {....

June 3, 2020 路 1 min 路 Khoa Pham

How to use folder as local npm package

Issue #657 Add library folder src/library src library res.js screens Home index.js package.json Declare package.json in library folder { "name": "library", "version": "0.0.1" } Declare library as dependency in root package.json "dependencies": { "library": "file:src/library" }, Now import like normal, for example in src/screens/Home/index.js import res from 'library/res'

June 1, 2020 路 1 min 路 Khoa Pham

How to update multiple state properties with React hooks

Issue #655 Declare state and setState export default function Showcase(props) { const factory = props.factory const [state, setState] = useState( { factory, selectedFilter: { name: '' } } ) const onFilterClick = (filter) => { setState({ selectedFilter: filter, factory: factory.filter((app) => { return app.showcase.platforms.includes(filter.name) }) }) } let cards = state.factory.map((app, index) => { return ( <Card app={app} key={app.slug} /> ) }) return ( <div> <FilterBar onClick={onFilterClick} /> <div css={css` display: flex; flex-direction: row; flex-wrap: wrap; justify-content: flex-start; margin: 0 auto; padding: 0 8vw; `}> {cards} </div> </div> ) }

May 8, 2020 路 1 min 路 Khoa Pham

How to make white label React app

Issue #654 Use shelljs to execute shell commands, and fs to read and write. In public/index.html specify some placeholder and we will replace those in our script const fs = require('fs'); const shell = require('shelljs') let indexHtml = fs.readFileSync(publicIndexHtmlPath, 'utf8') indexHtml = indexHtml .replace('CONSTANT_HTML_TITLE', `${app.name}- ${app.headline.title}`) .replace('CONSTANT_HTML_META_DESCRIPTION', app.headline.text) fs.writeFileSync(publicIndexHtmlPath, indexHtml) // build shell.cd('projects/my_react_app') shell.exec('npm run build') // copy shell.exec(`cp -a projects/my_react_app web_server/public`)

May 7, 2020 路 1 min 路 Khoa Pham

How to make white label React app for landing pages

Issue #654 A good landing page is one of the most crucial part of a successful launch. Recently I started creating landing pages for my apps, I was lazy that I ended creating a white label React app as a landing template and then write a script to build multiple similar pages. Here are a few examples, at first the pages share same look and feel, but we can add more configuration parameters later on....

May 7, 2020 路 7 min 路 Khoa Pham

How to show lightbox in React

Issue #653 Use https://github.com/biati-digital/glightbox Configure css. Specify class='glightbox for html elements <link rel="stylesheet" href="css/blueimp-gallery.min.css" /> Install package npm install glightbox import GLightbox from 'glightbox' const lbElements = features.map((feature) => { return { 'href': require(`../apps/${app.slug}/${feature.image}`), 'type': 'image', 'title': feature.title, 'description': feature.texts[0], } }) const openLb = () => { const lightbox = GLightbox({ touchNavigation: true, loop: true, autoplayVideos: true, onOpen: () => {}, beforeSlideLoad: (slide, data) => {} }); const myGallery = GLightbox({ elements: lbElements, autoplayVideos: false, }); myGallery....

May 7, 2020 路 1 min 路 Khoa Pham

How to animate on scroll in React

Issue #652 Use https://github.com/michalsnik/aos Add link to head <head> <link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" /> </head> Jus before closing body tag <script src="https://unpkg.com/aos@next/dist/aos.js"></script> <script> AOS.init(); </script> Specify data-aos <div data-aos="fade-up"> </div>

May 7, 2020 路 1 min 路 Khoa Pham

How to conditionally apply css in emotion js

Issue #649 Check flag then define css const Picture = (feature) => { const shadowCss = feature.shadow ? css` border-radius: 5px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); ` : css`` return ( <div css={css` width: 40vw; @media (max-width: 420px) { width: 98vw; } `}> <div css={shadowCss}> <img css={css` max-width: 100%; height: auto; `} src={require(`../apps/${feature.image}`)} /> </div> </div> ) }

May 6, 2020 路 1 min 路 Khoa Pham

How to scroll to element in React

Issue #648 In a similar fashion to plain old javascript, note that href needs to have valid hash tag, like #features <a href='#features' onClick={() => { const options = { behavior: 'smooth' } document.getElementById('features-section').scrollIntoView(options) }} > Features </a> Updated at 2020-05-06 08:36:21

May 6, 2020 路 1 min 路 Khoa Pham

How to use emotion for inline css in React

Issue #647 emotion can be used in framework agnostic or with React. To use with React, follow https://emotion.sh/docs/introduction#react npm i @emotion/core Note that you must have /** @jsx jsx */ at the top of the file, and the unused jsx in import is a directive for JSX to work properly // this comment tells babel to convert jsx to calls to a function called jsx instead of React.createElement /** @jsx jsx */ import { css, jsx } from '@emotion/core' const color = 'white' render( <div css={css` padding: 32px; background-color: hotpink; font-size: 24px; border-radius: 4px; &:hover { color: ${color}; } `} > Hover to change color....

May 2, 2020 路 1 min 路 Khoa Pham

How to use React JSX with Babel in Electron

Issue #352 For a normal electron app created with npm init, we can use all features of ES6, but not the JSX syntax for React. We can use just Babel to transpile JSX, as used in IconGenerator .babelrc { "plugins": [ "transform-react-jsx-source" ], "presets": ["env", "react"] } And in package.json, call babel to transpile src to dist "main": "dist/main.js", "scripts": { "start": "npm run babel && electron .", "babel": "babel ....

August 12, 2019 路 1 min 路 Khoa Pham

How to catch error in ApolloClient

Issue #192 Read https://www.apollographql.com/docs/react/features/error-handling How to catch actual error https://github.com/apollographql/apollo-client/issues/4016 馃 import { Observable } from 'apollo-link' import ApolloClient from 'apollo-boost' import Token from 'library/models/Token' import TokenService from './TokenService' import { TokenRefreshException } from 'library/utils/Exception' const client = new ApolloClient({ uri: 'https://www.myapp.no/api/', request: async (operation) => { const token = await TokenService.loadToken() updateOperation(operation, token) }, onError: (error) => { console.log('ApolloClient error', error) if (isAuthError(error)) { return handleAuthError(error) } else { return error....

March 28, 2019 路 1 min 路 Khoa Pham

How to handle file picker in React

Issue #190 render() { <Button color="inherit" onClick={this.onImagePress} >Image</Button> <input ref="fileInput" type="file" id="myFile" multiple accept="image/*" style={{display: 'none'}} onChange={this.handleFiles}></input> } onImagePress = () => { const fileInput = this.refs.fileInput fileInput.click() } handleFiles = (e) => { e.persist() const file = e.target.files[0] }

March 25, 2019 路 1 min 路 Khoa Pham