2

I am new to Javascript and React. This code is showing errors and Can this code be further improved. Any suggestions? Please be abstract I want to implement it.

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';

export class Projects extends Component {
    static propTypes = {
        projects: PropTypes.array.isRequired
    };

    render() {
        const { projects } = this.props;

        return (
            <div className="projects container">
                <Link to="/projects/new" className="btn">
                    New project
                </Link>

                {projects.map(project => (
                    <div>
                        <span className="language origin">
                            {project.languageFrom}
                        </span>
                        <span className="language destination">
                            {project.languageTo}
                        </span>
                    </div>
                )}
            </div>
        );
    }
};
baj9032
  • 2,414
  • 3
  • 22
  • 40
akash
  • 1,437
  • 2
  • 9
  • 12

2 Answers2

0

You need to do conditional check before doing .map. Also never forget to add unique key to top element when render them in loop

      {Array.isArray(projects) && projects.map((project,index) => (
  <div key={"Key-"+index}>//or if each project contains unique I’d then add id as key instead of index like key={project.id}
    <span className="language origin">
      {project.languageFrom}
    </span>
    <span className="language destination">
      {project.languageTo} 
    </span>
  </div>
)}
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
0

I think Something is problematic with syntax.Try this

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';

export class Projects extends Component {
    static propTypes = {
        projects: PropTypes.array.isRequired
    };

    render() {
        const { projects } = this.props;

        return (
            <div className="projects container">
                <Link to="/projects/new" className="btn">
                    New project
                </Link>

                {projects.map(project => (
                    <div>
                        <span className="language origin">
                            {project.languageFrom}
                        </span>
                        <span className="language destination">
                            {project.languageTo}
                        </span>
                    </div>
                ))}
            </div>
        );
    }
}
baj9032
  • 2,414
  • 3
  • 22
  • 40