Untitled

mail@pastecode.io avatar
unknown
javascript
22 days ago
1.7 kB
1
Indexable
Never
.//компонент App
import './App.css';
import { useState, useEffect } from 'react';
import { Users } from './components/Users';
import { UsersContext } from './context/usersContext';


export default function App() {
  const [users, setUsers] = useState([]);
  
  useEffect(() => {
    fetch ('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(json => setUsers(json))
  }, [setUsers])
  
  return(
    <UsersContext.Provider value={{
      users, 
      currentUser: users.length ? users[0] : {}
    }}>  
      <div className='App'>
        <h1>Пример передачи свойств</h1>
        <Users/>
      </div>
    </UsersContext.Provider>  
  );
}

//context
import { createContext } from 'react';

export const UsersContext = createContext({
  users: [],
  currentUser: {}
});

//компонент Users
import { UsersContext } from '../../context/usersContext'
// import { User } from "./components/User";
import { useContext } from "react";
import { CurrentUser } from './components/CurrentUser'

export const Users = () => {
  const users = useContext(UsersContext)

  return(<>
    {
      !users.length && <>Loading...</>
    }
    {
      users.map((user) => <CurrentUser key={user.id} user={user} />)
    }
    
  </>)
}

//компонент CurrentUser
// import { useContext } from 'react';
// import { UsersContext } from '../../context/usersContext';

export const CurrentUser = ({user}) => {
  // const {currentUser}= useContext(UsersContext);
  return (
    <>
      <div>User ID: {user.id}</div>
      <div>User name: {user.name}</div>
      <div>User email: {user.email}</div>
      <br />
    </>
  )
}
Leave a Comment