Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In React, how can I use one of my props to map my JSON?

I want to use props.type to edit the mapping of the JSON in the H5, similar to what I did with the className, but I can’t find the correct way to do it.

import text from "../../text/global.json";

function Card(props) {
  let col = props.col;
  let type = props.type;

  return (
    <>
      <Col className={`bg-white p-4 card-b col-md-${col}`}>
        <h5>{text.homepage.servicios.cards.${type}.title}</h5>
        <p>Litigio, Microfinanzas, Responsabilidad social y sustentabilidad.</p>
        <Button>Ver más</Button>
      </Col>
    </>
  );
}

I tried the same way I use for the className, hoping to use the prop as a string but it didn’t worked.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It looks like you’re trying to use dynamic property (type) to access a specific property within your JSON file. The correct syntax for dynamic property access in JavaScript is using square brackets []. Here’s how you can modify your code:

import text from "../../text/global.json";

function Card(props) {
  let col = props.col;
  let type = props.type;

  return (
    <>
      <Col className={`bg-white p-4 card-b col-md-${col}`}>
        <h5>{text.homepage.servicios.cards[type].title}</h5>
        <p>Litigio, Microfinanzas, Responsabilidad social y sustentabilidad.</p>
        <Button>Ver más</Button>
      </Col>
    </>
  );
}

In this modification, text.homepage.servicios.cards[type].title will dynamically access the property based on the value of type. Make sure that the property type exists in your JSON file and that it contains the necessary sub-properties like title. If type is not present or doesn’t match any property in the JSON, it might result in an error, so you may want to add proper validation for that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading