Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

render array of object into a <li> in react.js

I read an article and the author critic below code, I wonder what's wrong with it. I was starting to learn React, too bad the author did not point out what's his problem with the code below. I tested the code below, it's running fine.

import React from 'react';
import './App.css';

const TodoItems = React.createClass({
  getInitialState() {
    return {
      items : [
        {id:1,name:"Gym"},
        {id:2,name:"Jump"},
        {id:3,name:"Racing"}
      ] 
    }
  },
  renderItem(){
    return(
      <ul>
      {this.state.items.map((item,i) => 
        <li key={i}>item.name</li>
      )}
      </ul>
    ) 
  },
  render(){
    return (
      <renderItem />
    )
  }

})

ReactDOM.render(<TodoItems />,document.getElementById('app'));
like image 717
Thian Kian Phin Avatar asked May 15 '26 03:05

Thian Kian Phin


1 Answers

The method renderItem should be outside as a functional or stateless component:

const RenderItem = (props) => {
    return(
      <ul>
      {props.items.map((item,i) => 
        <li key={i}>item.name</li>
      )}
      </ul>
    ) 
  };

The render method of the parent component should be:

render(){
    return (
      <RenderItem items={this.state.items} />
    )
  }

This is the standard way that we write React components. It causes maintainability issues when you write it that way.

like image 157
vijayst Avatar answered May 16 '26 15:05

vijayst