Meimei Chen
Meimei Chen

Reputation: 35

JavaScript object function in react component class

I got the object function using in react component, the below is my code, I tried to create an object function inside articleActions object, not got the syntax error. The api import is working fine and I get the right data and store in this component state: this.state.articles, this.state.authors.

App.js
import React from "react";
import DataApi from "../DataApi";
import data from "../testData";
import ArticleList from "./ArticleList";

const api = new DataApi(data.data);

class App extends React.Component {
    constructor() {
    super();
     this.state = {
       articles: api.getArticles(),
       authors: api.getAuthors()
      };
    }
    articleActions = {
       lookupAuthor: authorId => this.state.authors[authorId]
    };
    render() {
      return (
       <ArticleList
         articles={this.state.articles}
         articleActions={this.articleActions}
       />
   );
}
}

export default App;

the second file: ArticleList.js

import React from "react";

import Article from "./Article";

 const ArticleList = props => {
      return (
        <div>
          {Object.values(props.articles).map(article => (
             <Article
               key={article.id}
               article={article}
               actions={props.articleActions}
             />
          ))}
        </div>
       );
      };

 export default ArticleList;

the third file: Article.js

import React from "react";

 const Article = props => {
    const { article, actions } = props;
    const author = actions.lookupAuthor(article.authorId);
    return (
      <div>
      <div>{article.title}</div>
      <div>{article.date}</div>
      <div>
          <a href={author.website}>
              {author.firstName} {author.lastName}
          </a>
      </div>
      <div>{article.body}</div>
    </div>
   );
 };

 export default Article;

The error message is :

SyntaxError: C:/Users/coral/Documents/react-advanced/lib/components/App.js: 
  Unexpected token (16:17)
  14 |     };
  15 |   }
> 16 |   articleActions = {
     |                  ^
  17 |     lookupAuthor: authorId => this.state.authors[authorId]
  18 |   };

the lookupAuthor should be a function with parameter:authorId, and get the return value of the author object. this.state.authors is the array of author objects. Each object with the authorId as the key, and author object as the value. I am not sure what is the error here when declare the function inside the js object. Hope someone can help

Upvotes: 0

Views: 5441

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

That should be method:

articleActions = () => ({
  lookupAuthor: authorId => this.state.authors[authorId]
});

Upvotes: 2

Related Questions