IvanS95
IvanS95

Reputation: 5732

How to generate components with each value from a JSON file in React?

I'm trying to implement something similar to Angular's ngFor directive in ReactJS. I've seen examples with map but I'm still not sure how to implement it correctly.

To provide more context; I need to build a grid with each square having the value of a letter read from a JSON file; I've built a component for each square, so it looks like this

class Square extends React.Component {
    render() {

        return (
            <div className="square">
                {this.props.letters.board.map((letter) => <span>{letter}</span>)}
            </div>
        );
    }
}

This letters prop would be the JSON file I need to read, this is mostly what I'm not sure if I'm doing correctly:

function App() {
  let letters = require('./test-board-2.json');
  console.log(letters);
  return (
    <div className="App">
      <div className="container">
        <div className="letters">
          <Square letters={letters}/>
        </div>
        <div className="controls">
          <Clear />
        </div>
      </div>
    </div>
  );
}

Am I actually reading the JSON file in a adequate manner? I actually get the console.log just fine but what I get rendered is just one square with all the values of the json file, instead of one square for each value.

This is what the json file looks like:

{
    "board": [
        "L",
        "I",
        "S",
        "T",
        "O",
        "F",
        "A",
        "T",
        "S",
        "T",
        "R",
        "S",
        "O",
        "R",
        "A",
        "Y"
    ]
}

Any help is appreciated, I mostly have an Angular background, and I'm just starting learning React.

Upvotes: 2

Views: 770

Answers (2)

jcrowson
jcrowson

Reputation: 4290

The reason why you're only seeing one Square is because you are passing in the whole JSON object into your <Square /> component and then looping through the array inside of Square.

What you should be doing is looping through the array outside of the Square component, and rendering a Square component for each element of the array, like so:

function App() {
  let letters = require('./test-board-2.json');
  console.log(letters);
  return (
    <div className="App">
      <div className="container">
        <div className="letters">
          {letters.board.map(letter => <Square letter={letter}/>)}
        </div>
        <div className="controls">
          <Clear />
        </div>
      </div>
    </div>
  );
}

Now, you can just use the letter prop inside of your <Square /> component, like so:

function Square() {
  render() {
    return (
      <div className="square">
        <span>{this.props.letter}</span>
      </div>
    );
  }
}

Upvotes: 1

AhmadDeel
AhmadDeel

Reputation: 348

My guess is what you read from your JSON file becomes an object. Try passing it to the square element by

<Square letters={letters.board}/>

Upvotes: 0

Related Questions