React component fails to render due to undefined property - reactjs

I'm a newbie to react, I'm using the create-react-app package, and express generator. I can't seem to be able to render the react component due to undefined property, which I can't see to understand why is it undefined? Here is my code:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import PageContent from './App';
import * as serviceWorker from './serviceWorker';
const pageContent = new PageContent();
ReactDOM.render(
<React.StrictMode>
<pageContent.App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
class PageContent extends React.Component {
constructor(props) {
super(props)
this.state = {
apiResponse: 'test test test'
};
}
callAPI() {
fetch("http://localhost:3127/testAPI")
.then(res => res.text())
.then(res => this.setState({ apiResponse: 'hello' }));
}
componentWillMount() {
this.callAPI();
}
App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
<p className="App-intro">**{PageContent.state.apiResponse}</p>
</header>
</div>
);
}
}
export default PageContent;
This is the error I get:
TypeError: Cannot read property 'apiResponse' of undefined
App
src/App.js:39
36 | >
37 | Learn React
38 | </a>
> 39 | <p className="App-intro">**{PageContent.state.apiResponse}</p>
40 | ^ </header>
41 | </div>
42 | );
Thanks everyone for the help

You want to use:
{this.state.apiResponse}
Edit: I noticed you're rendering the App method directly after creating an instance of the PageContent class. You don't need to do this. You can simply rename the App() method to be render(), then remove the const pageContent = new PageContent(); and you can then render <PageContent /> instead of <pageContent.App />.

You are making 2 mistakes -
first write it as {this.state.apiResponse}
Your app.js file is not written properly, It should be something like this
import React from 'react';
import logo from './logo.svg';
import './App.css';
export default class PageContent extends React.Component {
constructor(props) {
super(props)
this.state = {
apiResponse: 'test test test'
};
}
callAPI() {
fetch("http://localhost:3127/testAPI")
.then(res => res.text())
.then(res => this.setState({ apiResponse: 'hello' }));
}
componentWillMount() {
this.callAPI();
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
<p className="App-intro">{this.state.apiResponse}</p>
</header>
</div>
);
}
}
after this import this PageContent in your index.js like this -
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import PageContent from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<PageContent />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();

Related

why is console logging this is undefined with react?

I recently came back to coding and I'm trying learn react on udemy. this code should fetch json files from a website and console.log them. instead I'm getting a this is undefined error.how do I get it to correctly log the information from the fetched website and remove this is undefined error?
import {Component} from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component() {
constructor(){
super();
this.state ={
monsters:[],
};
}
componentDidMount(){
fetch('https://jsonplaceholder.typicode.com/users').then((response)=>response.json()).then((users)=>console.log(users));
}
render(){
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}}
export default App;
Try this, We can use function component and hooks nowadays because it is easy to use and redable to others.
import React, { useEffect } from 'react';
const App = () => {
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then((response)=>response.json())
.then((users)=>console.log(users));
}, []);
return (
<div className='App'>
<h1>Hello React.</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
export default App;

Jest snapshot testing not generating appropriate snapshot and passing

I'm new at jest testing. Now I'm trying to test my react components using snapshot testing. I've encountered such problem: jest only updates snapshot for AppComponent, but does not for another component, also it passes all both snapshot tests. What's wrong?
Have tried passing names to snapshot toMatchSnapshot(), have tried to change type of TestComponent from function to class extending Component, have tried deleting old snapshots and testing again, all in wain. Also, tried to render TestComponent in AppComponent below AppComponent default html and it caused updating AppComponent snapshot only.
AppComponent
import React from 'react';
import logo from './logo.svg';
import './App.css';
import { TestComponent } from './TestComponent';
export function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer">
Learn React
</a>
</header>
</div>
);
}
export default App;
AppComponent test
import React from 'react';
import ReactDOM from 'react-dom';
import { App, reverseOfReverse, addTwoIntegers } from './App';
import renderer from 'react-test-renderer';
describe('snapshot tests', () => {
test('matches the snapshot', () => {
const tree = renderer.create(<App />).toJSON();
expect(tree).toMatchSnapshot('AppComponentSnapshot');
});
});
AppComponent snapshot
// Jest Snapshot v1
exports[`snapshot tests matches the snapshot: AppComponentSnapshot 1`] = `
<div
className="App"
>
<header
className="App-header"
>
<img
alt="logo"
className="App-logo"
src="logo.svg"
/>
<p>
Edit
<code>
src/App.js
</code>
and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
rel="noopener noreferrer"
target="_blank"
>
Learn React
</a>
</header>
</div>
`;
TestComponent
import logo from './logo.svg';
import React, { Component } from 'react';
export class TestComponent extends Component {
render() {
return (
<div className="TestComponent">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer">
Learn React
</a>
</header>
<div>lola</div>
<div>amanda</div>
</div>
);
}
}
export default TestComponent;
TestComponent test
import React from 'react';
import renderer from 'react-test-renderer';
import { TestComponent } from './TestComponent';
describe('snapshot for second component', () => {
test('matches second snapshot', () => {
const tree = renderer.create(<TestComponent />).toJSON;
expect(tree).toMatchSnapshot('TestComponentSnapshot');
});
});
TestComponent snapshot
// Jest Snapshot v1
exports[`snapshot for second component matches second snapshot: TestComponentSnapshot 1`] = `[Function]`;
I expected that snapshot test would also fill TestComponent snapshot with appropriate snapshot, or the test would fail, but neither happened.
I just faced this problem too. Spent an hour to realize that toJSON is missing a pair of parentheses. It's supposed to be a function call toJSON() instead of just toJSON. How silly

Creating a new component and adding it to the webpage in ReactJS

In reactjs, I have already created one component and added it to my Main.js file but now, I need to add one more component to it and due to JSX restriction of having only one root element per JSX, I cannot add one more component to it. I don't know where I'm going wrong in this.
`~~~~index.js file`
import React from "react";
import ReactDOM from "react-dom";
import Main from "./Main";
ReactDOM.render(
<Main/>,
document.getElementById("root")
);
-------------------------------------------------------
Main.js file
import React, { Component } from "react";
import Header from './Header';
// import Body from './Body';
import './index.css';
class Main extends Component {
render() {
return (
<div className="Main">
<Header image={require('./demo.jpg')}/>
{/* <Body/> */}
</div>
);
}
}
export default Main;
-------------------------------------------------------
Header.js file
import React from 'react'
import './Header.css';
// import Body from './Body';
export default (props) => {
const style= {
backgroundImage : "url(" + props.image + ")"
}
return (
<div className="body" style={style}>
<button className="btn" > Drawer </button>
<h1 className="heading1"> Questions </h1>
<button className="heading2"> Eye Button </button>
<h2 className="heading3"> Hi.. Sandeep Gautam </h2>
<h3 className="heading4"> Mind answering a few questions </h3>
</div>
)
}`

How Can I use UIkit 2.27.4 with Meteor/React?

Since UIKit 3.0 is in beta I would like to use the stable version UIKIT2.27.4 with React and Meteor, however it is not detecting it. I have imported it as follows:
In meteor client/main.js is as follows
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import '../imports/jquery-3.2.1.min.js';
import '../imports/uikit/css/uikit.min.css';
import '../imports/uikit/js/uikit.min.js';
class App extends Component {
render() {
return (
<div>
<nav className="uk-navbar">
Kareri
<ul className="uk-navbar-nav">
<li>Home </li>
<li>Trekking</li>
<li>Hotels</li>
<li>Contact</li>
</ul>
</nav>
</div>
);
}
};
Meteor.startup(() => {
ReactDOM.render(<App />, document.querySelector('.container'));
});
How can i get uikit to work with REACT and METEOR?

TypeError: Cannot read property 'array' of undefined when trying to use google-maps-react

I am new to ReactJS, but familiar with React Native. I am trying to to get a basic map component to be displayed.
My map component is
WaterMapView.js
import React, { Component } from 'react';
import { Map, InfoWindow, Marker, GoogleApiWrapper } from 'google-maps-react';
export class WaterMapView extends Component {
render () {
console.log(' I am here ');
return (
<Map
google={this.props.google}
style={styles.mapStyle}
initialCenter={{
lat: 40.854885,
lng: -88.081807
}}
zoom={15}
/>
)
}
}
const styles = {
mapStyle: {
height: '100%',
width: '100%'
}
}
export default GoogleApiWrapper({
apiKey: 'AIxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
})(WaterMapView)
This component is embedded in MainDashboard.js as follows :
import React, { Component } from 'react';
import windowSize from 'react-window-size';
import WaterMapView from './WaterMapView';
class MainDashboard extends Component {
render () {
const height = this.props.windowHeight;
const {
containerStyle,
headerStyle,
navigationStyle,
mainPageStyle,
eventPageStyle,
mapPageStyle,
mapDisplayStyle,
mapPropertiesStyle
} = styles;
return (
<div style={{ ...containerStyle, height }} >
<div style={headerStyle} >
</div>
<div style={navigationStyle} >
</div>
<div style={mainPageStyle} >
<div style={eventPageStyle} >
</div>
<div style={mapPageStyle} >
<div style={mapDisplayStyle} >
<WaterMapView />
</div>
<div style={mapPropertiesStyle} >
</div>
</div>
</div>
</div>
);
};
};
My App.js component is :
import React from 'react';
import MainDashboard from './MainDashboard';
const App = () => {
return (
<div>
<MainDashboard />
</div>
)
};
export default App
And index.js is :
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './Components/App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
I am using React version 16.0.0 and google-maps-react version 1.1.0
I get an error accompanied by a dump of code. The error is :
TypeError: Cannot read property 'array' of undefined
I am not including the dump in this post. I can add that if required.
The problem seems very basic as the I do not even see the console.log statement 'I am here' in WaterMapView.js component.
Let me know what am I missing.
<div style={mapDisplayStyle} >
WaterMapView
</div>
Should be
<div style={mapDisplayStyle} >
<WaterMapView />
</div>
Otherwise react just interprets WaterMapView as a string and displays the string. When you want to use/render the component you need to add < > to id.

Resources