简体   繁体   中英

How to create Link dynamically in reactjs?

We have dynamically get menu navigation in through the API. how to pass menu navigation dynamically.

API Response.

http://jsoneditoronline.org/?id=7d4f2ddbabb7eba80dde69867989f0f3

Here code.

componentDidMount() {
    axios.get('http://****.com/****/api/products/navigation_menu?app_id=*******8')
      .then(res => {
       const ajaxresponse = res.data.result_set;
       console.log();
      ajaxresponse.forEach(function(loaddata) {
         console.log(loaddata.menu_custom_title);

    });

      });
  }
   render() {
      return (
         <div>
            <ul>
               <li><Link to="/home" >{this.state.home}</Link></li>
               <li><Link to="/about" >{this.state.about}</Link></li>
               <li><Link to="/contact" >{this.state.contact}</Link></li>
            </ul>

           {this.props.children}
         </div>
      )
   }
}

export default App;

Store the res.data.result_set in state variable once the data is fetched from server,

this.setState({data: res.data.result_set});

Then Use this function to dynamically generate the menuitems:

_createMenuItems(){
    return this.state.data.map((loaddata, index)=>
        <li key={index}><Link to={/*put the link here*/} >{loaddata.menu_custom_title}</Link></li>
    );
}

render() {
    return (
        <div>
            <ul>
               <li><Link to="/home" >{this.state.home}</Link></li>
               <li><Link to="/about" >{this.state.about}</Link></li>
               <li><Link to="/contact" >{this.state.contact}</Link></li>
               {this._createMenuItems()}
            </ul>
            {this.props.children}
        </div>
    )
}

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