Per documentation, Hooks cannot be used inside class components. But there are ways with higher order components: How can I use React hooks in React classic `class` component?. However this answer provided does not address the case of hooks that get called on function invocation. Take this simple Toast hook from: https://jossmac.github.io/react-toast-notifications/. I'd like to call the hook inside of a class of form:
```
class MyClass extends React.Component {
onTapButton = () => {
if(conditionTrue){
addToast('hello world', {
appearance: 'error',
autoDismiss: true,
})
}
}
render(){ ... }
}
```
There'd be no way of calling addToast without using const { addToast } = useToasts() in the class method, which would throw error.
You can use withToastManager HOC to archive that work
Here is an example
import React, { Component } from 'react';
import { withToastManager } from 'react-toast-notifications';
class ConnectivityListener extends Component {
state = { isOnline: window ? window.navigator.onLine : false };
// NOTE: add/remove event listeners omitted for brevity
onlineCallback = () => {
this.props.toastManager.remove(this.offlineToastId);
this.offlineToastId = null;
};
offlineCallback = id => {
this.offlineToastId = id;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
const { isOnline } = this.state;
if (prevState.isOnline !== isOnline) {
return { isOnline };
}
return null;
}
componentDidUpdate(props, state, snapshot) {
if (!snapshot) return;
const { toastManager } = props;
const { isOnline } = snapshot;
const content = (
<div>
<strong>{isOnline ? 'Online' : "Offline"}</strong>
<div>
{isOnline
? 'Editing is available again'
: 'Changes you make may not be saved'}
</div>
</div>
);
const callback = isOnline
? this.onlineCallback
: this.offlineCallback;
toastManager.add(content, {
appearance: 'info',
autoDismiss: isOnline,
}, callback);
}
render() {
return null;
}
}
export default withToastManager(ConnectivityListener);
For more information you can also find here
Related
i have to check the current Pathname of my website to set the Steps for my React-Joyride guided Tour.
i have a Parent Component where the routes are defined and in which the Joyride tour is implemented.
the Tutorial Component implements step Objects to set the steps for the tour like this:
import Tutorial from './tutorial/tutorial'
class App extends Component {
constructor (props) {
super(props)
this.state= {
// state things
}
}
render () {
return (
<BrowserRouter>
<Tutorial
run={this.state.run}
stepIndex={this.state.stepIndex}
firstPartClicked={this.state.firstPartClicked}
secondPartClicked={this.state.secondPartClicked}
handleRestart={this.handleRestart}
handleEnd={this.handleEnd}
handleSteps={this.handleSteps}
handleFirstPart={this.handleFirstPart}
handleSecondPart={this.handleSecondPart}
handleClickedFalse={this.handleClickedFalse}
handleSetVisited={this.handleSetVisited}
handleCheckTourDone={this.handleCheckTourDone}
/>
// many other Routes
<Route
exact path='/matches/:matchId/' render={(props) => {
this.removeGlobalTimeRef()
const matchId = this.props.matchId
return this.checkLoginThen(this.gotoMatchDetails(props))
}}
/>
</BrowserRouter>
)
}
}
export default App
import matchSteps from '../tutorial/steps/matchSteps'
class Tutorial extends React.Component {
constructor (props) {
super(props)
this.state = {
isUpdatet: false,
steps: []
}
}
callback = (tour) => {
const { action, index, type, status } = tour
if ([STATUS.FINISHED].includes(status)) {
this.props.handleEnd()
this.props.handleClickedFalse()
if (this.props.location.pathname.startsWith('/matches/') && this.props.location.pathname.includes('sequence')) {
this.props.handleSetVisited()
}
} else if ([STATUS.SKIPPED].includes(status)) {
this.props.handleEnd()
this.props.handleClickedFalse()
this.props.handleSetVisited()
} else if (action === 'close') {
this.props.handleEnd()
this.props.handleClickedFalse()
} else if ([EVENTS.STEP_AFTER, EVENTS.TARGET_NOT_FOUND].includes(type)) {
const step = index + (action === ACTIONS.PREV ? -1 : 1)
this.props.handleSteps(step)
}
}
render () {
let { steps } = this.state
const pathname = this.props.location.pathname
const siteSteps = [matchSteps, matchEditorSteps, matchEditorStepsOne, matchEditorStepsTwo,
matchSequenceSteps, matchSequenceStepsOne, matchSequenceStepsTwo, matchSiteSteps, matchSiteStepsOne, matchSiteStepsTwo]
for (let i = 0; i < siteSteps.length; i++) {
if (pathname === siteSteps[i].onSite && siteSteps[i].part === 'full') {
steps = siteSteps[i].steps
} else if (pathname === siteSteps[i].onSite && siteSteps[i].part === 'one') {
if (this.props.firstPartClicked === true) {
steps = siteSteps[i].steps
}
} else if (pathname === siteSteps[i].onSite && siteSteps[i].part === 'two') {
if (this.props.secondPartClicked === true) {
steps = siteSteps[i].steps
}
}
}
}
return (
<>
<Joyride
callback={this.callback}
run={this.props.run}
stepIndex={this.props.stepIndex}
steps={steps}
continuous
disableOverlayClose
spotlightClicks
showSkipButton
locale={{
back: <span>Zurück</span>,
last: (<span>Beenden</span>),
next: (<span>Weiter</span>)
}}
styles={{
options: {
primaryColor: '#2d98da'
}
}}
/>
</>
)
}
export default withRouter(Tutorial)
const matchSteps = {
name: 'matchSteps',
// onSite: '/matches/:matchId/', <-- HERE
part: 'full',
steps: [{
target: '.row',
title: '',
content: 'bla bla',
placement: 'center',
disableBeacon: true
}]
export default matchSteps
now i have to set the matchId in the step Object at onSite: '/matches/:matchId/' so i can check the pathname in the Tutorial Component.
i dont know how to do it correctly i've tested some ideas but the matchId was always undefined.
You can use react router hooks useParams to get the parameters of the current url
import { useParams } from "react-router-dom";
let { slug } = useParams();
or use react router hooks useLocation to get the current url as location object
import { useLocation } from "react-router-dom";
let location = useLocation();
Your question isn't clear to me. Well the question is clear but the code snippets are not.
There are only two data flows in javascript. Data flows down from parent to child via properties. Data can be passed back to a parent via a callback. You can chain that callback from child -> parent -> grandparent.
class grandparent extends Component {
getDecentData = (data) => { do something with data}
render(){
<Parent CB = {this.getDecentData}/>
}
}
class Parent extends Component {
render(){
<Child CB = {this.props.CB} />
}
}
class Child extends Component {
clickHandler=(e) => {
// do something to get data
this.props.CB(data)
}
render(){
<Control onClick={this.clickHandler} />
}
}
I would like to dynamically import a module from a path importPath set via Props.
var importPath;
class MainComponent extends Component {
state = {}
render() {
// Set var importPath = "path_to_module here;"
// importPath = this.props.myModulePath
return (
<ComponentToImport myComponentPath="./ToastExample" />);
}
}
export default MainComponent;
Then :
class ComponentToImport extends Component {
ToastExample: (async () => {
await import (this.props.revPath)
})()
async sayHiFromJava() {
this.state.ToastExample.showJ('Awesome', ToastExample.SHORT);
}
render() {
return (<ToastExample />);
}
}
How can I go about this?
Thank you all in advance.
How do I attach ToastExample in import ToastExample from importPath; to await import("importPath"); so that I can return(<ToastExample />);
UPDATE
I have tried :
class ComponentToImport extends Component {
ToastExample: (async () => {
await import (this.props.revPath)
})()
async sayHiFromJava() {
this.state.ToastExample.showJ('Awesome', ToastExample.SHORT);
}
render() {
return (<ToastExample />);
}
}
but I get the error :
error: bundling failed: index.js: index.js:Invalid call at line 28: import(_this.props.myComponentPath)
I guess this is the way:
import("importPath").then(() => {
// your code
});
or
await import("importPath");
// your code
see more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Is it what your are looking for?
const ToastExample = await import('importPath');
EDIT: Please read the official doc to set up your webpack or Babel (https://reactjs.org/docs/code-splitting.html)
class ComponentToImport extends Component {
constructor(props) {
super(props);
this.state = { module: null };
}
componentDidMount() {
const { path } = this.props;
import(`${path}`).then(module => this.setState({ module: module.default }));
}
render() {
const { module: Component } = this.state;
return <div>{Component && <Component />}</div>;
}
}
If you want to pass component to child component one way is to pass through child props.
import myComponentPath from "./ToastExample"
<ComponentToImport>
<myComponentPath />
<ComponentToImport/>
and then
class ComponentToImport extends Component {
render() {
return (this.props.children);
}
}
May be this helps.
Thanks
I typically use component composition to reuse logic the React way. For example, here is a simplified version on how I would add interaction logic to a component. In this case I would make CanvasElement selectable:
CanvasElement.js
import React, { Component } from 'react'
import Selectable from './Selectable'
import './CanvasElement.css'
export default class CanvasElement extends Component {
constructor(props) {
super(props)
this.state = {
selected: false
}
this.interactionElRef = React.createRef()
}
onSelected = (selected) => {
this.setState({ selected})
}
render() {
return (
<Selectable
iElRef={this.interactionElRef}
onSelected={this.onSelected}>
<div ref={this.interactionElRef} className={'canvas-element ' + (this.state.selected ? 'selected' : '')}>
Select me
</div>
</Selectable>
)
}
}
Selectable.js
import { Component } from 'react'
import PropTypes from 'prop-types'
export default class Selectable extends Component {
static propTypes = {
iElRef: PropTypes.shape({
current: PropTypes.instanceOf(Element)
}).isRequired,
onSelected: PropTypes.func.isRequired
}
constructor(props) {
super(props)
this.state = {
selected: false
}
}
onClick = (e) => {
const selected = !this.state.selected
this.setState({ selected })
this.props.onSelected(selected)
}
componentDidMount() {
this.props.iElRef.current.addEventListener('click', this.onClick)
}
componentWillUnmount() {
this.props.iElRef.current.removeEventListener('click', this.onClick)
}
render() {
return this.props.children
}
}
Works well enough. The Selectable wrapper does not need to create a new div because its parent provides it with a reference to another element that is to become selectable.
However, I've been recommended on numerous occasions to stop using such Wrapper composition and instead achieve reusability through Higher Order Components. Willing to experiment with HoCs, I gave it a try but did not come further than this:
CanvasElement.js
import React, { Component } from 'react'
import Selectable from '../enhancers/Selectable'
import flow from 'lodash.flow'
import './CanvasElement.css'
class CanvasElement extends Component {
constructor(props) {
super(props)
this.interactionElRef = React.createRef()
}
render() {
return (
<div ref={this.interactionElRef}>
Select me
</div>
)
}
}
export default flow(
Selectable()
)(CanvasElement)
Selectable.js
import React, { Component } from 'react'
export default function makeSelectable() {
return function decorateComponent(WrappedComponent) {
return class Selectable extends Component {
componentDidMount() {
// attach to interaction element reference here
}
render() {
return (
<WrappedComponent {...this.props} />
)
}
}
}
}
The problem is that there appears to be no obvious way to connect the enhanced component's reference (an instance variable) to the higher order component (the enhancer).
How would I "pass in" the instance variable (the interactionElRef) from the CanvasElement to its HOC?
I came up with a different strategy. It acts roughly like the Redux connect function, providing props that the wrapped component isn't responsible for creating, but the child is responsible for using them as they see fit:
CanvasElement.js
import React, { Component } from "react";
import makeSelectable from "./Selectable";
class CanvasElement extends Component {
constructor(props) {
super(props);
}
render() {
const { onClick, selected } = this.props;
return <div onClick={onClick}>{`Selected: ${selected}`}</div>;
}
}
CanvasElement.propTypes = {
onClick: PropTypes.func,
selected: PropTypes.bool,
};
CanvasElement.defaultProps = {
onClick: () => {},
selected: false,
};
export default makeSelectable()(CanvasElement);
Selectable.js
import React, { Component } from "react";
export default makeSelectable = () => WrappedComponent => {
const selectableFactory = React.createFactory(WrappedComponent);
return class Selectable extends Component {
state = {
isSelected: false
};
handleClick = () => {
this.setState({
isSelected: !this.state.isSelected
});
};
render() {
return selectableFactory({
...this.props,
onClick: this.handleClick,
selected: this.state.isSelected
});
}
}
};
https://codesandbox.io/s/7zwwxw5y41
I know that doesn't answer your question. I think you're trying to let the child get away without any knowledge of the parent.
The ref route feels wrong, though. I like the idea of connecting the tools to the child. You can respond to the click in either one.
Let me know what you think.
Just as you did on DOM element for CanvasElement, Ref can be attached to class component as well, checkout the doc for Adding a Ref to a Class Component
export default function makeSelectable() {
return function decorateComponent(WrappedComponent) {
return class Selectable extends Component {
canvasElement = React.createRef()
componentDidMount() {
// attach to interaction element reference here
console.log(this.canvasElement.current.interactionElRef)
}
render() {
return (
<WrappedComponent ref={this.canvasElement} {...this.props} />
)
}
}
}
}
Also, do checkout Ref forwarding if you need child instance reference in ancestors that's multiple levels higher in the render tree. All those solutions are based on assumptions that you're on react 16.3+.
Some caveats:
In rare cases, you might want to have access to a child’s DOM node from a parent component. This is generally not recommended because it breaks component encapsulation, but it can occasionally be useful for triggering focus or measuring the size or position of a child DOM node.
While you could add a ref to the child component, this is not an ideal solution, as you would only get a component instance rather than a DOM node. Additionally, this wouldn’t work with functional components. https://reactjs.org/docs/forwarding-refs.html
I've now come up with an opinionated solution where the HoC injects two callback functions into the enhanced component, one to register the dom reference and another to register a callback that is called when an element is selected or deselected:
makeElementSelectable.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import movementIsStationary from '../lib/movement-is-stationary';
/*
This enhancer injects the following props into your component:
- setInteractableRef(node) - a function to register a React reference to the DOM element that should become selectable
- registerOnToggleSelected(cb(bool)) - a function to register a callback that should be called once the element is selected or deselected
*/
export default function makeElementSelectable() {
return function decorateComponent(WrappedComponent) {
return class Selectable extends Component {
static propTypes = {
selectable: PropTypes.bool.isRequired,
selected: PropTypes.bool
}
eventsAdded = false
state = {
selected: this.props.selected || false,
lastDownX: null,
lastDownY: null
}
setInteractableRef = (ref) => {
this.ref = ref
if (!this.eventsAdded && this.ref.current) {
this.addEventListeners(this.ref.current)
}
// other HoCs may set interactable references too
this.props.setInteractableRef && this.props.setInteractableRef(ref)
}
registerOnToggleSelected = (cb) => {
this.onToggleSelected = cb
}
componentDidMount() {
if (!this.eventsAdded && this.ref && this.ref.current) {
this.addEventListeners(this.ref.current)
}
}
componentWillUnmount() {
if (this.eventsAdded && this.ref && this.ref.current) {
this.removeEventListeners(this.ref.current)
}
}
/*
keep track of where the mouse was last pressed down
*/
onMouseDown = (e) => {
const lastDownX = e.clientX
const lastDownY = e.clientY
this.setState({
lastDownX, lastDownY
})
}
/*
toggle selected if there was a stationary click
only consider clicks on the exact element we are making interactable
*/
onClick = (e) => {
if (
this.props.selectable
&& e.target === this.ref.current
&& movementIsStationary(this.state.lastDownX, this.state.lastDownY, e.clientX, e.clientY)
) {
const selected = !this.state.selected
this.onToggleSelected && this.onToggleSelected(selected, e)
this.setState({ selected })
}
}
addEventListeners = (node) => {
node.addEventListener('click', this.onClick)
node.addEventListener('mousedown', this.onMouseDown)
this.eventsAdded = true
}
removeEventListeners = (node) => {
node.removeEventListener('click', this.onClick)
node.removeEventListener('mousedown', this.onMouseDown)
this.eventsAdded = false
}
render() {
return (
<WrappedComponent
{...this.props}
setInteractableRef={this.setInteractableRef}
registerOnToggleSelected={this.registerOnToggleSelected} />
)
}
}
}
}
CanvasElement.js
import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import PropTypes from 'prop-types'
import flowRight from 'lodash.flowright'
import { moveSelectedElements } from '../actions/canvas'
import makeElementSelectable from '../enhancers/makeElementSelectable'
class CanvasElement extends PureComponent {
static propTypes = {
setInteractableRef: PropTypes.func.isRequired,
registerOnToggleSelected: PropTypes.func
}
interactionRef = React.createRef()
componentDidMount() {
this.props.setInteractableRef(this.interactionRef)
this.props.registerOnToggleSelected(this.onToggleSelected)
}
onToggleSelected = async (selected) => {
await this.props.selectElement(this.props.id, selected)
}
render() {
return (
<div ref={this.interactionRef}>
Select me
</div>
)
}
}
const mapStateToProps = (state, ownProps) => {
const {
canvas: {
selectedElements
}
} = state
const selected = !!selectedElements[ownProps.id]
return {
selected
}
}
const mapDispatchToProps = dispatch => ({
selectElement: bindActionCreators(selectElement, dispatch)
})
const ComposedCanvasElement = flowRight(
connect(mapStateToProps, mapDispatchToProps),
makeElementSelectable()
)(CanvasElement)
export default ComposedCanvasElement
This works, but I can think of at least one significant issue: the HoC injects 2 props into the enhanced component; but the enhanced component has no way of declaratively defining which props are injected and just needs to "trust" that these props are magically available
Would appreciate feedback / thoughts on this approach. Perhaps there is a better way, e.g. by passing in a "mapProps" object to makeElementSelectable to explicitly define which props are being injected?
I have the following class
class MatchBox extends React.Component {
constructor(props) {
super(props);
this.countdownHandler = null;
this.showBlocker = true;
this.start = this.start.bind(this);
}
start() {
...
}
render() {
...
return (
<div style={ styles.mainContainer } className="fluid-container">
...
</div>
);
}
};
function mapStateToProps(state) {
...
}
function matchDispatchToProps(dispatch) {
...
}
export default withRouter(connect(mapStateToProps, matchDispatchToProps, null, { withRef: true })(MatchBox));
which is used in this class
class GameBox extends React.Component {
constructor(props) {
super(props);
...
}
render() {
var mainElement = null;
switch(this.props.mainElement.element) {
case 'SEARCHING': mainElement = <SearchingBox gameType={ this.props.gameType }/>; break;
case 'MATCH': mainElement = <MatchBox ref='matchBox'/>; break;
default: mainElement = <SearchingBox/>;
}
return (
<div style={ styles.mainContainer } className="fluid-container">
{ mainElement }
</div>
);
}
};
function mapStateToProps(state) {
...
}
function matchDispatchToProps(dispatch) {
...
}
export default withRouter(connect(mapStateToProps, matchDispatchToProps, null, { withRef: true })(GameBox));
And I can't get the ref of the object MatchBox. I tried with this.refs.matchBox and is null, also tried getting directly from ref(ref={(r) => { // r is null } }) and I don't know what to try anymore.
I'm using react-router-dom 4 and I don't know if function withRouter affect the outcome component.
It's not pretty, but I think this is the solution. withRouter exposes the child ref via a wrappedComponentRef callback, which gets us to the connect hoc. That exposes its child ref via getWrappedInstance if you pass the withRef attribute as you did. So you just have to combine both of those.
class GameBox extends React.Component {
matchboxRefCallback = (connectHOC) => {
this.matchboxRef = connectHOC ? connectHOC.getWrappedInstance() : null;
}
render() {
return <MatchBox wrappedComponentRef={this.matchboxRefCallback}/>;
}
}
Much more cleaner solution would be to create a HOC. which will forward the ref to actual component
const matchBoxHOC = (WrappedComponent) => {
class MatchBoxHOC extends React.Component {
render() {
const { forwardRef, ...rest } = this.props;
return <WrappedComponent {...rest} ref={forwardRef} />;
}
}
const WithRouterMatchBoxHOC = withRouter(MatchBoxHOC, { withRef: true });
return React.forwardRef((props, ref) => {
return <WithRouterMatchBoxHOC {...props} forwardRef={ref} />;
});
}
Call is like
export default matchBoxHOC(connect(mapStateToProps, matchDispatchToProps, null, { withRef: true })(MatchBox));
import React, { Component } from 'react'
import { connect } from 'react-redux';
export default function(strategies = []) {
class Authentication extends Component {
constructor() {
super()
this.state = {
allGreen: true
}
}
componentWillMount() {
const { history } = this.props
strategies.map(strategy => {
if (!this.props.auth[strategy]) {
this.setState({ allGreen: false })
history.replace('/')
}
})
}
componentWillUpdate(nextProps, nextState) {
const { history } = this.props
strategies.map(strategy => {
if (!nextProps.auth[strategy]) {
this.setState({ allGreen: false })
history.replace('/')
}
})
}
render() {
if (!this.state.allGreen) return (<div></div>)
return this.props.children
}
}
function mapStateToProps(state) {
return {
auth: state.auth
}
}
return connect(mapStateToProps)(Authentication)
}
I'm using 'destructor object' usually in ES6
For example, const { history } = this.props like.
However, I want to know whether there is an efficient way to have just one object destruction, and use it in all of component's method.(componentWillMount, componentWillUpdate ...)
Above picture, I used object destruction twice in componentWillMount method and componentWillUpdate method. ( const { history } = this.props )
I want to destruct object just once! Is there any solution ?
There's not performance issues on using destructurization multiple times (you are not expanding the whole object if this is your fear).
An ES 6 code like::
const aaa = {
a: 5,
b: 'ffff'
}
const { bbb } = aaa;
... is translated to...
var aaa = {
a: 5,
b: 'ffff'
};
var bbb = aaa.bbb;
Try it to https://babeljs.io
So use it, or simply use this.props.history