Forwarding Refs: forwardedRef is always null - javascript

I have an ant design Table component that I want ref to be attached to.
I want to be able to use the tableRef in HOC withCustomPagination's lifecycle componentDidUpdate method.
Following the React Docs Forwarding Refs, that I could not clearly comprehend. I could cook up the following code:
App.js
import WrappedTable from '/path/to/file';
class App extends React.Component {
render() {
const tableRef = React.createRef();
return (
<WrappedTable ref={tableRef} />
)
}
}
Table.js
import withCustomPagination from '/path/to/file';
class Table extends React.Component {
constructor(props) {
super(props);
}
render() {
<TableContainer ref={this.props.forwardedRef} />
}
}
const WrappedTable = withCustomPagination(Table);
export default WrappedTable;
withCustomPagination.js
import CustomPagination from 'path/to/file';
const withCustomPagination = tableRef => Component => {
class WithCustomPagination extends React.Component {
constructor(props) {
super(props);
this.state = {
rows: 1,
dataLength: props.dataLength,
}
}
componentDidUpdate() {
tableRef.current.state ..... //logic using ref, Error for this line
this.state.rows ..... //some logic
}
render() {
const { forwardedRef } = this.props;
return (
<Component {...this.state} ref={forwardedRef} />
<CustomPagination />
)
}
}
return React.forwardRef((props, ref) => {
return <WithCustomPagination {...props} forwardedRef={ref} />;
});
}
export default withCustomPagination;
After debugging, I find that forwardedRef is always null.

Your issue is happening in your HOC:
here
const withCustomPagination = tableRef => Component => {
You need to remove that parameter. The way to access to the ref prop is simply in your componentDidUpdate method like forwardedRef prop e.g:
import CustomPagination from 'path/to/file';
const withCustomPagination = Component => {
class WithCustomPagination extends React.Component {
constructor(props) {
super(props);
this.state = {
rows: 1,
dataLength: props.dataLength,
}
}
componentDidUpdate() {
//You got the ref here
console.log(forwardedRef.current)
}
render() {
const { forwardedRef } = this.props;
return (
<Component {...this.state} ref={forwardedRef} />
<CustomPagination />
)
}
}
return React.forwardRef((props, ref) => {
return <WithCustomPagination {...props} forwardedRef={ref} />;
});
}
export default withCustomPagination;
Also somethings to have in account are:
You should not create the ref in the render method because this method is raised every time you set a state. I recommend you to do it in the constructor:
import WrappedTable from '/path/to/file';
class App extends React.Component {
constructor(){
super();
this.reference = React.createRef();
}
render() {
return (
<WrappedTable ref={this.reference} />
)
}
}
Also in you HOC render only one child or use React.Fragment. Besides do not forget the send the rest properties:
const withCustomPagination = Component => {
class WithCustomPagination extends React.Component {
constructor(props) {
super(props);
this.state = {
rows: 1,
dataLength: props.dataLength,
}
}
componentDidUpdate() {
//You got the ref here
console.log(forwardedRef.current)
}
render() {
// Do not forget to send the rest of properties here like:
const { forwardedRef, ...rest } = this.props;
return (
<React.Fragment>
<Component {...this.state} ref={forwardedRef} {...rest} />
<CustomPagination />
</React.Fragment>
)
}
}
return React.forwardRef((props, ref) => {
return <WithCustomPagination {...props} forwardedRef={ref} />;
});
}
export default withCustomPagination;
EDIT:
Add the reference of the ref prop
import withCustomPagination from '/path/to/file';
class Table extends React.Component {
constructor(props) {
super(props);
this.reference = React.createRef();
}
render() {
<TableContainer ref={this.reference} />
}
}
const WrappedTable = withCustomPagination(Table);
export default WrappedTable;

To access the tableRef in HOC withCustomPagination, I removed const tableRef = React.createRef() from App.js and the corresponding ref = {tableRef} lines.
I pass tableRef to HOC, curried, withCustomPagination(tableRef)(NewGiftCardTable). I also removed all the Forwarding Refs logic in HOC, this I did because I needed access to tableRef only in HOC and not in App.js.
Added above removed lines to Table.js:
import withCustomPagination from '/path/to/file';
const tableRef = React.createRef();
class Table extends React.Component {
constructor(props) {
super(props);
}
render() {
<TableContainer ref={tableRef} />
}
const WrappedTable = withCustomPagination(tableRef)(Table);
export default WrappedTable;

Related

this.context is always empty in React, contextApi

test.js
export default class TestScreen extends React.Component {
static contextType= AppProvider;
componentDidMount() {
console.log('test',this.context);
}
render() {
return (
<AppConsumer>
{ (context) => (
<p>{context.favoriteAnimal}</p>
)}
</AppConsumer>
)
}
}
store.js
const initialState = {
favoriteAnimal: "cow",
};
export const AppContext = React.createContext();
export const AppConsumer = AppContext.Consumer;
export class AppProvider extends React.Component {
constructor(props) {
super(props);
this.state = initialState;
}
render() {
return (
<AppContext.Provider value={{
favoriteAnimal: this.state.favoriteAnimal,
}}>
{this.props.children}
</AppContext.Provider>
);
}
}
dependencies: {
"react": "^16.8.4",
"react-dom": "^16.8.4",
"react-scripts": "2.1.8"
},
this.context is empty {},
in test.js. cant find a way out , any help will be appreciated. thank you
Problem is that you are assigning the ContextType to AppProvider which is your component instead of the context returned by React.createContext. Once you make this change, you don't even need to use AppConsumer inside of render method
export default class TestScreen extends React.Component {
static contextType= AppContext;
componentDidMount() {
console.log('test',this.context);
}
render() {
return (
<p>{this.context.favoriteAnimal}</p>
)
}
}

Cannot read property 'state' of undefined in react-native context api?

I'm trying to context api in my ract-native app. But i'm getting this error.
TypeError: TypeError: Cannot read property 'number' of undefined. What is wrong my code?
appContext.js
import React from 'react';
export const AppContext = React.createContext();
class AppProvider extends React.Component {
constructor(props) {
super(props);
this.state = {
number: 10,
};
}
render() {
return
(
<AppContext.Provider value={this.state}>
{this.props.children}
</AppContext.Provider>
)
}
}
export default AppProvider;
homeScreen.js
import { AppContext } from './appContext';
<AppContext.Consumer>
{(context) => context.number}
</AppContext.Consumer>
This is because you are not using your AppProvider component anywhere in your App. Try like this:
const AppContext = React.createContext();
class AppProvider extends React.Component {
constructor( props ) {
super( props );
this.state = {
number: 10,
};
}
render() {
return (
<AppContext.Provider value={this.state}>
{this.props.children}
</AppContext.Provider>
);
}
}
class App extends React.Component {
render() {
return (
<AppProvider>
<AppContext.Consumer>
{context => context.number}
</AppContext.Consumer>
</AppProvider>
);
}
}
AppProvider is merely a standard component here. It renders the context's Provider and that one gets some children. So, you should use this AppProvider component somewhere in your app and pass a child with a Consumer.
If you want to keep your context in a separate file it would be like this:
Context and provider component
import React from "react";
export const AppContext = React.createContext();
class AppProvider extends React.Component {
constructor( props ) {
super( props );
this.state = {
number: 1745,
};
}
render() {
return (
<AppContext.Provider value={this.state}>
{this.props.children}
</AppContext.Provider>
);
}
}
export default AppProvider;
Main component
import React from "react";
import AppProvider, { AppContext } from "./AppProvider";
class App extends React.Component {
render() {
return (
<AppProvider>
<AppContext.Consumer>
{context => context.number}
</AppContext.Consumer>
</AppProvider>
);
}
}
export default App;

Accessing variable from different class

How to access the state variable testState from the different class UserAuthentication?
I have tried this without success:
import React from 'react';
import UserAuthenticationUI from './UserAuthentication/UserAuthenticationUI';
class App extends React.Component {
constructor(props) {
super(props);
this.userAuthenticationUI = React.createRef();
this.state={
testState: 'test message'
}
}
render() {
return(
<div>
<UserAuthenticationUI ref={this.userAuthenticationUI} />
<div>
)
}
}
export default App;
How to access this.state.teststate from class UserAuthenticationUI?
import React from "react";
import App from '../App';
class UserAuthenticationUI extends React.Component {
constructor(props) {
super(props);
this.app = React.createRef();
}
render() {
return(
<div>
<App ref={this.app} />
{console.log(this.state.testState)}
</div>
)
}
}
export default UserAuthenticationUI;
You need to pass it via props.
import React from "react";
import UserAuthenticationUI from "./UserAuthentication/UserAuthenticationUI";
class App extends React.Component {
constructor(props) {
super(props);
this.userAuthenticationUI = React.createRef();
this.setParentState = this.setParentState.bind(this);
this.state = {
testState: "test message"
};
}
setParentState(newStateValue){ // this is called from the child component
this.setState({
testState: newStateValue
})
};
render() {
return (
<div>
<UserAuthenticationUI
stateVariable={this.state.testState}
ref={this.userAuthenticationUI}
setParentState={this.setParentState}
/>
</div>
);
}
}
export default App;
UserAuthenticationUI:
import React from "react";
import App from "../App";
class UserAuthenticationUI extends React.Component {
constructor(props) {
super(props);
this.app = React.createRef();
this.onClick = this.onClick.bind(this);
}
onClick(){
const newStateValue = 'new parent state value';
if(typeof this.props.setParentState !== 'undefined'){
this.props.setParentState(newStateValue);
}
}
render() {
const stateProps = this.props.stateVariable;
return (
<div>
<App ref={this.app} />
<div onClick={this.onClick} />
{console.log(stateProps)}
</div>
);
}
}
export default UserAuthenticationUI;
You should think differently.
Try to read the variable via GET methods and set via SET methods.
Do not try to call the variable immediately
Hope this helps.
you can pass it through Props:
import React from 'react';
import UserAuthenticationUI from
'./UserAuthentication/UserAuthenticationUI';
class App extends React.Component {
constructor(props) {
super(props);
this.userAuthenticationUI = React.createRef();
this.state={
testState: 'test message'
}
}
render(){
return(
<div>
<UserAuthenticationUI testState={this.state.testState} />
<div>
)}
}
export default App;
UserAuthenticationUI:
import React from "react";
import App from '../App';
class UserAuthenticationUI extends React.Component
{
constructor(props){
super(props);
}
render(){
return(
<div>
<App/>
{console.log(this.props.testState)}
</div>
)}
}
export default UserAuthenticationUI;
You can access it via props:
<div>
<UserAuthenticationUI testState={this.state.testState} ref={this.userAuthenticationUI} />
<div>
and in UserAuthenticationUI class access it:
<div>
<App ref={this.app} />
{console.log(this.props.testState)}
</div>

React - Pass function to component that has default props

I have a React component that uses default props:
class MyComponent extends Component {
constructor(props) {
console.log('props', props);
super(props);
// rest of code here
}
MyComponent .defaultProps = {
__TYPE: 'MyDateRange',
};
When I use the component, without passing any props, the console log of props shows the default props, like it should.
Now, when I want to pass an additional prop (a function in this case), like this:
<MyComponent onEnterKey={() => console.log('snuh')}/>
The console log of props only shows the onEnterKey function.
What do I have to do to allow MyComponent to use the default props and accept a function? I've tried adding another argument to the constructor of MyComponent, but that doesn't work.
I tried and this is working :
import React from "react";
import { render } from "react-dom";
class MyComponent extends React.Component {
constructor(props) {
console.log("props", props);
super(props);
}
render() {
return null;
}
}
MyComponent.defaultProps = {
__TYPE: "MyDateRange"
};
render(
<MyComponent onEnterKey={() => console.log("snuh")} />,
document.getElementById("app")
);
You can see it here : https://codesandbox.io/s/wkw0k0j5o8
You can put the defaultProp on the class outside of the constructor like this:
class MyComponent extends Component {
constructor(props) {
console.log("props", props);
super(props);
}
render() {
return <div> test </div>;
}
}
MyComponent.defaultProps = {
__TYPE: "MyDateRange"
};
Alternatively, you can have defaultProps be a static property on the class:
class MyComponent extends Component {
static defaultProps = {
__TYPE: "MyDateRange"
};
constructor(props) {
console.log("props", props);
super(props);
}
render() {
return <div> test </div>;
}
}

React data do not go to child component after fetch

I'm having a problem with the function fetch. I'm trying to send just a number for example "1", and I have access to this data in all child components, but after calling fetch, I'm no longer able to access this data.
App.jsx:
import React, { Component } from 'react'
import './App.css';
import fetch from 'isomorphic-fetch'
import Header from './Header'
import Content from './Content'
import Footer from './Footer'
class App extends Component {
constructor(props) {
super(props)
this.state = {
stripdata: null
}
}
componentWillMount() {
fetch(`http://localhost:3000/data/info.json`)
.then(results => results.json())
.then(data => {
this.setState({
stripdata: data
})
// console.log(this.state.stripdata)
})
.catch(err => {
console.log("Didn't connect to API", err)
})
}
render() {
// console.log(this.state.stripdata)
return (
<div className="App">
<Header onQuery={1}/>
{
(this.state.data === null) ? <div className="loading">Loading data...</div> : <Content onResult={this.state.stripdata}/>
}
<Footer />
</div>
);
}
}
export default App;
Content.jsx:
import React, { Component } from 'react'
import Result from './Result'
class Content extends Component {
constructor(props) {
super(props);
this.state = {
stripdata: this.props.onResult
};
}
componentWillMount() {
}
render() {
console.log("im an Content: " + this.state.stripdata)
return (
<div className="Content">
<Result stripdata={ this.state.stripdata }/>
</div>
);
}
}
export default Content;
Result.jsx:
import React, { Component } from 'react'
import PersonCard from './PersonCard'
class Result extends Component {
constructor(props) {
super(props);
this.state = {
stripdata: this.props.stripdata
};
}
componentWillMount() {
}
render() {
console.log("im the Result: " + this.state.stripdata)
return (
<div className="result">
<PersonCard />
</div>
);
}
}
export default Result;
Please help. This is blocking my progress.
Fix the issue here:
<Header onQuery={1}/>
{
(this.state.stripdata === null) ? <div className="loading">Loading data...</div> : <Content onResult={this.state.stripdata}/>
}
You need to check properties in state with name stripdata.
And btw, fetch has to be performed in ComponentDidMount, see https://daveceddia.com/where-fetch-data-componentwillmount-vs-componentdidmount/
The problem is that, in your Results, you are only using the value from props once: in the constructor, where you set to state.
You should not set value in state from props. Instead, just use the props directly. Change Result to as following, then it will work proper:
import React, { Component } from 'react'
import PersonCard from './PersonCard'
class Result extends Component {
constructor(props) {
super(props);
// removed setting state from props.stripdata
}
render() {
console.log("im the Result: " + this.props.stripdata) // <-- using props!
return (
<div className="result">
<PersonCard />
</div>
);
}
}
export default Result;
In general it is considered bad practice/antipattern to set state from props.

Categories