sahib_hayat
sahib_hayat

Reputation: 11

I loop through the numbers where I'm using a function in Reactjs but here my <br /> tag is not working the result is showing but there is an error

react-dom.development.js:14887 Uncaught Error: Objects are not valid as a React child (found: object with keys {text}). If you meant to render a collection of children, use an array instead

import React from 'react';

const UseReducers = () => {
  const looper = () => {
    let text = '';
    for (var a = 1; a <= 100; a++) {
      <>
        {text += a} <br />
      </>;
    }
    return <> {text} </>;
  };

  return <> {looper()} </>;
};

export default UseReducers;

Upvotes: 1

Views: 37

Answers (1)

thienms98
thienms98

Reputation: 187

To render an array in react, you should use map(). https://legacy.reactjs.org/docs/lists-and-keys.html

And in this case you want to create an array with text + number from (0-100). The solution is create array with the number or (string text + number if you want) then map inside return;

const looper = () => {
    let result = [];
    for(let i=0; i<100; i++) result.push(i);
    return result;    
}
return <>{
    looper().map(item => (
        <p key={item}>{item}</p>
    )}
</>

Upvotes: 1

Related Questions