Getting an arrow function syntax error in React - reactjs

I have following code which is rendering the React app.
import React from 'react';
import ReactDOM from 'react-dom';
import SearchBar from './components/search_bar';
import YTSearch from 'youtube-api-search';
import VideoList from './components/video_list'
const API_KEY = 'AIzaSyCF7K58Xwpr7m5C0yGy8Bck02iQ0fJ2yuI';
class App extends React.Component {
constructor(props){
super(props);
this.state = {videos: []};
this.YTSearch = this.YTSearch.bind(this);
}
YTSearch({key: API_KEY, term: BMW}, (videos => {
this.setState({ videos });
});
);
render() {
return (
<div>
<SearchBar />
<VideoList videos={ this.state.videos }/>
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'));
Also I think I have some syntax problem with using the setState function.

Class body is for defining functions and variables but you are calling the function YTSearch inside class body, which is giving syntax error. If you want to call the function then either call it inside constructor or inside any other function like componentDidMount etc
constructor(props){
super(props);
this.state = {videos: []};
}
componentDidMount(){
// Call it here inside componentDidMount or any other function
YTSearch({key: API_KEY, term: BMW}, (videos => {
this.setState({ videos });
}));
}

Your destructured setState is fine, you have a bracket (open which needs to be closed or either way you can remove it as there is only one argument in your arrow function.

Your specific issue isn't made clear in your question but from looking at your code I assume your YTSearch is never firing and therefore your state never gets set with a list of videos.
If you are trying to create a method to pass to the search bar that triggers a search perhaps try something like this. I hope this helps!
import React from 'react';
import ReactDOM from 'react-dom';
import SearchBar from './components/search_bar';
import YTSearch from 'youtube-api-search';
import VideoList from './components/video_list';
const API_KEY = 'AIzaSyCF7K58Xwpr7m5C0yGy8Bck02iQ0fJ2yuI';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { videos: [] };
this.search = this.search.bind(this);
}
search(phrase) {
YTSearch({ key: API_KEY, term: phrase }, videos => {
this.setState({ videos });
});
}
render() {
return (
<div>
<SearchBar onSearch={this.search}/>
<VideoList videos={this.state.videos} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'));

Related

ReactJS Question Component function scope and sharing functions

I have a question about ReactJS and components, specifically about how functions interact within the component system.
In this example:
// Index.js
import React from ‘/reactʼ;
import ReactDOM from ‘/react-domʼ;
import App from ‘./App.jsʼ;
ReactDOM.render(<App />, document.getElementById(‘rootʼ));
// App.js
import React from ‘/reactʼ;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {someProp = ‘ʼ};
};
functionA = (e) => { console.log(e);
};
Render() {
return <div><ComponentA /></div>
};
};
export default App;
// ComponentA.js
import React from ‘/reactʼ;
import App from ‘./../App.jsʼ;
class ComponentA extends React.Component {
constructor(props) {
super(props);
this.state = {someProp = ‘ʼ};
};
functionB = App.functionA
Render() {
return(
<div>
<input onSubmit={this.functionB} />
</div>
);
};
};
export default ComponentA;
ComponentA imports App.js and attempts to assign App.functionA to functionB and then call it in the JSX. This results in a failure basically saying that the function is not defined.
I know this is NOT the way to function share (I have learned about passing functions through props etc).
I simply just want to know WHY this does not work, to help me better understand the mechanics of React, and Javascript in general.
Thank you,
Curtis
To call a function from another React component, you can write static methods in ES6 notation. If you are using ES7, then you can also write static properties.
You can write statics inside ES6+ classes this way:
class Component extends React.Component {
static propTypes = {
...
}
static someMethod(){
}
}
Working Demo about static function
My noob brain finally figured it out lol... I think.
Basically because an instance of the class [the App component] was not initialized within the scope of ComponentA, the App function is not accessible.
This made it work (DISCLAIMER: I DO NOT PLAN ON DOING THIS, I KNOW ITS TERRIBLE CODE)
// ComponentA.js
import React from ‘/reactʼ;
import App from ‘./../App.jsʼ;
class ComponentA extends React.Component {
constructor(props) {
super(props);
this.state = {someProp = ‘ʼ};
this.appInstance = new App();
}
functionB = (e) => {
this.appInstance.functionA(e);
}
Render() {
return(
<div>
<input onSubmit={this.functionB} />
</div>
);
}
};
export default ComponentA;

The constructor and render function is called twice

I have a very simple component, in that I log the information to check the Component Lifecycle and see that the constructor and render function is called twice every time when I reload the browser. Could anyone please help me to review why?
Here is my code, and the result in the picture.
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
name: 'Viet'
};
console.log('App constructor');
}
componentWillMount() {
console.log('App componentWillMount');
}
componentDidMount() {
console.log('App componentDidMount');
}
changeState = () => {
this.setState({ name: 'Viet is changed' })
}
render() {
console.log('App render');
return (
<div className='App'>
{this.state.name}
{<button onClick={this.changeState.bind(this)} >Click to change state</button>}
</div>
);
}
}
export default App;
In your render method you are not passing the function right due to which component is re-rendered again. You need to bind the function in constructor change the onClick of button as:
constructor(props) {
super(props);
this.state = {
name: 'Viet'
};
console.log('App constructor');
this.changeState = this.changeState.bind(this);
}
<button onClick={this.changeState}>Click to change state</button>
The double rendering is due to React.StrictMode. If you check your src/index.js the App Component is wrapped with React.StrictMode tags.
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
As mentioned in the release notes:
"React.StrictMode is a wrapper to help prepare apps for async rendering"
P.S: There is nothing to worry about re-rendering.

'Items' is not defined error when passing value to another component

I am getting ./src/App.js Line 27: 'Items' is not defined react/jsx-no-undef
while trying to pass state to a another component
import React, { Component } from 'react';
import axios from 'axios'
class App extends Component {
// Added this:
constructor(props) {
super(props);
// Assign state itself, and a default value for items
this.state = {
items: []
};
}
componentWillMount() {
axios.get('https://api.opendota.com/api/proMatches').then(res => {
this.setState({ items: res.data });
});
}
render() {
return (
<div className="app">
<Items items={this.state.items} />
</div></blink></blink>
);
}
}
export default App;
You are not trying to use a component called Items without importing it first:
<Items items={this.state.items} />
Every component that you use must be imported first:
import { Items } from "DIRECTORY"
Errors:- (1) import Items component (2) use componentDidMount() instead of componentWillMount() (3) use ternary operator in JSX this.state.items.length > 0 for displaying items after getting response
import React, { Component } from 'react';
import axios from 'axios';
import Items from './Items';
class App extends Component {
// Added this:
constructor(props) {
super(props);
// Assign state itself, and a default value for items
this.state = {
items: []
};
}
componentDidMount() {
axios.get('https://api.opendota.com/api/proMatches').then(res => {
this.setState({ items: res.data });
});
}
render() {
return (
<div className="app">
{
this.state.items.length > 0 ?
<Items items={this.state.items} /> : null
}
</div></blink></blink>
);
}
}
export default App;
App is top component and Items is child component.To use any child component or pass any kind props or state ,it has to be imported first .
There can be another issue to it since you are using state and if the child component Items is rerendered due to any change ,then state of your APP component will also reset.

How to include the Match object into a ReactJs component class?

I am trying to use my url as a parameter by passing the Match object into my react component class. However it is not working! What am I doing wrong here?
When I create my component as a JavaScript function it all works fine, but when I try to create my component as a JavaScript class it doesn't work.
Perhaps I am doing something wrong? How do I pass the Match object in to my class component and then use that to set my component's state?
My code:
import React, { Component } from 'react';
import axios from 'axios';
import PropTypes from 'prop-types';
class InstructorProfile extends Component {
constructor(props, {match}) {
super(props, {match});
this.state = {
instructors: [],
instructorID : match.params.instructorID
};
}
componentDidMount(){
axios.get(`/instructors`)
.then(response => {
this.setState({
instructors: response.data
});
})
.catch(error => {
console.log('Error fetching and parsing data', error);
});
}
render(){
return (
<div className="instructor-grid">
<div className="instructor-wrapper">
hi
</div>
</div>
);
}
}
export default InstructorProfile;
React-Router's Route component passes the match object to the component it wraps by default, via props. Try replacing your constructor method with the following:
constructor(props) {
super(props);
this.state = {
instructors: [],
instructorID : props.match.params.instructorID
};
}
Hope this helps.
Your constructor only receives the props object, you have to put match in it...
constructor(props) {
super(props);
let match = props.match;//← here
this.state = {
instructors: [],
instructorID : match.params.instructorID
};
}
you then have to pass that match object via props int a parent component :
// in parent component...
render(){
let match = ...;//however you get your match object upper in the hierarchy
return <InstructorProfile match={match} /*and any other thing you need to pass it*/ />;
}
for me this was not wrapping the component:
export default (withRouter(InstructorProfile))
you need to import withRouter:
import { withRouter } from 'react-router';
and then you can access match params via props:
someFunc = () => {
const { match, someOtherFunc } = this.props;
const { params } = match;
someOtherFunc(params.paramName1, params.paramName2);
};
Using match inside a component class
As stated in the react router documentation. Use this.props.match in a component class. Use ({match}) in a regular function.
Use Case:
import React, {Component} from 'react';
import {Link, Route} from 'react-router-dom';
import DogsComponent from "./DogsComponent";
export default class Pets extends Component{
render(){
return (
<div>
<Link to={this.props.match.url+"/dogs"}>Dogs</Link>
<Route path={this.props.match.path+"/dogs"} component={DogsComponent} />
</div>
)
}
}
or using render
<Route path={this.props.match.path+"/dogs"} render={()=>{
<p>You just clicked dog</p>
}} />
It just worked for me after days of research. Hope this helps.
In a functional component match gets passed in as part of props like so:
export default function MyFunc(props) {
//some code for your component here...
}
In a class component it's already passed in; you just need to refer to it like this:
`export default class YourClass extends Component {
render() {
const {match} = this.props;
console.log(match);
///other component code
}
}`

Can't find an internal method in a React container component

I'm trying to get AJAX-retrieved data into a parent React component so it can be fed down to a child component. I'm using the popular pattern for this defined here where a comment list is used as the example:
components/CommentList.js
import React from 'React';
export class CommentList extends React.Component {
constructor(props) {
super(props);
}
render() {
return <ul> {this.props.comments.map(renderComment)} </ul>;
}
renderComment({body, author}) {
return <li>{body}—{author}</li>;
}
}
components/CommentListContainer.js
import React from 'React';
import { CommentList } from './CommentList';
export class CommentListContainer extends React.Component {
constructor() {
super();
this.state = { comments: [] }
}
componentDidMount() {
$.ajax({
url: "http://get/some/api",
dataType: 'json',
success: function(comments) {
this.setState({comments: comments});
}.bind(this)
});
}
render() {
return <CommentList comments={this.state.comments} />;
}
}
index.js: the entry point for webpack
import React from 'react'
import { render } from 'react-dom'
import { CommentListContainer } from './components/CommentListContainer';
window.React = React;
render(
<CommentListContainer />,
document.getElementById('nav__react-target')
)
When doing all this, I get the following error:
Uncaught ReferenceError: renderComment is not defined
I've move the methods around as well as tweaked the importing of dependencies in various spots with no luck. Any ideas?
Thanks in advance.
You don't have unguarded references to sibling methods with ES2015 classes (as you do in Java / C#, etc.) - instead you need to explicitly reference this to get at the methods of the class:
render() {
// I changed map(renderComment) to map(this.renderComment)
return <ul>{this.props.comments.map(this.renderComment)}</ul>;
}

Resources