This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
I have a react application and I'm trying to build a Navbar component using data from a javascript file.
My NavbarData.js file looks like the following:
const NavbarData = [
{
id: 1,
text: "Typography"
},
{
id: 2,
text: "Buttons"
},
{
id: 3,
text: "icons"
}
]
export default NavbarData
I'm using .map() to iterate over this data and create NavbarItem components inside my App.js file.
// Build navmenu items
const navbarItems = this.state.navbarData.map(function(item){
return <NavbarItem key={item.id} text={item.text} id={item.id}></NavbarItem>
});
And here is my NavbarItem.js file
import React, { Component } from 'react';
class NavbarItem extends Component{
render(){
return(
<>
<li key={this.props.id} id={this.props.id}>{this.props.text}</li>
</>
)
}
}
export default NavbarItem
All of this gives me something that looks like this. Which is great.
But I want to add a click listener to each of these. As this is a single page application, I would like to render either a typography, buttons, or icons component. To do this, I need a function that will update the state of the parent component which in my case is just App.js
So I put the following function inside App.js
//This function changes the state so that different components can render
navClick(id) {
console.log('changed', id);
}
And I made sure to bind it in my constructor of App.js
this.navClick = this.navClick.bind(this);
My entire App.js file now looks like this
//React stuff
import React, { Component } from 'react';
//Bootstrap stuff
import { Container, Row, Col } from 'reactstrap';
//Layout
import NavbarItem from './layout/NavbarItem'
import NavbarData from './layout/NavbarData'
//Components
import Typography from './components/Typography/Typography'
import Buttons from './components/Buttons/Buttons'
//Styles
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
class App extends Component {
constructor(){
super();
// State determines what component is active and loads navbar data
this.state = {
navbarData: NavbarData,
typography: true,
buttons: false,
icons: false
}
this.navClick = this.navClick.bind(this);
}
//This function changes the state so that different components can render
navClick(id) {
console.log('changed', id);
}
render() {
// Build navmenu items
const navbarItems = this.state.navbarData.map(function(item){
return <NavbarItem key={item.id} text={item.text} id={item.id}></NavbarItem>
});
// Determine what component to display in main area using state
let elementToDisplay;
if(this.state.typography){
elementToDisplay = <Typography></Typography>
}
else if(this.state.buttons){
elementToDisplay = <Buttons></Buttons>
}
////////////////////////////////////////////////////
return (
<Container fluid={true}>
<Row>
<Col>Header</Col>
</Row>
<Row>
<Col xs="12" sm="12" md="1" lg="1" xl="1">
<ul>
{navbarItems}
</ul>
</Col>
<Col xs="12" sm="12" md="11" lg="11" xl="11">
{elementToDisplay}
</Col>
</Row>
<Row>
<Col>Footer</Col>
</Row>
</Container>
);
}
}
export default App;
The problem comes when I try to attach the navClick function to the mapped NavbarItem like so.
// Build navmenu items
const navbarItems = this.state.navbarData.map(function(item){
return <NavbarItem navigationWhenClicked={this.navClick} key={item.id} text={item.text} id={item.id}></NavbarItem>
});
The error I receive is the following:
TypeError: this is undefined
When googleing this issue, this is the top post.
React: "this" is undefined inside a component function
But that's not my problem as I am making sure to bind my function.
I really have no idea what I'm doing wrong here. Any help would be appreciated.
The function you pass to .map also has its own this binding. The simplest solution is to pass this as second argument to .map:
const navbarItems = this.state.navbarData.map(function(item) {
...
}, this);
this inside the function will be set to whatever you pass as second argument, which in this case is the component instance.
Alternatively you can use an arrow function instead of a function expression, since this is resolved lexically (i.e. like any other variabe) inside arrow functions:
const navbarItems = this.state.navbarData.map(
item => <NavbarItem navigationWhenClicked={this.navClick} key={item.id} text={item.text} id={item.id} />
});
See also: How to access the correct `this` inside a callback?
Related
My application consists of several pages. Every page has a ToastContainer component and some other component that behaves as a small single-page application (in this case, Job):
Note that Job and ToastContainer are siblings.
I have set up some basic toasts in my application and I want to be able to call a method on ToastContainer called pushToast(...) from anywhere in my application, since many child components of make AJAX calls that return feedback/responses to the user and it is not feasible to pass down a toast method into every component that I have.
const ToastContext = React.createContext(); //???
export default class ToastContainer extends Component {
constructor(props) {
super(props);
this.state = {
toastList: [],
}
}
render() {
return(
<div id="toast-container" className="toast-container position-absolute top-0 end-0 p-3" style={{'zIndex': 999}}>
{this.state.toastList.map(toast => (
<Toast .../>
))}
</div>
)
}
pushToast = (title, time, content) => //HOW CAN I MAKE THIS METHOD ACCESSIBLE TO JOB AND ITS CHILDREN?
{
var newToast = {
title: title,
time: time,
content: content,
}
this.setState({
toastList: [...this.state.toastList, newToast]
})
}
I think what I need to use are React.js contexts, but I don't know where to define the context and if the other components (such as Job) will have access to it. I need to somehow send pushToast defined in ToastContainer into every component (globally) so that I can call it from anywhere I want
way to solve this problem could be creating a context wrapper, first of all, you have to create a file that represents the ToastContextWrapper then creates a wrapper component that holds the state of your toats and pushToast function and then passes it to the context provider and wraps whole your project (because you want to access it from everywhere you want, otherwise you can consider a specific scope).
let me give you an example by code:
ToastContextWrapper.jsx:
export const ToastContext = React.createContext(undefined);
export default function ToastContextWrapper({ children }) {
const [toastData, setToastData] = React.useState([]);
const pushToast = (newToast) => setToastData((prev) => [...prev, newToast]);
return (
<ToastContext.Provider
value={{
value: toastData,
pushToast,
}}>
{children}
</ToastContext.Provider>
);
}
then you have to wrap your project by this component:
index/App.js:
const Child = () => {
const toastContext = React.useContext(ToastContext);
return (
<>
<h1>{JSON.stringify(toastContext.value)}</h1>
<button onClick={() => toastContext.pushToast('BlahBlah ')}>
Call ToastData!
</button>
</>
);
};
function App() {
return (
<ToastContextWrapper>
<Child />
</ToastContextWrapper>
);
}
in this way by using ToastContext you have access to the values, the first one is toast state, and the seconds one is pushToast.
I have the next code, where I import NextButton and GroupButton from TitleHeader,
those components are simple buttons
After that, I declared a simple array ButtonsArray and filled it with those components in the useEffect segment, in adition, I 'bind' the Button function to the button component.
Example :
<NextButton function={ShowSearchBar}/>
Then, my other component TitleHeader receives the array and render the components inside it using a map function
My issue is, if I use the const array ButtonsArray with the components loaded as props in TitleHeader, when press the NextButton in the UI to confirm everything is working something weird happens
The only job of NextButton is execute ShowSearchBar function whose have to switch a const from true to false and vice versa but it doest not work,
If i debug the program, when I press the button, the program enters to the ShowSearchBar function but ALWAYS allowFind is false
Note: if I declare the array directly in the TitleHeader params everything works fine
import React, { useState, useEffect } from "react";
import { TitleHeader, NextButton, GroupButton } from "../Common/TitleHeader";
export const ACATG001 = () => {
const [allowFind, setAllowFind] = useState(false);
const [allowGroup, setAllowGroup] = useState(false);
const [ButtonsArray, setButtonsArray] = useState([]);
useEffect(() => {
setButtonsArray([
<NextButton function={ShowSearchBar} />,
<GroupButton function={ShowGroupBar} />,
]);
}, []);
function ShowSearchBar() {
setAllowFind(!allowFind);
}
return (
<GeneralContainer>
//doesnt work (using a const type array and filled in UseEffect)
<TitleHeader
Title={t("TTER001")}
BarSize="300px"
Embedded={false}
ButtonsArray={ButtonsArray}
/>
//Works declaring the array and the items inline
<TitleHeader
Title={t("TTER001")}
BarSize="300px"
Embedded={false}
ButtonsArray={[
<NextButton function={ShowSearchBar} />,
<GroupButton function={ShowGroupBar} />,
]}
/>
</GeneralContainer>
);
};
Second JS TitleHeader
import React, { Component } from "react";
import { Button } from "primereact/button";
export class TitleHeader extends Component {
constructor() {
super();
}
componentDidMount() {}
render() {
let TitleDesing;
TitleDesing = (
<div className="Buttons-Group">
{this.props.ButtonsArray.map((component, index) => (
<React.Fragment key={index}>{component}</React.Fragment>
))}
</div>
);
return TitleDesing;
}
}
export const NextButton = (props) => {
return (
<Button
id="nextButton"
label="test"
tooltip="Next"
className="p-button-rounded p-button-text"
onClick={props.function}
>
<CgChevronRight size="20PX" color=" #d6f1fa" />{" "}
</Button>
);
};
If the update you do to a state depends only on its current value, always use the function callback version of the dispatcher, this will guarantee you don't use a stale value
function ShowSearchBar() {
setAllowFind((previousAllowFind) => !previousAllowFind)
}
I have the following (using Material UI)....
import React from "react";
import { NavLink } from "react-router-dom";
import Tabs from "#material-ui/core/Tabs";
import Tab from "#material-ui/core/Tab";
function LinkTab(link){
return <Tab component={NavLink}
to={link.link}
label={link.label}
value={link.link}
key={link.link}
/>;
}
In the new versions this causes the following warning...
Warning: Function components cannot be given refs. Attempts to access
this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of ForwardRef.
in NavLink (created by ForwardRef)
I tried changing to...
function LinkTab(link){
// See https://material-ui.com/guides/composition/#caveat-with-refs
const MyLink = React.forwardRef((props, ref) => <NavLink {...props} ref={ref} />);
return <Tab component={MyLink}
to={link.link}
label={link.label}
value={link.link}
key={link.link}
/>;
}
But I still get the warning. How do I resolve this issue?
Just give it as innerRef,
// Client.js
<Input innerRef={inputRef} />
Use it as ref.
// Input.js
const Input = ({ innerRef }) => {
return (
<div>
<input ref={innerRef} />
</div>
)
}
NavLink from react-router is a function component that is a specialized version of Link which exposes a innerRef prop for that purpose.
// required for react-router-dom < 6.0.0
// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678
const MyLink = React.forwardRef((props, ref) => <NavLink innerRef={ref} {...props} />);
You could've also searched our docs for react-router which leads you to https://mui.com/getting-started/faq/#how-do-i-use-react-router which links to https://mui.com/components/buttons/#third-party-routing-library. The last link provides a working example and also explains how this will likely change in react-router v6
You can use refs instead of ref. This only works as it avoids the special prop name ref.
<InputText
label="Phone Number"
name="phoneNumber"
refs={register({ required: true })}
error={errors.phoneNumber ? true : false}
icon={MailIcon}
/>
In our case, we were was passing an SVG component (Site's Logo) directly to NextJS's Link Component which was a bit customized and we were getting such error.
Header component where SVG was used and was "causing" the issue.
import Logo from '_public/logos/logo.svg'
import Link from '_components/link/Link'
const Header = () => (
<div className={s.headerLogo}>
<Link href={'/'}>
<Logo />
</Link>
</div>
)
Error Message on Console
Function components cannot be given refs. Attempts to access this ref will fail.
Did you mean to use React.forwardRef()?
Customized Link Component
import NextLink from 'next/link'
import { forwardRef } from 'react'
const Link = ({ href, shallow, replace, children, passHref, className }, ref) => {
return href ? (
<NextLink
href={href}
passHref={passHref}
scroll={false}
shallow={shallow}
replace={replace}
prefetch={false}
className={className}
>
{children}
</NextLink>
) : (
<div className={className}>{children}</div>
)
}
export default forwardRef(Link)
Now we made sure we were using forwardRef in the our customized Link Component but we still got that error.
In order to solve it, I changed the wrapper positioning of SVG element to this and :poof:
const Header = () => (
<Link href={'/'}>
<div className={s.headerLogo}>
<Logo />
</div>
</Link>
)
If you find that you cannot add a custom ref prop or forwardRef to a component, I have a trick to still get a ref object for your functional component.
Suppose you want to add ref to a custom functional component like:
const ref = useRef();
//throws error as Button is a functional component without ref prop
return <Button ref={ref}>Hi</Button>;
You can wrap it in a generic html element and set ref on that.
const ref = useRef();
// This ref works. To get button html element inside div, you can do
const buttonRef = ref.current && ref.current.children[0];
return (
<div ref={ref}>
<Button>Hi</Button>
</div>
);
Of course manage state accordingly and where you want to use the buttonRef object.
to fix this warning you should wrap your custom component with the forwardRef function as mentioned in this blog very nicely
const AppTextField =(props) {return(/*your component*/)}
change the above code to
const AppTextField = forwardRef((props,ref) {return(/*your component*/)}
const renderItem = ({ item, index }) => {
return (
<>
<Item
key={item.Id}
item={item}
index={index}
/>
</>
);
};
Use Fragment to solve React.forwardRef()? warning
If you're using functional components, then React.forwardRef is a really nice feature to know how to use for scenarios like this. If whoever ends up reading this is the more hands on type, I threw together a codesandbox for you to play around with. Sometimes it doesn't load the Styled-Components initially, so you may need to refresh the inline browser when the sandbox loads.
https://codesandbox.io/s/react-forwardref-example-15ql9t?file=/src/App.tsx
// MyAwesomeInput.tsx
import React from "react";
import { TextInput, TextInputProps } from "react-native";
import styled from "styled-components/native";
const Wrapper = styled.View`
width: 100%;
padding-bottom: 10px;
`;
const InputStyled = styled.TextInput`
width: 100%;
height: 50px;
border: 1px solid grey;
text-indent: 5px;
`;
// Created an interface to extend the TextInputProps, allowing access to all of its properties
// from the object that is created from Styled-Components.
//
// I also define the type that the forwarded ref will be.
interface AwesomeInputProps extends TextInputProps {
someProp?: boolean;
ref?: React.Ref<TextInput>;
}
// Created the functional component with the prop type created above.
//
// Notice the end of the line, where you wrap everything in the React.forwardRef().
// This makes it take one more parameter, called ref. I showed what it looks like
// if you are a fan of destructuring.
const MyAwesomeInput: React.FC<AwesomeInputProps> = React.forwardRef( // <-- This wraps the entire component, starting here.
({ someProp, ...props }, ref) => {
return (
<Wrapper>
<InputStyled {...props} ref={ref} />
</Wrapper>
);
}); // <-- And ending down here.
export default MyAwesomeInput;
Then on the calling screen, you'll create your ref variable and pass it into the ref field on the component.
// App.tsx
import React from "react";
import { StyleSheet, Text, TextInput, View } from "react-native";
import MyAwesomeInput from "./Components/MyAwesomeInput";
const App: React.FC = () => {
// Set some state fields for the inputs.
const [field1, setField1] = React.useState("");
const [field2, setField2] = React.useState("");
// Created the ref variable that we'll use down below.
const field2Ref = React.useRef<TextInput>(null);
return (
<View style={styles.app}>
<Text>React.forwardRef Example</Text>
<View>
<MyAwesomeInput
value={field1}
onChangeText={setField1}
placeholder="field 1"
// When you're done typing in this field, and you hit enter or click next on a phone,
// this makes it focus the Ref field.
onSubmitEditing={() => {
field2Ref.current.focus();
}}
/>
<MyAwesomeInput
// Pass the ref variable that's created above to the MyAwesomeInput field of choice.
// Everything should work if you have it setup right.
ref={field2Ref}
value={field2}
onChangeText={setField2}
placeholder="field 2"
/>
</View>
</View>
);
};
const styles = StyleSheet.create({
app: {
flex: 1,
justifyContent: "center",
alignItems: "center"
}
});
export default App;
It's that simple! No matter where you place the MyAwesomeInput component, you'll be able to use a ref.
I just paste here skychavda solution, as it provide a ref to a child : so you can call child method or child ref from parent directly, without any warn.
source: https://github.com/reactjs/reactjs.org/issues/2120
/* Child.jsx */
import React from 'react'
class Child extends React.Component {
componentDidMount() {
const { childRef } = this.props;
childRef(this);
}
componentWillUnmount() {
const { childRef } = this.props;
childRef(undefined);
}
alertMessage() {
window.alert('called from parent component');
}
render() {
return <h1>Hello World!</h1>
}
}
export default Child;
/* Parent.jsx */
import React from 'react';
import Child from './Child';
class Parent extends React.Component {
onClick = () => {
this.child.alertMessage(); // do stuff
}
render() {
return (
<div>
<Child childRef={ref => (this.child = ref)} />
<button onClick={this.onClick}>Child.alertMessage()</button>
</div>
);
}
}
I'm a beginner in React and I'm facing a problem that I can't solve.
I get an object from an API call.
In my console log, it appears well. I am able to access first-level properties (like ID for example) but if I want to access ACF values for example I get the error:
TypeError: can't access property "date_project", this.state.projet.acf is undefined
I guess I don't do correctly to get the data from the ACF object but I don't understand how to do otherwise.
Here's my code:
[import React, { Component } from 'react';
import '../App.scss';
import {Row, Container, Col} from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import {Config} from '../config';
import { withRouter } from "react-router";
class Projet extends Component {
constructor(props) {
super(props);
this.state = {
projet: \[\]
};
}
async componentDidMount() {
const id = parseInt(this.props.match.params.id);
const response = await fetch(Config.apiUrl + `wp-json/wp/v2/projet/${id}`);
const json = await response.json();
this.setState({ projet: json });
}
renderProjet() {
console.log('projet', this.state.projet)
return (
<p>{this.state.projet.acf.date_projet}</p>
)
}
render() {
return (
<Container fluid className="App-home">
<Row className="align-items-left">
<div>
{ this.renderProjet()}
</div>
</Row>
</Container>
)
}
}
export default (Projet);][1]
It's because of asynchronous call. When its trying to access acf at that time it is not available. Either create loading variable to track it or do not render component if data is not available:
render() {
if(!this.state.projet?.acf) return null; //Do not render if data is not available
return (
<Container fluid className="App-home">
<Row className="align-items-left">
<div>
{ this.renderProjet()}
</div>
</Row>
</Container>
)
}
New to React, in the following code I am passing data between two components via the parent. Flow is from Search to the parent App then to another child Sidebar. I am able to send to both from Search to App and App to Sidebar individually but for some reason setState is not behaving as expected making the link to trigger a refresh of <Search updateMenu={this.handleSearchResult} /> as you can see in the console.log code comments below:
import React, { Component } from 'react';
import './App.css';
import Search from './Search';
import Sidebar from './Sidebar';
class App extends Component {
constructor() {
super()
this.state = {
menu: []
}
}
handleSearchResult = (array) => {
// always the correct value
console.log('in ', array);
this.setState( {menu: menuList})
// 1st call : empty
// 2nd call : previous value not showing on 1st call + new value as expected
// does not trigger <Sidebar list={this.state.menu}/>
console.log('out', this.state.menu);
}
render() {
return (
<div className="App">
// not refreshing
<Search updateMenu={this.handleSearchResult} />
<Sidebar list={this.state.menu}/>
</div>
);
}
}
export default App;
Logging this.setState(). Is not so straight forward. this.setState() is asynchronus.
Here is a reference on Medium.