How to use relative file module with Create React app

Issue #751 Declare data/package.json to make it into node module { "name": "data", "version": "0.1.0", "private": true, "homepage": ".", "main": "main.js" } Then in landing/package.json, use file { "name": "landing", "version": "0.1.0", "private": true, "homepage": ".", "dependencies": { "@emotion/core": "^10.0.28", "react": "^16.13.1", "react-dom": "^16.13.1", "react-image": "^2.4.0", "react-scripts": "3.4.1", "data": "file:../data" }, ...

January 17, 2021 路 1 min 路 Khoa Pham

How to use default system fonts in React apps

Issue #700 In index.css body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; } Updated at 2020-11-18 06:29:29...

November 18, 2020 路 1 min 路 Khoa Pham

How to make simple overlay container in React

Issue #699 Use term ZStack like in SwiftUI, we declare container as relative position. For now it uses only 2 items from props.children but can be tweaked to support mutiple class App extends React.Component { render() { return ( <ZStack> <Header /> <div css={css` padding-top: 50px; `}> <Showcase factory={factory} /> <Footer /> </div> </ZStack> ) } } /** @jsx jsx */ import React from 'react'; import { css, jsx } from '@emotion/core' export default function ZStack(props) { return ( <div css={css` position: relative; border: 1px solid red; `}> <div css={css` position: absolute; top: 0; left: 0; width: 100%; z-index: -1; `}> {props....

November 18, 2020 路 1 min 路 Khoa Pham

How to use useEffect in React hook

Issue #669 Specify params as array [year, id], not object {year, id} const { year, id } = props useEffect(() => { const loadData = async () => { try { } catch (error) { console.log(error) } } listenChats() }, [year, id]) } Hooks effect https://reactjs.org/docs/hooks-effect.html https://reactjs.org/docs/hooks-reference.html#useeffect By default, it runs both after the first render and after every update. This requirement is common enough that it is built into the useEffect Hook API....

June 17, 2020 路 1 min 路 Khoa Pham

How to go back to home in React

Issue #665 Usually in header we have logo that takes user back to the home page // index.js import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom' <Router> <Switch> <Route exact path="/"> <Home /> </Route> </Router> // Header.js import { useHistory } from 'react-router-dom' const history = useHistory() <a class="navbar-item" onClick={() => { history.push('/') }}> ...

June 13, 2020 路 1 min 路 Khoa Pham

How to format date in certain timezone with momentjs

Issue #664 Use moment-timezone https://momentjs.com/timezone/docs/ npm install moment-timezone // public/index.html <script src="moment.js"></script> <script src="moment-timezone-with-data.js"></script> Need to import from moment-timezone, not moment import moment from 'moment-timezone' moment(startAt).tz('America/Los_Angeles').format('MMMM Do YYYY') ...

June 13, 2020 路 1 min 路 Khoa Pham

How to style video js

Issue #663 /** @jsx jsx */ import { css, jsx } from '@emotion/core' import React from 'react'; import videojs from 'video.js' export default class VideoPlayer extends React.Component { componentDidMount() { // instantiate Video.js this.player = videojs(this.videoNode, this.props, function onPlayerReady() { console.log('onPlayerReady', this) }); } // destroy player on unmount componentWillUnmount() { if (this.player) { this.player.dispose() } } // wrap the player in a div with a `data-vjs-player` attribute // so videojs won't create additional wrapper in the DOM // see https://github....

June 12, 2020 路 1 min 路 Khoa Pham

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