Home > Mobile >  render a list of items in reactjs using props
render a list of items in reactjs using props

Time:06-26

I have a problem, which is fill in the blanks. you cannot change the default code only add code where comments are mentioned, I have linked the code sandbox too for better understanding.

import ReactDom from 'react-dom'

function ListItem(props) {
  //return a list item
}

function MyList(props){
  const stuff = props.stuff
  const listItems = //write a function to create list
  <ListItem   //props for calling listitem />
  );
  return(
    <ul>
    //display list items
    </ul>
  )
}

const stuff = [
  {id: 1, name: 'hi'},
  {id: 2, name: 'hii'},
  {id: 3, name: 'hiiii'},
  {id: 4, name: 'hiiiiiii'}
]



ReactDom.render(
//give write component name here
,document.getElementById('root'))

https://codesandbox.io/s/crazy-wiles-yzr6ff

CodePudding user response:

Just drill down your stuff into MyList, which exports an <ul></ul>, and use its items to render multiple ListItem which export a <li></li> containing the name.

I think you should educate yourself on the simplest React mechanism, passing props.

Here's an updated and working CodeSandbox.

import ReactDom from "react-dom";

function ListItem(props) {
  const { name } = props;
  return <li>{name}</li>;
}

function MyList(props) {
  const { stuff } = props;
  return (
    <ul>
      {stuff.map(({ id, name }) => (
        <ListItem key={id} name={name} />
      ))}
    </ul>
  );
}

const stuff = [
  { id: 1, name: "hi" },
  { id: 2, name: "hii" },
  { id: 3, name: "hiiii" },
  { id: 4, name: "hiiiiiii" }
];

ReactDom.render(<MyList stuff={stuff} />, document.getElementById("root"));
  • Related