< Back to Coding

Using JSON data to populate a component

Continuing from our last post, this is now our component code:

import React from 'react';

import { NavLink } from 'react-router-dom';

import "./YearsUpdates.scss";

class YearsUpdates extends React.Component {

    constructor(props) {
        super(props);
        this.state = {

        }

    }

    getLink(type) {
        switch (type) {
            case 'website':
                return <NavLink to="/websites">Websites</NavLink>
            default:
                return 'error'
        }

    };


    render() {
        console.log(this.props.updates);
        var tableRows = this.props.data.updates.map((update, i) =>
            <tr key={i}><td>{this.props.data.year}</td>
                <td>Added {update.name} to {this.getLink(update.type)}</td>
            </tr>
        );

        return (
            <table className="updates">
                <tbody>
                    {tableRows}

                </tbody>
            </table>
        )
    }
}

export default YearsUpdates;

We can access the JSON using this.props.data. We can then loop through the updates using “map” and add a new table row for each update and store it all up in the variable tableRows. We also use a function getLink() that renders different things depending on the update’s type.

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *