So I have just started learning React and its been fun so far, however I'm trying to split my components into sections for cleaner prettier code.
This is my component -
class Papers extends React.Component {
// Constructor
constructor(props) {
super(props);
this.state = {
items: [],
DataisLoaded: false
};
}
// ComponentDidMount is used to execute the code
componentDidMount() {
const randomFilmId = Math.floor(Math.random() * 10) + 1
const url ="#"
fetch(url)
.then((res) => res.json())
.then((json) => {
this.setState({
items:json,
DataisLoaded: true
});
})
.catch ((err) => {
console.log("something went wrong ", err)
});
}
render() {
const { DataisLoaded, items } = this.state;
if (!DataisLoaded) return <div>
<h1> Pleses wait some time.... </h1> </div> ;
return (
<div className="auth-box">
<div className="auth-card" key="{item.id}">
<div className = "App">
<h1> Fetch data from an api in react </h1> {
items.map((item) => (
<ul key = { item.id } >
<li> User_Name: { item.first_name }, </li>
<li> Full_Name: { item.middle_name }, </li>
<li> User_Email: { item.last_name } </li>
</ul>
))
}
</div>
</div>
</div>
);
}
}
export default Papers;
But if I want to put the following piece oof code in a new class,
<div className="auth-box">
<div className="auth-card" key="{item.id}">
<div className = "App">
<h1> Fetch data from an api in react </h1> {
items.map((item) => (
<ul key = { item.id } >
<li> User_Name: { item.first_name }, </li>
<li> Full_Name: { item.middle_name }, </li>
<li> User_Email: { item.last_name } </li>
</ul>
))
}
</div>
</div>
</div>
How would I pass all the props into the new class? I'm sorry if this a basic beginner question.
Appreciate all the help and support
You can pass down props to child components very easily.
<Auth userDetails={this.state.items} />
And iside the new class component you can access them as
this.props.userDetails
It is pretty simple actully. You just do
class AuthComponent extends React.Component {
render () {
return (
<div className="auth-box">
<div className="auth-card" key="{item.id}">
<div className = "App">
<h1> Fetch data from an api in react </h1>
{
this.props.items.map((item) => (
<ul key = { item.id } >
<li> User_Name: { item.first_name },</li>
<li> Full_Name: { item.middle_name }, </li>
<li> User_Email: { item.last_name } </li>
</ul>
))
}
</div>
</div>
</div>
);
}
}
and in parent do <AuthComponent items={items} />
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.