Unverified Commit 4a02dc5a authored by TodorTotev's avatar TodorTotev Committed by GitHub

Refactor class components to functional @ examples (#13398)

**Affected examples**

with-segment-analytics
with-slate
with-portals-ssr ( _with-portals-ssr is based on a package not being updated in the last year_)
with-videojs
with-next-page-transitions
with-firebase-cloud-messaging
with-dynamic-app-layout
with-dynamic-import
with-next-transition
with-carbon-components
with-cerebral
with-custom-babel-config

Here and there I have removed some redundant imports as well. I believe with this PR, there are only 1 or 2 examples left using class-based components. If by any chance you find any, let me know and I'll refactor them too.

If you don't like anything or you want me to change something, please let me know.

**If there is anything else you'd like me to help with, I would be honored to assist.**
parent dcf446d8
import { Component, Fragment } from 'react'
import { Button } from 'carbon-components-react' import { Button } from 'carbon-components-react'
export default class DemoApp extends Component { const Home = () => {
render() {
return ( return (
<Fragment> <>
<Button>Hello, world!</Button> <Button>Hello, world!</Button>
</Fragment> </>
) )
}
} }
export default Home
import { Component } from 'react'
import { Controller } from 'cerebral' import { Controller } from 'cerebral'
import Devtools from 'cerebral/devtools' import Devtools from 'cerebral/devtools'
import { Container } from '@cerebral/react' import { Container } from '@cerebral/react'
import Page from '../components/Page' import Page from '../components/Page'
import clock from '../modules/clock' import clock from '../modules/clock'
export default class Counter extends Component { const Home = (props) => {
constructor(props) { const { stateChanges } = props
super(props)
// The controller will be instantiated for every page change and we only const controller = Controller({
// add the devtools if we indeed are running in the browser
this.controller = Controller({
devtools: devtools:
process.env.NODE_ENV === 'production' || typeof window === 'undefined' process.env.NODE_ENV === 'production' || typeof window === 'undefined'
? null ? null
: Devtools({ host: 'localhost:8787' }), : Devtools({ host: 'localhost:8787' }),
modules: { clock }, modules: { clock },
stateChanges: props.stateChanges, stateChanges: stateChanges,
}) })
}
render() {
return ( return (
<Container controller={this.controller}> <Container controller={controller}>
<Page title="Index Page" linkTo="/other" /> <Page title="Index Page" linkTo="/other" />
</Container> </Container>
) )
}
} }
export default Home
import { Component } from 'react'
import { Controller } from 'cerebral' import { Controller } from 'cerebral'
import Devtools from 'cerebral/devtools' import Devtools from 'cerebral/devtools'
import { Container } from '@cerebral/react' import { Container } from '@cerebral/react'
import Page from '../components/Page' import Page from '../components/Page'
import clock from '../modules/clock' import clock from '../modules/clock'
export default class Counter extends Component { const Other = (props) => {
constructor(props) { const { stateChanges } = props
super(props)
// The controller will be instantiated for every page change and we only const controller = Controller({
// add the devtools if we indeed are running in the browser
this.controller = Controller({
devtools: devtools:
process.env.NODE_ENV === 'production' || typeof window === 'undefined' process.env.NODE_ENV === 'production' || typeof window === 'undefined'
? null ? null
: Devtools({ host: 'localhost:8787' }), : Devtools({ host: 'localhost:8787' }),
modules: { clock }, modules: { clock },
stateChanges: props.stateChanges, stateChanges: stateChanges,
}) })
}
render() {
return ( return (
<Container controller={this.controller}> <Container controller={controller}>
<Page title="Other Page" linkTo="/" /> <Page title="Index Page" linkTo="/other" />
</Container> </Container>
) )
}
} }
export default Other
import { Component } from 'react' import { useState, useEffect } from 'react'
export default class MyLuckNo extends Component {
constructor(...args) {
super(...args)
this.state = { randomNo: null }
}
componentDidMount() { const MyLuckNo = () => {
this.recalculate() const [randomNumber, setRandomNumber] = useState(null)
}
recalculate() { const recalculate = () => {
this.setState({ setRandomNumber(Math.ceil(Math.random() * 100))
randomNo: Math.ceil(Math.random() * 100),
})
} }
render() { useEffect(() => {
const { randomNo } = this.state recalculate()
}, [])
if (randomNo === null) {
return <p>Please wait..</p>
}
// This is an experimental JavaScript feature where we can get with
// using babel-preset-stage-0
const message = do { const message = do {
if (randomNo < 30) { if (randomNumber < 30) {
// eslint-disable-next-line no-unused-expressions // eslint-disable-next-line no-unused-expressions
;('Do not give up. Try again.') ;('Do not give up. Try again.')
} else if (randomNo < 60) { } else if (randomNumber < 60) {
// eslint-disable-next-line no-unused-expressions // eslint-disable-next-line no-unused-expressions
;('You are a lucky guy') ;('You are a lucky guy')
} else { } else {
...@@ -37,12 +24,14 @@ export default class MyLuckNo extends Component { ...@@ -37,12 +24,14 @@ export default class MyLuckNo extends Component {
} }
} }
if (randomNumber === null) return <p>Please wait..</p>
return ( return (
<div> <div>
<h3>Your Lucky number is: "{randomNo}"</h3> <h3>Your Lucky number is: "{randomNumber}"</h3>
<p>{message}</p> <p>{message}</p>
<button onClick={() => this.recalculate()}>Try Again</button> <button onClick={() => recalculate()}>Try Again</button>
</div> </div>
) )
}
} }
export default MyLuckNo
import React from 'react'
import App from 'next/app' import App from 'next/app'
const Noop = ({ children }) => children const Noop = ({ children }) => children
......
import { Component } from 'react' import { useEffect } from 'react'
import { firebaseCloudMessaging } from '../utils/webPush' import { firebaseCloudMessaging } from '../utils/webPush'
class Index extends Component { const Index = () => {
componentDidMount() { useEffect(() => {
firebaseCloudMessaging.init() firebaseCloudMessaging.init()
} }, [])
render() {
return <div>Next.js with firebase cloud messaging.</div> return <div>Next.js with firebase cloud messaging.</div>
}
} }
export default Index export default Index
import React from 'react' import { useState, useEffect } from 'react'
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import Link from 'next/link' import Link from 'next/link'
class About extends React.Component { const About = (props) => {
static pageTransitionDelayEnter = true const [loaded, setLoaded] = useState(false)
const { pageTransitionReadyToEnter } = props
constructor(props) { useEffect(() => {
super(props) const timeoutId = setTimeout(() => {
this.state = { pageTransitionReadyToEnter()
loaded: false, setLoaded(true)
}
}
componentDidMount() {
this.timeoutId = setTimeout(() => {
this.props.pageTransitionReadyToEnter()
this.setState({ loaded: true })
}, 2000) }, 2000)
return () => {
clearTimeout(timeoutId)
} }
}, [pageTransitionReadyToEnter])
componentWillUnmount() { if (!loaded) return null
if (this.timeoutId) clearTimeout(this.timeoutId)
}
render() {
if (!this.state.loaded) return null
return ( return (
<div className="container bg-success page"> <div className="container bg-success page">
<h1>About us</h1> <h1>About us</h1>
...@@ -37,7 +30,6 @@ class About extends React.Component { ...@@ -37,7 +30,6 @@ class About extends React.Component {
</Link> </Link>
</div> </div>
) )
}
} }
About.propTypes = { About.propTypes = {
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
"dependencies": { "dependencies": {
"@jesstelford/react-portal-universal": "1.0.0", "@jesstelford/react-portal-universal": "1.0.0",
"next": "latest", "next": "latest",
"react": "^16.8.0", "react": "16.13.1",
"react-dom": "^16.8.0" "react-dom": "16.13.1"
} }
} }
import { Component } from 'react' import { useState } from 'react'
import { UniversalPortal } from '@jesstelford/react-portal-universal' import { UniversalPortal } from '@jesstelford/react-portal-universal'
export default class Index extends Component { const Index = () => {
constructor() { const [isOpen, toggle] = useState(true)
super(...arguments)
this.state = { opened: true }
}
open = () => {
this.setState({ opened: true })
}
close = () => {
this.setState({ opened: false })
}
render() {
return ( return (
<> <>
{/* A portal that is adjacent to its target */} {/* A portal that is adjacent to its target */}
...@@ -25,10 +13,10 @@ export default class Index extends Component { ...@@ -25,10 +13,10 @@ export default class Index extends Component {
</UniversalPortal> </UniversalPortal>
{/* Open a modal in a portal that is elsewhere in the react tree */} {/* Open a modal in a portal that is elsewhere in the react tree */}
<button type="button" onClick={this.open}> <button onClick={() => toggle(!isOpen)} type="button">
Open Modal Open Modal
</button> </button>
{this.state.opened && ( {isOpen && (
<UniversalPortal selector="#modal"> <UniversalPortal selector="#modal">
<div <div
style={{ style={{
...@@ -58,7 +46,7 @@ export default class Index extends Component { ...@@ -58,7 +46,7 @@ export default class Index extends Component {
</a> </a>
. .
</p> </p>
<button type="button" onClick={this.close}> <button type="button" onClick={() => toggle(!isOpen)}>
Close Modal Close Modal
</button> </button>
</div> </div>
...@@ -67,5 +55,6 @@ export default class Index extends Component { ...@@ -67,5 +55,6 @@ export default class Index extends Component {
)} )}
</> </>
) )
}
} }
export default Index
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
"dependencies": { "dependencies": {
"@segment/snippet": "^4.0.1", "@segment/snippet": "^4.0.1",
"next": "latest", "next": "latest",
"react": "^16.7.0", "react": "16.13.1",
"react-dom": "^16.7.0" "react-dom": "16.13.1"
} }
} }
import { Component } from 'react' import { useState } from 'react'
export default class Contact extends Component { const Contact = () => {
state = { message: '' } const [message, setMessage] = useState('')
const handleSubmit = (e) => {
e.preventDefault()
global.analytics.track('Form Submitted', {
message,
})
setMessage('')
}
render() {
return ( return (
<div> <div>
<h1>This is the Contact page</h1> <h1>This is the Contact page</h1>
<form onSubmit={this.handleSubmit}> <form onSubmit={handleSubmit}>
<label> <label>
<span>Message:</span> <span>Message:</span>
<textarea onChange={this.handleInput} value={this.state.message} /> <textarea
onChange={(e) => setMessage(e.target.value)}
value={message}
/>
</label> </label>
<button type="submit">submit</button> <button type="submit">submit</button>
</form> </form>
...@@ -33,17 +43,5 @@ export default class Contact extends Component { ...@@ -33,17 +43,5 @@ export default class Contact extends Component {
`}</style> `}</style>
</div> </div>
) )
}
handleInput = (e) => {
this.setState({ message: e.target.value })
}
handleSubmit = (e) => {
e.preventDefault()
global.analytics.track('Form Submitted', {
message: this.state.message,
})
this.setState({ message: '' })
}
} }
export default Contact
import { Component } from 'react'
import Link from 'next/link' import Link from 'next/link'
import Editor from '../components/NextEditor' import Editor from '../components/NextEditor'
class MultipleEditors extends Component { const MultipleEditors = () => {
render() {
return ( return (
<> <>
<Link href="/"> <Link href="/">
...@@ -15,7 +13,6 @@ class MultipleEditors extends Component { ...@@ -15,7 +13,6 @@ class MultipleEditors extends Component {
<Editor slateKey="bar" defaultValue="Bar" /> <Editor slateKey="bar" defaultValue="Bar" />
</> </>
) )
}
} }
export default MultipleEditors export default MultipleEditors
import { Component } from 'react' import { useCallback, useEffect, useState } from 'react'
import videojs from 'video.js' import videojs from 'video.js'
import 'videojs-youtube' import 'videojs-youtube'
class Player extends Component { const Player = (props) => {
componentDidMount() { const [videoEl, setVideoEl] = useState(null)
// instantiate Video.js const onVideo = useCallback((el) => {
this.player = videojs(this.videoNode, this.props, function onPlayerReady() { setVideoEl(el)
console.log('onPlayerReady', this) }, [])
})
}
// destroy player on unmount useEffect(() => {
componentWillUnmount() { const player = videojs(videoEl, props)
if (this.player) { return () => {
this.player.dispose() player.dispose()
}
} }
}, [props, videoEl])
// 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.com/videojs/video.js/pull/3856
render() {
return ( return (
<div>
<div data-vjs-player> <div data-vjs-player>
<video ref={(node) => (this.videoNode = node)} className="video-js" /> <video ref={onVideo} className="video-js" playsInline />
</div>
</div> </div>
) )
}
} }
export default Player export default Player
...@@ -8,8 +8,8 @@ ...@@ -8,8 +8,8 @@
}, },
"dependencies": { "dependencies": {
"next": "^9.1.8-canary.11", "next": "^9.1.8-canary.11",
"react": "^16.7.0", "react": "16.13.1",
"react-dom": "^16.7.0", "react-dom": "16.13.1",
"video.js": "^6.7.3", "video.js": "^6.7.3",
"videojs-youtube": "^2.4.1" "videojs-youtube": "^2.4.1"
}, },
......
import { Component } from 'react'
import Player from '../components/Player' import Player from '../components/Player'
export default class Index extends Component { const Index = () => {
render() {
const videoJsOptions = { const videoJsOptions = {
techOrder: ['youtube'], techOrder: ['youtube'],
autoplay: false, autoplay: false,
...@@ -16,5 +14,6 @@ export default class Index extends Component { ...@@ -16,5 +14,6 @@ export default class Index extends Component {
} }
return <Player {...videoJsOptions} /> return <Player {...videoJsOptions} />
}
} }
export default Index
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment