Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scoping in React + React Router

I am having a scoping issue. I can console.log this.props.routeParams.key from within the constructor. But when outside of the constructor, within the filterList function, I get the error "Uncaught TypeError: Cannot read property 'props' of undefined". What's my scoping issue? Why can it read the this from within the constructor but not from within the filterList function?

I am using React Router + Flux + React.

import AltContainer from 'alt-container';
import React from 'react';
import { Link } from 'react-router';
import Blogger from './Blogger'
import List from './List'
const rootURL = 'https://incandescent-fire-6143.firebaseio.com/';

import BlogStore from '../stores/BlogStore'
import BlogActions from '../actions/BlogActions';


export default class BlogShow extends React.Component {
  constructor(props) {
    super(props);
    {console.log(this.props.routeParams.key)}
}


filterList(key) {
  if (this.props.routeParams.key===key){
    return Blogstore.state.blog
  }
}

  render() {
             {Object.keys(BlogStore.state.blog).map(this.filterList)}
  }
}
like image 239
CodeYogi Avatar asked May 01 '16 14:05

CodeYogi


People also ask

What is routes in react router?

Route: Route is the conditionally shown component that renders some UI when its path matches the current URL. Link: Link component is used to create links to different routes and implement navigation around the application. It works like HTML anchor tag.

What is scope in react?

React Scope leverages React Developer Tools to retrieve information about the client's application. We then use this data to render a DOM tree visualization. The user simply hovers over the nodes within the tree to see each component's name, state, and props.

What is the difference between HashRouter and BrowserRouter in react?

Both BrowserRouter and HashRouter components were introduced in React Router ver. 4 as subclasses of Router class. Simply, BrowserRouter syncs the UI with the current URL in your browser, This is done by the means of HTML-5 History API. On the other hand, HashRouter uses the Hash part of your URL to sync.

How do you fix react must be in scope when using JSX?

To Solve 'React' must be in scope when using JSX react/react-in-jsx-scope Error Maybe you are importing the wrong spelled React that's why this error occurs. Just Import React like this: import React, { Component } from 'react'; And Now, Your error must be solved. Thanks.


1 Answers

that is happening because your filterList function is not bound to your component

Bind it in your constructor

constructor(props) {
    super(props);
    this.filterList = this.filterList.bind(this);
}

You read about it here

like image 115
QoP Avatar answered Oct 11 '22 03:10

QoP