I am trying to fetch data from GitHub user API and store the JSON in an array, and then and then loop through the array and create Card components dynamically on submission of form, but the Card components doesn't render even though the array is updated with the newly added user.
I have added relevant code files and image of React component tree on dev console before and after valid form submission. Thanks.
App.js
import React from "react"; import Form from "./Form"; import Cardlist from "./Cardlist"; import ProfileData from "../JSON"; export default class App extends React.Component { testData = ProfileData(); state = { profiles: this.testData, }; addNewProfile = (profile) => { this.setState({ profiles: [...this.state.profiles, profile], }); }; render() { return ( <div> <h4>GITHUB PROFILE CARDS</h4> <Form onSubmit={this.addNewProfile} /> <Cardlist profiles={this.state.profiles} /> </div> ); } }
Form.js
import React from "react"; export default class Form extends React.Component { state = { userName: "" }; handleSubmit = (event) => ( event.preventDefault(), fetch(`https://api.github.com/users/${this.state.userName}`) .then((response) => { return response.json(); }) .then((data) => { this.props.onSubmit(data); }) ); render() { return ( <div> <form onSubmit={this.handleSubmit}> <input type="text" placeholder="username" value={this.state.userName} onChange={(event) => this.setState({ userName: event.target.value }) } /> <button>Add Card</button> </form> </div> ); } }
Cardlist.js
import React from "react"; import Card from "./Card"; export default class Cardlist extends React.Component { profile = this.props.profiles.map((element) => ( <Card key={element.id} {...element} /> )); render() { return (<div>{this.profile}</div>); } }
Card.js
import React from "react"; export default class Card extends React.Component { render() { return( <div style = > <img src = {this.props.avatar_url} style = /> <div> <h6>{this.props.name}</h6> <h6>{this.props.name}</h6> </div> </div> ); } }
component tree before array before
component tree after array after
https://stackoverflow.com/questions/66848272/why-newly-dynamically-added-card-components-doesnt-re-render-on-form-submit March 29, 2021 at 11:02AM
没有评论:
发表评论