React.js: How to pass props to components? - javascript

I want to make API call reusable and use it's functionality in other components. I am fetching API in Hook/index.js component. Then I want to iterate through data got from API in another component, make it as a parameter and use it in other components.
I've a Flag/index.js component for flag(img) and want to get url of the image as a parameter and use in Flag/index.js component.
Any help will be appreciated.
In Hook/index.js I fetch API
import React, { useState, useEffect } from "react";
import "./hook.scss";
export default function Hook(){
const [data, setData] = useState([]);
const [error, setError] = useState(null);
const [search, setSearch] = useState("");
const fetchData = () => {
fetch("https://restcountries.eu/rest/v2/all")
.then((res) => res.json())
.then((result) => setData(result))
.catch((err) => console.log("error"));
};
useEffect(() => {
const searchResult = data && data.filter((item) => item.name.toLowerCase().includes(search));
setSearch(searchResult);
}, []);
useEffect(() => {
fetchData();
}, []);
return [data, error];
}
In App.js I'm mapping through API data
import React, { useState }from "react";
import Header from "./components/Header";
import SearchBar from "./components/SearchBar";
import Flag from "./components/Flag";
import useCountries from "./Hooks";
import "./App.scss";
export default function App () => {
const [data, error] = useCountries();
return (
<div className="App">
<SearchBar />
<Header />
{data &&
data.map((country) => (
<div className="CountryList" key={country.name}>
<div className="CountryListImg">
<img src={country.flag} alt="" width="80px" /> if change here to flag={country.flag} I see link in browser
</div>
<div className="countryName">{country.name}</div>
<div className="population">{country.population}</div>
<div className="region">{country.region}</div>
<div>
{country.languages.map((language, languageIndex) => (
<div key={languageIndex}>{language.name}</div>
))}
</div>
</div>
))}
<useCountries />
</div>
);
return [data, error]
}
And my Flag/index.js component, of course doesn't work
import React from "react";
import "./flag.scss";
export default function Flag({flag}) {
return (
<div className="">
<img src={flag} alt="" width="80px" />
</div>
);
};
How to make work search bar. For now it says undefined in console
import React, {useState} from "react";
import "./SearchBar.scss";
export default function Searchbar({data}) {
const [search, setSearch] = useState("");
function handleChange(e) {
setSearch(e.target.value);
}
console.log(data)
return (
<div className="SearchBar">
<input
className="input"
type="text"
placeholder="search country ..."
value={data}
onChange={handleChange}
/>
{data && data.filter((item) => item.name.toLowerCase().includes(search))}
</div>
);
};

You need to use Flag component inside App component
import React, { useState }from "react";
import Header from "./components/Header";
import SearchBar from "./components/SearchBar";
import Flag from "./components/Flag";
import useCountries from "./Hooks";
import "./App.scss";
export default () => {
const [data, error] = useCountries();
return (
<div className="App">
<SearchBar />
<Header />
{data &&
data.map((country) => (
<div className="CountryList" key={country.name}>
<div className="CountryListImg">
<Flag flag={country.flag}/>
</div>
<div className="countryName">{country.name}</div>
<div className="population">{country.population}</div>
<div className="region">{country.region}</div>
<div>
{country.languages.map((language, languageIndex) => (
<div key={languageIndex}>{language.name}</div>
))}
</div>
</div>
))}
<useCountries />
</div>
);
return [data, error]
}

1
I am not completely sure if this answers the question, but to add the abstracted Flag class in you simply need to change this:
<img src={country.flag} alt="" width="80px" />
To this:
<Flag flag={country.flag} />

Just use <Flag flag={country.flag} />
See online: https://stackblitz.com/edit/stackoverflow-63831710?file=src/App.js

Related

Same code in terms of localStorage worked in React 17, but doesn't work in React 18 [duplicate]

I am creating a react app which is using local storage. I am saving and array of objects to local storage.
when I try to save to local storage the data is saving.
and then when I refresh the page the saved data is becoming empty object,
like this [].
if any one knows why its happening please help me
import React, {useEffect, useState} from 'react';
import Addcontact from './Addcontact';
import './App.css';
import Contactlist from './Contactlist';
import { Header } from './Header';
function App() {
const keyy ="contactlist"
const [contacts, setcontacts] = useState([])
const contactshandler = (contact)=> {
console.log(contact)
setcontacts([...contacts, contact])
}
useEffect(() => {
const getdata = JSON.parse(localStorage.getItem(keyy))
getdata && setcontacts(getdata)
}, [])
useEffect(() => {
localStorage.setItem(keyy, JSON.stringify(contacts));
}, [contacts])
return (
<div className="ui container">
<Header />
<Addcontact contacts={contacts} contactshandler={contactshandler} />
<Contactlist contacts={contacts} />
</div>
);
}
app component
import React, { useState } from 'react'
function Addcontact({contacts, setcontacts, contactshandler}) {
const [user, setuser] = useState({username:'', email:''})
const addvalue = (e) => {
e.preventDefault();
console.log(user)
contactshandler(user)
setuser({username:'', email:''})
}
return (
<div>
<div className='ui main'>
<h2> Add Contact</h2>
<form className='ui form' onSubmit={addvalue}>
<div className=''>
<label>name</label>
<input name="name" placeholder='name' value={user.username} onChange={(e) => setuser({...user, username : e.target.value })} />
</div>
<div className='feild'>
<label>email</label>
<input email='email' placeholder='email' value={user.email} onChange={(e) => setuser({...user, email: e.target.value})} />
</div>
<button>add</button>
</form>
</div>
</div>
)
}
export default Addcontact
export default App;
add component
this is the value showing when saving after refresh this value becomes empty object
enter image description here
console
enter image description here
You don't need useEffect to read the data. You can initially read it.
const [contacts, setcontacts] = useState(JSON.parse(localStorage.getItem(keyy)) ?? [])
and remove
useEffect(() => {
const getdata = JSON.parse(localStorage.getItem(keyy))
getdata && setcontacts(getdata)
}, [])

Update child component while using filter on parent component in React

I have seen this asked before but I can't seem to be able to wrap my head around it with my situation.
I am using a search bar to filter the data down and it works but the image will not update. The URL passing to the child works fine but it's just not changing its state. I just don't really understand how to implement it.
PokemonList.jsx
import axios from "axios";
import React, { useEffect, useState } from "react";
import PokemonSprite from "./PokemonSprite";
import Card from "#material-tailwind/react/Card";
import CardBody from "#material-tailwind/react/CardBody";
import CardFooter from "#material-tailwind/react/CardFooter";
import H6 from "#material-tailwind/react/Heading6";
import Paragraph from "#material-tailwind/react/Paragraph";
import Button from "#material-tailwind/react/Button";
// const baseURL = "https://pokeapi.co/api/v2/pokemon?limit=898";
const baseURL = "https://pokeapi.co/api/v2/pokemon?limit=20";
export default function PokemonList() {
const [post, setPost] = useState([]);
const [searchTerm, setSearchTerm] = useState('');
useEffect(() => {
axios.get(baseURL).then((response) => {
setPost(response.data.results);
});
}, []);
if (!post) return <p>Sorry, no results.</p>;
return (
<div>
<input type="text" placeholder="Search..." onChange={e => {setSearchTerm(e.target.value)}}/>
{post.filter((data) => {
if (searchTerm == "") {
return data;
} else if (data.name.toLowerCase().includes(searchTerm.toLowerCase())) {
console.log(data);
return data;
}
}).map((data, idx) => (
<div className="p-5">
<Card key={idx}>
<PokemonSprite url={data.url} />
<CardBody>
<H6 color="gray">{data.name}</H6>
<Paragraph color="gray">
Don't be scared of the truth because we need to restart the human
foundation in truth And I love you like Kanye loves Kanye I love
Rick Owens’ bed design but the back is...
</Paragraph>
</CardBody>
<CardFooter>
<Button color="lightBlue" size="lg" ripple="light">
Read More
</Button>
</CardFooter>
</Card>
</div>
))}
</div>
);
}
PokemonSprite.jsx
import axios from "axios";
import React, { useEffect, useState } from "react";
import CardImage from "#material-tailwind/react/CardImage";
export default function PokemonList(url) {
const [post, setPost] = useState();
console.log(url);
useEffect(() => {
axios.get(url.url).then((response) => {
//console.log(response.data);
setPost(response.data);
});
}, []);
if (!post) return <p>Sorry, no results.</p>;
return (
<div>
<CardImage
src={post.sprites.front_default}
alt="Card Image"
/>
</div>
);
}
Please rewrite your PokemonSprite component like this to enable re rendering on updates to the Url...
import axios from "axios";
import React, { useEffect, useState } from "react";
import CardImage from "#material-tailwind/react/CardImage";
export default function PokemonList(url) {
const [post, setPost] = useState();
console.log(url);
const getUpdatedImage = async (imageUrl) => {
const response = await axios.get(imageUrl);
setPost(response.data);
return post;
}
useEffect(() => {
getUpdatedImage(url.url);
}, [url]);
if (!post) return <p>Sorry, no results.</p>;
return (
<div>
<CardImage
src={post.sprites.front_default}
alt="Card Image"
/>
</div>
);
}

Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization at Module.default (post.js:44)

I created a twitter clone with React.js and it is working, but if I try to get the data from the Firebase, I get this error. I get this error in the console. Uncaught ReferenceError: Cannot access 'WEBPACK_DEFAULT_EXPORT' before initialization but showing that everything is working fine in the terminal. Please let me know what could be wrong.
feed.js
import React, { useEffect, useState } from "react";
import db from "../firebase";
import "./feed.css";
import TweetBox from "./TweetBox";
import Post from "./post";
const Feed = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
db.collection("posts").onSnapshot((snapshot) => {
setPosts(snapshot.docs.map((doc) => doc.data()));
});
}, []);
return (
<div className="feed">
<div className="feed_header">
<h2>Home</h2>
</div>
<TweetBox />
{posts.map((post) => (
<Post
displayName={post.displayName}
userName={post.userName}
isVerified={post.isVerified}
text={post.text}
avatar={post.avatar}
image={post.image}
/>
))}
</div>
);
};
export default Feed;
post.js
import React from "react";
import { Avatar } from "#material-ui/core";
import "./post.css";
import VerifiedUserIcon from "#material-ui/icons/VerifiedUser";
import ChatBubbleOutlineIcon from "#material-ui/icons/ChatBubbleOutline";
import RepeatIcon from "#material-ui/icons/Repeat";
import FavoriteBorderIcon from "#material-ui/icons/FavoriteBorder";
import BackupIcon from "#material-ui/icons/Backup";
const Post = ({ displayName, userName, isVerified, text, image, avatar }) => {
return (
<div className="post">
A
<div className="post__avatar">
<Avatar src={avatar} />
</div>
<div className="post__body">
<div className="post__header">
<div className="post__headerText">
<h3>
{displayName} {""}
<span className="post__headerSpecial">
{isVerified && <VerifiedUserIcon className="post__badge" />}#
{userName}
</span>
</h3>
</div>
<div className="post__headerDescription">
<p>{text}</p>
</div>
</div>
<img src={image} alt="" />
<div className="post__footer">
<ChatBubbleOutlineIcon fontSize="small" />
<RepeatIcon fontSize="small" />
<FavoriteBorderIcon fontSize="small" />
<BackupIcon fontSize="small" />
</div>
</div>
</div>
);
};
export default Post;
firebase.js
import firebase from "./firebase"
const firebaseApp = firebase.initializeApp(firebaseConfig)
const db = firebaseApp.firebase();
export default db;

How to assign value onClick from different component to another component in React

What i want to do :
When i click my button i.e Search in Navbar.js i want to assign the search text in the variable urlQuery so i can pass it as props in Episodes.js component
End goal is to pass the urlQuery from Navbar.js somehow to Episodes.js component so i can query the REST api
How do i achieve the desired behaviour pls help
App.js
import React, { useState } from 'react';
import './App.css'
import Episodes from './components/Episodes/Episodes'
import CustomNavbar from './components/Navbar/Navbar'
import Pagination from './components/Pagination/Pagination'
function App() {
const [postsPerPage] = useState(20);
const [currentPage, setCurrentPage] = useState(1);
const url=`https://rickandmortyapi.com/api/episode?page=${currentPage}`
let urlQuery = `https://rickandmortyapi.com/api/episode?name=${SEARCH TEXT HERE}`
const paginate = pageNumber => setCurrentPage(pageNumber);
return (
<div>
<CustomNavbar />
<Episodes
urlQuery={urlQuery}
url={url}
/>
<Pagination
postsPerPage={postsPerPage}
totalPosts={36}
paginate={paginate}
/>
</div>
);
}
export default App;
Navbar.js
import React from 'react';
import Navbar from 'react-bootstrap/Navbar';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import FormControl from 'react-bootstrap/FormControl';
const customNavbar = () => {
return (
<Navbar bg="light" expand="lg">
<Navbar.Brand href="#home">Rick And Morty</Navbar.Brand>
<Form inline>
<FormControl type="text" placeholder="Search" />
<Button>Search</Button>
</Form>
</Navbar>
);
}
export default customNavbar
Edit
On Zohaib's suggestion this error is thrown
Failed to compile.
./src/components/Navbar/Navbar.js
Line 14:48: Unexpected use of 'event' no-restricted-globals
Search for the keywords to learn more about each error.
App.js
import React, { useState, useEffect } from 'react';
import './App.css'
import Episodes from './components/Episodes/Episodes'
import CustomNavbar from './components/Navbar/Navbar'
import Pagination from './components/Pagination/Pagination'
function App() {
const [postsPerPage] = useState(20);
const [currentPage, setCurrentPage] = useState(1);
const [userSearchValue, setUserSearchValue] = useState('');
const [url, setUrl] = useState(``);
const [urlQuery, setUrlQuery] = useState(``)
useEffect(() => {
setUrl(`https://rickandmortyapi.com/api/episode?page=${currentPage}`)
}, [currentPage]);
useEffect(() => {
setUrlQuery(`https://rickandmortyapi.com/api/episode?name=${userSearchValue}`)
}, [userSearchValue])
const paginate = pageNumber => setCurrentPage(pageNumber);
const handleButtonClick = (searchValue) => {
setUserSearchValue(searchValue);
}
return (
<div>
<CustomNavbar
onButtonClick={handleButtonClick}
/>
<Episodes
urlQuery={urlQuery}
url={url}
/>
<Pagination
postsPerPage={postsPerPage}
totalPosts={36}
paginate={paginate}
/>
</div>
);
}
export default App;
Navbar.js
import React, { useState } from 'react';
import Navbar from 'react-bootstrap/Navbar';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import FormControl from 'react-bootstrap/FormControl';
const customNavbar = ({ onButtonClick }) => {
const [searchValue, setSearchValue] = useState('');
return (
<Navbar bg="light" expand="lg">
<Navbar.Brand href="#home">Rick And Morty</Navbar.Brand>
<Form inline>
<FormControl type="text" placeholder="Search" value={searchValue} onChange={(e) => setSearchValue(e.target.value)} />
<Button onClick={() => onButtonClick(searchValue)}>Search</Button>
</Form>
</Navbar>
);
}
export default customNavbar
The important part here is you're passing down the handleButtonClick function to the child component (Navbar). This way you can call that parent function in the child component whenever you want (ie. when the user clicks the submit button).
Do you mean something like this?
There is a React guide about this specific problem: Lifting State Up.
Normally what you do is you manage the state in the parent. In this case App where you manage the search text state. You pass down a function to components to change this state. The components that depend upon this state are passed the value through the properties.
Here is an example:
const {useEffect, useState} = React;
function App() {
const episodesURL = "https://rickandmortyapi.com/api/episode";
const [page, setPage] = useState(1);
const [pageInfo, setPageInfo] = useState({});
const [searchText, setSearchText] = useState("");
const [episodes, setEpisodes] = useState([]);
useEffect(() => {
const url = new URL(episodesURL);
url.searchParams.set("page", page);
if (searchText) url.searchParams.set("name", searchText);
fetch(url)
.then(response => response.json())
.then(response => {
if (response.error) {
setPageInfo({});
setEpisodes([]);
} else {
setPageInfo(response.info);
setEpisodes(response.results);
}
});
}, [page, searchText]);
const search = searchText => {
setSearchText(searchText);
setPage(1);
};
return (
<div>
<CustomNavbar search={search} />
<Episodes episodes={episodes} />
<Pagination setPage={setPage} info={pageInfo} />
</div>
);
}
function CustomNavbar({search}) {
const [searchText, setSearchText] = useState("");
const handleFormSubmit = event => {
event.preventDefault();
search(searchText);
};
return (
<form onSubmit={handleFormSubmit}>
<input
type="text"
placeholder="search"
value={searchText}
onChange={event => setSearchText(event.target.value)}
/>
<button type="submit">Search</button>
</form>
);
}
function Episodes({episodes}) {
return (
<table>
<thead>
<tr>
<th>episode</th>
<th>name</th>
<th>air date</th>
</tr>
</thead>
<tbody>
{episodes.map(episode => (
<tr key={episode.id}>
<td>{episode.episode}</td>
<td>{episode.name}</td>
<td>{episode.air_date}</td>
</tr>
))}
</tbody>
</table>
);
}
function Pagination({setPage, info}) {
return (
<div>
{info.prev && <a onClick={() => setPage(page => page - 1)}>previous</a>}
{info.next && <a onClick={() => setPage(page => page + 1)}>next</a>}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
th { text-align: left; }
a { cursor: pointer; }
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root"></div>
Change urlQuery to state variable. Then, pass setUrlQuery to NavBar as a prop and on search button clickEvent call setUrlQuery function.

React, Adding data from json to single post component

I try to write website in React and that was going fine until now. I totally got stuck.
I have component with list of posts which is working fine. My problem is, that I dont know how to add data from JSON to single post component. I was trying to change geting my JSON data from list articles component to app.js and then passing it down to component with my list posts and to single post component, but then I have error with map() function.
//geting data from JSON and passing it through props down
import React, { useEffect, useState } from "react";
import "./style.css";
import SideBar from "../SideBar";
import MainContent from "../MainContent";
import blogData from "../../assets/data/blog.json";
const MainContainer = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
const post = blogData.data;
setPosts(post);
}, []);
return (
<div className="main-container">
<MainContent posts={posts} />
<SideBar posts={posts} />
</div>
);
};
export default MainContainer;
//mapping through posts
import React from "react";
import "./style.css";
import Post from "../Post";
const MainContent = ({ posts }) => {
return (
<main className="main-content">
{posts.map(post => {
return <Post key={post.id} post={post} />;
})}
</main>
);
};
export default MainContent;
//Post from list of posts
const Post = ({ post }) => {
return (
<div className="post">
<Animated
animationIn="bounceInLeft"
animationOut="fadeOut"
isVisible={true}
>
<h3 className="postTitle">{post.blogTitle}</h3>
<div className="imgContainer">
<img
alt="travel"
src={require("../../assets/img/" + post.blogImage)}
></img>
</div>
<p className="postDescription">{post.blogText}</p>
<NavLink to={`/post/${post.id}`}>
<h5 className="postLink">Read more</h5>
</NavLink>
<h5 className="posteDate">
Posted on {post.postedOn} by {post.author}
</h5>
</Animated>
</div>
);
};
export default Post;
Here is link to my repo:
https://github.com/Gitarrra92/travel-blog/
I think I should have a state in my component with single object of specific id. I just still dont know how to do this. This is my SinglePost component
const SinglePost = ({ match }) => {
const [singlePosts, setSinglePost] = useState({});
useEffect(() => {
const singlePost = blogSingleData.data;
setSinglePost(singlePost);
console.log(singlePost);
}, [match]);
return (
<>
<Socials />
</>
);
};
export default SinglePost;

Categories