I'd like to manage to focus on a component that I've wrapped with withRouter. However, when I give the component a ref, I get the a warning about assigning a ref to a stateless component. I'm assuming this is because the ref is being attached to the withRouter HOC and not my component, as it is stateful. My general set up looks like this:
// InnerComponent.js
class InnerComponent extends Component {
constructor(props) {
super(props);
}
}
export default withRouter(InnerComponent);
// App.js
class App extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return (
<Router>
<InnerComponent ref={this.myRef}>
</Router>
);
}
I see this question has been asked before, but never answered. I'm new to React so please forgive me if I'm missing something obvious. Thanks in advance.
EDIT: I'm fairly sure what I need is here: https://reacttraining.com/react-router/web/api/withRouter, in the wrappedComponentRef section of the withRouter docs, but I don't understand how to implement it.
Based on #Ranjith Kumar answer I came up with the following solution that:
Is a bit shorter/simpler (no need for class component or withRef option)
Plays a bit better in tests and dev tools
const withRouterAndRef = Wrapped => {
const WithRouter = withRouter(({ forwardRef, ...otherProps }) => (
<Wrapped ref={forwardRef} {...otherProps} />
))
const WithRouterAndRef = React.forwardRef((props, ref) => (
<WithRouter {...props} forwardRef={ref} />
))
const name = Wrapped.displayName || Wrapped.name
WithRouterAndRef.displayName = `withRouterAndRef(${name})`
return WithRouterAndRef
}
Usage is the same:
// Before
export default withRouter(MyComponent)
// After
export default withRouterAndRef(MyComponent)
HOC component to forward inner component refs with withRouter HOC
const withRouterInnerRef = (WrappedComponent) => {
class InnerComponentWithRef extends React.Component {
render() {
const { forwardRef, ...rest } = this.props;
return <WrappedComponent {...rest} ref={forwardRef} />;
}
}
const ComponentWithRef = withRouter(InnerComponentWithRef, { withRef: true });
return React.forwardRef((props, ref) => {
return <ComponentWithRef {...props} forwardRef={ref} />;
});
}
Usage
class InnerComponent extends Component {
constructor(props) {
super(props);
}
}
export default withRouterInnerRef(InnerComponent);
Finally, I have done this way! this will work for sure
import { withRouter } from 'react-router';
//Just copy and add this withRouterAndRef HOC
const withRouterAndRef = (WrappedComponent) => {
class InnerComponentWithRef extends React.Component {
render() {
const { forwardRef, ...rest } = this.props;
return <WrappedComponent {...rest} ref={forwardRef} />;
}
}
const ComponentWithRouter = withRouter(InnerComponentWithRef, { withRef: true });
return React.forwardRef((props, ref) => {
return <ComponentWithRouter {...props} forwardRef={ref} />;
});
}
class MyComponent extends Component {
constructor(props) {
super(props);
}
}
//export using withRouterAndRef
export default withRouterAndRef (MyComponent)
I think you could use React.forwardRef (https://reactjs.org/docs/forwarding-refs.html) like this:
// InnerComponent.js
class InnerComponent extends Component {
constructor(props) {
super(props);
}
}
export default withRouter(InnerComponent);
// App.js
const InnerComponentWithRef = React.forwardRef((props, ref) => <InnerComponent ref={ref} props={props} />);
class App extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return (
<Router>
<InnerComponentWithRef ref={this.myRef}>
</Router>
);
}
Note: Untested code!
I thing you can use withRef option available while exporting the component.
See the below sample to export
// InnerComponent.js
class InnerComponent extends Component {
constructor(props) {
super(props);
this.exampleMethod = this.exampleMethod.bind(this);
}
exampleMethod(){
}
}
export default withRouter(InnerComponent , { withRef: true });
and also try the below method to access the methods using reference
this.myRef.getWrappedInstance().exampleMethod()
A much easier way to do this:
// InnerComponent.js
class InnerComponent extends Component {
constructor(props) {
super(props);
}
}
export default withRouter(InnerComponent);
// App.js
import InnerComponentWithRouter, { InnerComponent } from '/InnerComponent'
class App extends Component {
private myRef: InnerComponent|null = null;
constructor(props) {
super(props);
}
render() {
return (
<Router>
<InnerComponentWithRouter wrappedComponentRef={(r: InnerComponent) => this.myRef = r} />
</Router>
);
}
}
Simplified the good answer by #pandaiolo a bit more. Uses wrappedComponentRef, which is already used by withRouter
function withRouterAndRef(WrappedComponent) {
const RoutableComponent = withRouter(WrappedComponent);
const RoutableComponentWithRef = React.forwardRef((props, ref) => (
<RoutableComponent {...props} wrappedComponentRef={ref} />
));
const name = WrappedComponent.displayName || WrappedComponent.name;
RoutableComponentWithRef.displayName = `withRouterAndRef(${name})`;
return RoutableComponentWithRef;
}
Related
I am trying to get adaptValue from Component1 and use it in Component2. For some reason this does not work since my adaptValue is always null/undefined. Is it because Parent is a functional component?
const Parent = (props) => {
const [adaptValue, setAdapt] = useState(null);
return (
<div>
<Component1 setAdapt={setAdapt}/>
<Component2 adaptValue={adaptValue}/>
</div>
)
}
export default class Component1 extends Component {
constructor(props) {
super(props);
}
adaptValue = (value) =>{
DO_SOMETHING_WITH_VALUE
}
componentDidMount() {
this.props.setAdapt(this.adaptValue);
}
render() {
return something;
}
}
export default class Component2 extends Component {
constructor(props) {
super(props);
}
someFunction = (value) =>{
...
//adaptValue is always undefined
this.props.adaptValue(value)
...
}
render() {
return something;
}
}
UPDATE Made the parent a class component in the end and all works. Wondering whether this is a compatibility issue between functional or class-based components.
When passing setAdapt to Component1 ... setAdapt is already a function. There is no need to wrap it in another one. Component1 will modify the value, and Component2 will display it. Function Components have nothing to do with the behavior.
Try ...
App.js
import React, { useState } from "react";
import "./styles.css";
import Component1 from "./Component1";
import Component2 from "./Component2";
export default function App() {
const [adaptValue, setAdapt] = useState(null);
return (
<div>
<Component1 setAdapt={setAdapt} />
<Component2 adaptValue={adaptValue} />
</div>
);
}
Component1.js
import React, { Component } from "react";
export default class Component1 extends Component {
handleClick = () => {
this.props.setAdapt("New Value");
};
render() {
return <button onClick={() => this.handleClick()}>Set Value</button>;
}
}
Component2.js
import React, { Component } from "react";
export default class Component2 extends Component {
render() {
return !!this.props.adaptValue ? (
<h1>{`"${this.props.adaptValue}" <- Value of adaptValue`}</h1>
) : (
<h1>adaptValue Not Assigned</h1>
);
}
}
Sandbox Example ...
So I keep div element in my state. I want to change it's className in response to onClick event. I know I could do it with event.target.className but the code below is only the sample of a biggest application and it's not possible to use it there. As a resultant from changeClass function I get
"TypeError: Cannot assign to read only property 'className' of object '#'".
So I wonder is there any other way to do it?
import React, { Component } from "react";
import "./styles/style.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
myDiv: [
<div
id="firstDiv"
key={1}
className={"first"}
onClick={this.changeClass}
/>
]
};
}
changeClass = () => {
this.setState(prevState => {
return { myDiv: (prevState.myDiv[0].props.className = "second") };
});
};
render() {
return <div>{this.state.myDiv.map(div => div)}</div>;
}
}
export default App;
Don't put your jsx in state. only add className and state and onChangeClass use this.stateState to update className.
import React, { Component } from "react";
import "./styles/style.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
className:"first"
};
}
changeClass = () => {
this.setState({ classNmae: "two" });
};
render() {
return <div>
<div
id="firstDiv"
className={this.state.className}
onClick={this.changeClass}
/>
</div>;
}
}
export default App;
there's a simpler option try this:
import React, { Component } from "react";
import "./styles/style.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
className: "first"
};
}
changeClass = () => {
this.setState({className: "second"});
};
render() {
return <div
id="firstDiv"
className={this.state.className}
onClick={this.changeClass}>
</div>;
}
}
export default App;
You can use Hooks if you use a React version upper than 16.8
import React, { useState } from "react"
import "./styles/style.css"
const App = () => {
const [myClass, setMyClass] = useState("first")
const changeClass = () => {
setMyClass("second")
}
render() {
return <div
id="firstDiv"
className={myClass}
onClick={changeClass}>
</div>;
}
}
export default App
So I am using React's context because I have to change a state in the opposite direction.
E.g.:
App.js (has state) <--- My Component (changes the state in App.js)
I know how to do this using an onClick event. However, I fail understanding how to do this in a componentDidMount(). I created a basic example to illustrate what I'm trying to achieve:
MyComponent.js
import { MyConsumer } from '../App.js';
export default class MyComponent extends Component {
componentDidMount() {
// TRYING TO CHANGE STATE IN COMPONENTDIDMOUNT
<MyConsumer>
{({ actions }) => actions.setMyState(true)}
</MyConsumer>
}
render() {
return (
<SearchConsumer>
{({ actions }) => {
return (
<div onClick={() => actions.setMyState(true)}>
My content
</div>
)
}}
</SearchConsumer>
)
}
}
App.js
export const SearchContext = createContext();
export const SearchProvider = SearchContext.Provider;
export const SearchConsumer = SearchContext.Consumer;
class App extends Component {
constructor (props) {
super (props)
this.state = {
setMyState: 0,
}
}
render(){
return(
<SearchProvider value={
{
actions: {
setMyState: event => {
this.setState({ setMyState: 0 })
},
}
}
}>
<Switch>
<Route
exact path='/' render={(props) => <MyComponent />}
/>
</Switch>
</SearchProvider>
)
}
}
If you're using react 16.6.0 or later and are using exactly one context consumer, then the simplest approach is to use contextType (note that that's singular, not plural). This will cause react to make the value available on this.context, which you can then use in lifecycle hooks. For example:
// In some other file:
export default MyContext = React.createContext();
// and in your component file
export default class MyComponent extends Component {
static contextType = MyContext;
componentDidMount() {
const { actions } = this.context;
actions.setMyState(true);
}
// ... etc
}
If you are on an older version and thus can't use contextType, or if you need to get values from multiple contexts, you'll instead need to wrap your component in another component, and pass the context in via a prop.
// In some other file:
export default MyContext = React.createContext();
// and in your component file
class MyComponent extends Component {
static contextType = MyContext;
componentDidMount() {
const { actions } = this.props;
actions.setMyState(true);
}
// ... etc
}
export default props => (
<MyContext.Consumer>
{({ actions }) => (
<MyComponent actions={actions} {...props} />
)}
</MyContext.Consumer>
);
I fixed my problem by an idea given thanks to Nicholas Tower's answer. Instead of using the contextType in React, I just passed my actions as a prop in a different component. This way I could still use everything of my consumer if I just pass it on as a prop.
class MyComponent extends Component {
componentDidMount() {
this.props.actions.setMyState(true);
}
// ... etc
}
export default class MyComponentTwo extends Component {
render(){
return(
<MyConsumer>
{({ actions }) => (
<MyComponent actions={actions}/>
)}
</MyConsumer>
)
}
);
I am trying to find a solution to setState from a parent within child promise.
The parent component is
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
transition: false
};
}
handleTransition = () => {
this.setState(state => ({ transition: !state.transition }));
};
render() {
return <Child handleTransition={this.handleTransition} />;
}
}
of which this.props.handleTransition is to be triggered from a child component as
class Child extends Component {
constructor(props) {
super(props);
this.state = {};
}
onSubmit = event => {
firebase
.doCreateUserWithEmailAndPassword(email, password)
.then(() => {
// Trigger this.props.handleTransition here
})
...
Where this.props.handleTransition is wanting to be triggered with then of onSubmit
Please let me know if you require more detail? I would prefer not to use a library or package to achieve this but if it makes life easier I may consider. Redux is likely the best option but I would prefer not to unless necessary.
Note: this.props.handleTransition(); does the job but esLint returns an error of Must use destructuring props assignmenteslint(react/destructuring-assignment) and I am considering that this method is not the correct method.
// --- parent.js
import React, { Component, Fragment } from "react";
import { ChildComponent } from './containers/child'
class ParentContainer extends Component {
handleUpdate = () => {
// whatever you want to do here
}
render(){
return (
<Fragment>
<ChildComponent onUpdate={this.handleUpdate} />
</Fragment>
);
}
}
export default ParentContainer;
// --- child.js
import React, { Component, Fragment } from "react";
export class ChildComponent extends Component {
this.someAsyncFunction = () => {
fetch('/just/for/example')
.then(res =>
// Do whatever you need here, then hit your function on parent by bubbling the request up the chain
this.props.onUpdate();
)
}
render(){
return (
// whatever you want to do with this data
);
}
}
Suppose you have a simple react application (see my codesandbox):
import React from 'react';
import { render } from 'react-dom';
class RenderPropComponent extends React.Component {
render() {
console.log(this.example.test());
return this.props.render();
}
}
class Example extends React.Component {
test = () => console.log('Test successful!');
render() {
return <h1>I am an example!</h1>;
}
}
const App = () => (
<RenderPropComponent
render={() => {
return (
<Example ref={node => this.example = node} />
)
}}
/>
);
render(<App />, document.getElementById('root'));
This causes the error:
TypeError
Cannot read property 'test' of undefined
How can I assign a ref to a component rendered via render prop?
I know I can accomplish this with this.props.children as follows:
class RenderPropComponent extends React.Component {
const childComponents = React.Children.map(this.props.children, child => {
return React.cloneElement(child, {ref: node => this.example = node})
});
console.log(this.example.test());
render() {
return <div>{childComponents}</div>;
}
}
...
<RenderPropComponent>
<Example />
</RenderPropComponent>
But I would like to be able to use a render prop to do this! Any suggestions?
Not fully sure if it fits your case, but maybe you can pass the setRef function as an argument to the render prop? Like in this forked sandbox.
import React from 'react';
import { render } from 'react-dom';
const styles = {
fontFamily: 'sans-serif',
textAlign: 'center',
};
class Hello extends React.Component {
constructor(props) {
super(props);
this.setRef = this.setRef.bind(this);
}
setRef(node) {
this.example = node;
}
render() {
console.log(this.example && this.example.test());
return this.props.render(this.setRef);
}
}
class Example extends React.Component {
test = () => console.log('Test successful!');
render() {
return <h1>I am an example!</h1>;
}
}
const App = () => (
<div style={styles}>
<Hello
name="CodeSandbox"
render={(setRef) => {
return (
<Example ref={setRef} />
)
}}
/>
<h2>Start editing to see some magic happen {'\u2728'}</h2>
</div>
);
render(<App />, document.getElementById('root'));
The only problem i see here, is that on initial render this.example will not be available (that's why I've added a guard to the console log) and after it will be set, the rerender will not be triggered (since it's set on the instance and not in the state). If a rerender is needed, we can store the ref in the component state or force the rerender.
On the other hand, if you need a ref to be used in some event handler later on, that should do the trick without rerendering.
Look carefully, this keyword is used in the global scope, not in the scope of the example component.
const App = () => (
<RenderPropComponent
render={() => {
return (
<Example ref={node => this.example = node} />
)
}}
/>
);
If you didn’t spot it yet, take a look at that snippet:
class Foo {
constructor(stuffToDo) {
this.bar = ‘bar’;
this.stuffToDo = stuffToDo
}
doStuff() {
this.stuffToDo();
}
}
new Foo(() => console.log(this.bar)).doStuff();
This will log undefined, not bar, because this is derived from the current closure.