Answer the question
In order to leave comments, you need to log in
How to bind form input to method in React?
How to display information about posts (repositories) of a specific GitHub user ${person}, whose name we enter in the field in the form component (Info.js)?
In other words:
how to bind the fetchPosts method so that it is called when the form button is clicked (onSubmit)? For example, in the Info component, this method will already be called ReposMethod.
app.js:
import React, { useState, useEffect } from 'react';
import Posts from './components/Posts';
import Pagination from './components/Pagination';
import Info from './components/Info'
import axios from 'axios';
import './App.css';
const App = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(10);
useEffect(() => {
const fetchPosts = async (event) => {
setLoading(true);
const res = await axios.get(`https://api.github.com/users/bibeva/repos`);
setPosts(res.data);
setLoading(false);
};
fetchPosts();
}, []);
// Get current posts
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);
// Change page
const paginate = pageNumber => setCurrentPage(pageNumber);
return (
<div className='container mt-5'>
<h1 className='text-primary mb-3'>My Blog</h1>
<Info />
<Posts posts={currentPosts} loading={loading} />
<Pagination
postsPerPage={postsPerPage}
totalPosts={posts.length}
paginate={paginate}
/>
</div>
);
};
export default App;
import React from 'react';
class Info extends React.Component{
render() {
return (
<div>
<form onSubmit={this.props.reposMethod}>
<input type="text" name="person"/>
<button>Получить сведения</button>
</form>
</div>
)
}
}
export default Info;
Answer the question
In order to leave comments, you need to log in
Remove the effect.
The function to get the list of repositories - let it get the username as a parameter:
async function fetchRepos(username) {
let result = [];
try {
result = (await axios.get(`https://api.github.com/users/${username}/repos`)).data;
} catch(e) {
console.error(e);
}
setRepos(result);
}
<Search onSearch={fetchRepos} />
function Search({ onSearch }) {
const [ searchValue, setSearchValue ] = useState('');
function onSubmit(e) {
e.preventDefault();
onSearch(searchValue);
}
return (
<form onSubmit={onSubmit}>
<input
type="text"
value={searchValue}
onChange={e => setSearchValue(e.target.value)}
/>
<button>Найти</button>
</form>
)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question