简体   繁体   中英

Split up json-data fetched with axios in to a clickable list-item that redirects to page

Noob to react and everything that has to do with web-developing pretty much. I'm trying to create a list in a Navbar with buttons that redirects the user to a new page. I'm fetching sports from a JSON-file and I have the code below to reduce/get rid of all the duplicates. My question now is what the best practice to create a list in, eg a navbar with a button that gets one sport each. I have a total of 5 sports in {postList} and I have no Idea how to split them up from the SportList.js-file. My goal is attaching them to an icon somehow (like a football for football), that sends the user to the football-page (where you can see all the football games). Not really sure where to start.

I hope my question is not to confusing, english is not my first language. Any help and/or hints is awesome. Ask me if it doesn't make sense and I will try to rephrase the question. Thank you!

import React, { Component } from 'react'
import axios from 'axios'

class SportList extends Component {
  state = {
    posts: []
  }
  componentDidMount(){
    axios.get('https://data.json')
      .then(res => {
        this.setState({
          posts: res.data
        });
      })
  }
  render() {
    const { posts } = this.state;
    const uniquePosts = Object.values(posts.reduce((r,c) => { 
      r[c.sport] = c 
      return r
    }, {}))
    const postList = uniquePosts.length ? (
        uniquePosts.map(post => {
          return (
            <div key={post.id}>
              <div>
                {post.sport}
              </div>
            </div>
          )
        })
      ) : (<div>No Sports Available</div>)
    return (<div>{postList}</div>);
  }
}

export default SportList

You need to install two packages react-router-dom and lodash.

After the api call , once you get the data. Get the sport names, create each components for the sport. Pass the data to each component.

Note : Since i don't have the api, i have used to get it from a file, so you can call the api in the componentDidMount and set the data to state.

Also use the Route component inorder to render the data based on each component load.

I hope this will solve the issue. Please let me know if any issue occurred.

 // App.js import React, { Component } from 'react'; import './App.css'; import Aux from './Aux'; import { BrowserRouter, Switch, Route } from 'react-router-dom'; import Data from './Data'; import FootBall from './FootBall'; import EachNavLink from './EachNavLink'; import {groupBy} from 'lodash' class App extends Component { state = { apiData: Data } getData = (sport) => { let data = groupBy(this.state.apiData, "sport") return data[sport]; } renderTabs = () => { const { apiData } = this.state const sports = Array.from(new Set(apiData.map(o => o.sport))) const tabs = sports.map((item, index) => { return ( <EachNavLink key={index} href={`/${item}`} name={item} /> ) }) return tabs } render() { const { apiData } = this.state return ( <BrowserRouter> <Aux> <Aux> { apiData.length > 0 ? this.renderTabs() : <p>Data is Loading... Please wait.</p> } </Aux> <div className="content"> <Switch> <Route path="/FOOTBALL" render={(routeProps) => (<FootBall {...routeProps} data={apiData.length > 0 ? this.getData("FOOTBALL") : []} />)} /> </Switch> </div> </Aux> </BrowserRouter> ); } } export default App; // Data.js const data = [ { "awayName": "Panthrakikos Komotini", "createdAt": "2015-12-18T12:30:39.228Z", "group": "Greek Cup", "homeName": "Chania FC", "id": 1002916450, "name": "Chania FC - Panthrakikos Komotini", "objectId": "1UaQjc7lIb", "sport": "FOOTBALL", "country": "ENGLAND", "state": "STARTED" }, { "awayName": "PAOK Thessaloniki", "createdAt": "2015-12-18T12:30:39.234Z", "group": "Greek Cup", "homeName": "Olympiakos Volos", "id": 1002916451, "name": "Olympiakos Volos - PAOK Thessaloniki", "objectId": "UPJ240T2Qj", "sport": "FOOTBALL", "country": "FRANCE", "state": "STARTED" }, { "awayName": "Ukraine U18", "createdAt": "2015-12-18T12:30:39.244Z", "group": "Under 18", "homeName": "Israel U18", "id": 1003022920, "name": "Israel U18 - Ukraine U18", "objectId": "fZZUhitsVt", "sport": "FOOTBALL", "country": "SWEDEN", "state": "STARTED" }, { "awayName": "Stade Gabesien", "createdAt": "2015-12-18T12:30:39.249Z", "group": "Ligue 1", "homeName": "CA Bizertin", "id": 1003015194, "name": "CA Bizertin - Stade Gabesien", "objectId": "Bf52z7GIut", "sport": "FOOTBALL", "country": "SWEDEN", "state": "STARTED" }, { "awayName": "AS de la Marsa", "createdAt": "2015-12-18T12:30:39.255Z", "group": "Ligue 1", "homeName": "Club Africain", "id": 1003015197, "name": "Club Africain - AS de la Marsa", "objectId": "sFjPkmljKv", "sport": "FOOTBALL", "country": "ENGLAND", "state": "STARTED" }, { "awayName": "Kastamonuspor", "createdAt": "2015-12-18T12:30:39.261Z", "group": "T\ürkyie Kupasi", "homeName": "Kar\ş\ıyaka", "id": 1003016331, "name": "Kar\ş\ıyaka - Kastamonuspor", "objectId": "cRqV2RTmsu", "sport": "FOOTBALL", "country": "FRANCE", "state": "FINISHED" }, { "awayName": "Allen, Gareth", "createdAt": "2015-12-18T12:30:39.266Z", "group": "German Masters Qualifiers", "homeName": "Ding Junhui", "id": 1003018193, "name": "Ding Junhui - Allen, Gareth", "objectId": "nPuz011p0W", "sport": "SNOOKER", "country": "SWEDEN", "state": "NOT_STARTED" }, { "awayName": "Lines, Peter", "createdAt": "2015-12-18T12:30:39.272Z", "group": "German Masters Qualifiers", "homeName": "Trump, Judd", "id": 1003018186, "name": "Trump, Judd - Lines, Peter", "objectId": "CSJn3kZhdx", "sport": "SNOOKER", "country": "ENGLAND", "state": "NOT_STARTED" }, { "awayName": "SKIF-Krasnodar", "createdAt": "2015-12-18T12:30:39.278Z", "group": "Cup", "homeName": "Dinamo Astrakhan", "id": 1003027200, "name": "Dinamo Astrakhan - SKIF-Krasnodar", "objectId": "enCbqOuRLr", "sport": "HANDBALL", "country": "SWEDEN", "state": "STARTED" }, { "awayName": "THK Tver", "createdAt": "2015-12-18T12:30:39.283Z", "group": "VHL", "homeName": "Zauralie Kurgan", "id": 1002988754, "name": "Zauralie Kurgan - THK Tver", "objectId": "7HWfuCIMlp", "sport": "ICE_HOCKEY", "country": "ENGLAND", "state": "STARTED" }, { "awayName": "Doumbia, SReboul, F", "createdAt": "2015-12-18T12:30:39.289Z", "group": "Nigeria", "homeName": "Harris, LG MMaamoun, KM", "id": 1003026313, "name": "Harris, LG MMaamoun, KM - Doumbia, SReboul, F", "objectId": "JxrZyQKTrw", "sport": "TENNIS", "country": "FRANCE", "state": "STARTED" }, { "awayName": "Halebian, Alexios", "createdAt": "2015-12-18T12:30:39.294Z", "group": "Dominican Republic", "homeName": "Bangoura, Sekou", "id": 1003026667, "name": "Bangoura, Sekou - Halebian, Alexios", "objectId": "tALMRNqAxD", "sport": "TENNIS", "country": "SWEDEN", "state": "NOT_STARTED" }, { "awayName": "Roberts, Justin", "createdAt": "2015-12-18T12:30:39.300Z", "group": "Dominican Republic", "homeName": "Pla Malfeito, Jaume", "id": 1003026666, "name": "Pla Malfeito, Jaume - Roberts, Justin", "objectId": "KGA9nqYAJl", "sport": "TENNIS", "country": "ENGLAND", "state": "FINISHED" }, { "awayName": "Mridha, J", "createdAt": "2015-12-18T12:30:39.306Z", "group": "Qatar", "homeName": "Clayton, Scott", "id": 1003026476, "name": "Clayton, Scott - Mridha, J", "objectId": "utc63de1Fl", "sport": "TENNIS", "country": "FRANCE", "state": "STARTED" }, { "awayName": "Kania, PKerkhove, L", "createdAt": "2015-12-18T12:30:39.311Z", "group": "Ankara", "homeName": "Buyukakcay, CKrunic, A", "id": 1003026234, "name": "Buyukakcay, CKrunic, A - Kania, PKerkhove, L", "objectId": "mTVUIuYdbF", "sport": "TENNIS", "country": "SWEDEN", "state": "NOT_STARTED" }, { "awayName": "Chernetsova, DPerper, A", "createdAt": "2015-12-18T12:30:39.317Z", "group": "El Kantaoui", "homeName": "Baskova, DPodlinska, M", "id": 1003026673, "name": "Baskova, DPodlinska, M - Chernetsova, DPerper, A", "objectId": "heL53W56d2", "sport": "TENNIS", "country": "FRANCE", "state": "STARTED" }, { "awayName": "Njoze, M", "createdAt": "2015-12-18T12:30:39.322Z", "group": "El Kantaoui", "homeName": "Stoilkovska, M", "id": 1003026214, "name": "Stoilkovska, M - Njoze, M", "objectId": "gldlV9xhi2", "sport": "TENNIS", "country": "SWEDEN", "state": "STARTED" }, { "awayName": "Haas, Barbara", "createdAt": "2015-12-18T12:30:39.328Z", "group": "Navi Mumbai", "homeName": "Jia-Jing Lu", "id": 1003026299, "name": "Jia-Jing Lu - Haas, Barbara", "objectId": "V6Qsm2Wlms", "sport": "TENNIS", "country": "ENGLAND", "state": "FINISHED" } ] export default data // Aux.js const aux = ({children}) => children export default aux // EachNavLink.js import React from 'react'; import {NavLink} from 'react-router-dom'; const eachNavLink = ({href,name}) => { return( <div> <NavLink to={href} activeClassName="active" > {name} </NavLink> </div> ) } export default eachNavLink // FootBall.js import React from 'react'; const football = (props) => { const { data } = props return ( data.map((item, index) => { return ( <div key={index}> <ul> <li>Away Name: {item.awayName}</li> <li>Country: {item.country}</li> <li>Group: {item.group}</li> </ul> </div> ) }) ) } export default football 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM