I have json data file. I want to make a search with the names of the data and display the typed names when I click the search button.
I get the value of input in the console when I type something however I am not able to display it on the screen
How can I display the value of this input ?
my code is below
PostResults.jsx
import React from "react";
const PostResults = (props) => {
const {name} = props.posts
return(
<div className="">
<p className="titles">{name}</p>
</div>
)
}
export default PostResults
Posts.jsx
import React, { useState, useEffect } from "react";
import PostResults from './PostResults'
const Posts = (props) => {
const [posts, setPosts] = useState([]);
const [searchTerm,setSearchTerm]=useState([]);
const getData = () => {
fetch('data.json')
.then(response => {
return response.json()
//console.log(response)
})
.then(data => {
setPosts(data)
console.log(data)
})
}
useEffect(() => {
getData()
},[])
const submitHandler = (event) => {
event.preventDefault()
{searchTerm ? searchTerm : console.log("none")}
}
return(
<div className="">
<input
type="text"
placeholder="Search Anything"
name="query"
onChange={e => setSearchTerm(e.target.value)}
className="search-input"
/>
<button
onClick={submitHandler}
type="submit"
className="search-button"
>
<i className="fas fa-search"></i>
</button>
{posts.map(posts => (
<PostResults key={posts.id} posts={posts}/>
))}
</div>
)
}
export default Posts
App.jsx
import React from "react";
import "./style.css";
import 'bootstrap/dist/css/bootstrap.min.css'
import Posts from './components/Posts'
export default function App() {
return (
<div className="container">
<div className="row">
< Posts />
</div>
</div>
);
}
Related
I am new to reactJS. i am expecting the json data to be fetched and displayed according to the options that are clicked. I tested with console.log and the data was being fetched correctly, however when i tried using useState setItems(json), it gives me an error of 'Uncaught TypeError: items.map is not a function'
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { useState, useEffect} from 'react';
function App() {
const [option, setOption] = useState('Posts')
const [items, setItems] = useState([])
useEffect(()=> {
fetch(`https://jsonplaceholder.typicode.com/${option}`)
.then(response => response.json())
.then(json => setItems(json))
}, [option])
return (
<div className="App">
<div className='container'>
<div className='menuBar'>
<button onClick={()=> setOption('posts')}>Posts</button>
<button onClick={()=> setOption('users')}>Users</button>
<button onClick={() => setOption('comments')}>Comments</button>
<h2>{option}</h2>
{items.map(item => {
return <pre>{JSON.stringify(item)}</pre>
})}
</div>
</div>
</div>
);
}
export default App;
To make your code fail-safe and easier to debug, you should check if items is an array before using map.
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { useState, useEffect } from "react";
function App() {
const [option, setOption] = useState("posts");
const [items, setItems] = useState([]);
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/${option}`)
.then(response => response.json())
.then(json => setItems(json));
}, [option]);
return (
<div className="App">
<div className="container">
<div className="menuBar">
<button onClick={() => setOption("posts")}>Posts</button>
<button onClick={() => setOption("users")}>Users</button>
<button onClick={() => setOption("comments")}>Comments</button>
<h2>{option}</h2>
{Array.isArray(items) ? items.map(item => <pre>{JSON.stringify(item)}</pre>) : <pre>{JSON.stringify(items)}</pre>}
</div>
</div>
</div>
);
}
export default App;
I have such a problem. I want to receive a notification after entering a keyword in the input and submitting. If there is a movie, then the movies should be listed, if there is not movies, let the toast notification appear. But the problem, even movies there are still toast works. How can i fix it? I want only when there are no movies for example search results doesnt find any film that toast will come. But toast comes every moment
import React, { useState } from "react";
import axios from "axios";
import { API_KEY } from "../../utils/api";
import MovieItem from "../../components/MovieItem/MovieItem";
import { Button, Input, Form } from "antd";
import "antd/dist/antd.min.css";
import "./Search.scss";
import Loader from "../../components/Loader/Loader";
import { toast } from "react-toastify";
const Search = () => {
const [movies, setMovies] = useState([]);
const [searchTerm, setSearchTerm] = useState("");
const [loading, setLoading] = useState(false);
const fetchSearch = () => {
setLoading(true)
axios
.get(
`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&language=en-US&query=${searchTerm}&page=1&include_adult=false`
)
.then((res) => res.data)
.then((res) => {
if (!res.errors) {
setMovies(res.results);
setLoading(false)
if (movies.length === 0) {
toast("Movies doesnt find");
}
setSearchTerm("");
console.log("yes");
} else {
setMovies([]);
console.log("no");
}
});
};
const handleChange = (e) => {
setSearchTerm(e.target.value);
};
return (
<>
<div className="search">
<div className="container">
<div className="row">
<div className="col-lg-12 mb-3 mt-3">
<h2>Suggest me</h2>
</div>
<Form onFinish={fetchSearch}>
<Form.Item>
<Input
value={searchTerm}
onChange={handleChange}
placeholder="Search Movies"
/>
</Form.Item>
<Button htmlType="submit">Search</Button>
</Form>
</div>
</div>
</div>
<div className="movies">
<div className="container-fluid">
<div className="row">
{loading
?
<Loader/>
: movies?.map((movie, index) => (
<div className="col-lg-3 p-3" key={index}>
<MovieItem movie={movie} page='top_Rated'/>
</div>
))}
</div>
</div>
</div>
</>
);
};
export default Search;
Problem is solved. Res.results.length was my problem's solution
I'm trying to make a FAQ of sorts, right now I have it as a search bar but I'm having a hard time sending a value that I want the videos to populate with. I want the user to have the option to click on the button, and that specific button have the data of "How to find a queen" and send that automaitcally to the iframe player. Any pointers on how to achieve this? As I have it right now, my handleSubmit populates the search bar.
SearchBar.jsx
import React, { useState } from 'react';
import "./SearchBar.css";
const SearchBar = (props) => {
const [searchRequest, setSearchRequest] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
props.getSearchResults(searchRequest);
setSearchRequest('What Does a Queen Bee look like?');
}
return (
<div className='search-contain'>
<form className='search-form-contain' onSubmit={handleSubmit}>
<label className='search-label'>Search:</label>
<input type='text' placeholder="Search for a video..." className='search-input' value={searchRequest} onChange ={(event) => setSearchRequest(event.target.value)} />
<button className='search-button'>Search</button>
</form>
</div>
);
}
export default SearchBar;```
import React from "react";
import "./VideoPlayer.css";
const VideoPlayer = (props) => {
return (
<div>
<iframe
id="ytplayer"
title="MyPlayer"
type="text/html"
width="640"
height="360"
src={`https://www.youtube.com/embed/${props.videoId}?autoplay=1&origin=http://example.com`}
frameBorder="0">
</iframe>
<div className="video-details">
<h3>{props.title}</h3>
<p>{props.description}</p>
</div>
<div className="video-details">
</div>
<div className="flex-container">
{props.relatedVideos.map((video, index) => {
if(video.snippet){
return (
<div key={index} className="flex-item">
<div>
<img src={video.snippet.thumbnails.medium.url} alt="" />
</div>
<div>
<h6 >{video.snippet.title}</h6>
</div>
</div>
);
} else {
return null;
}
})}
</div>
</div>
);
}
export default VideoPlayer;
VideoPage.js
import React, {useEffect, useState } from "react";
import { Link } from "react-router-dom";
import "./VideoPage.css";
import SearchBar from "../../components/SearchBar/SearchBar";
import axios from 'axios'
import VideoPlayer from "../../components/VideoPlayer/VideoPlayer";
import { KEY } from "./../../localKey"
const VideoPage = () => {
const [searchResults, setSearchResults] = useState('');
const [videoId, setVideoId] = useState("");
const [description, setDescription] = useState("");
const [title, setTitle] = useState("");
const [relatedVideos, setRelatedVideos] = useState([]);
useEffect(() => {
getSearchResults();
},[])
async function getSearchResults(searchTerm='Bees'){
let response = await axios.get(`https://www.googleapis.com/youtube/v3/search?part=snippet&q=${searchTerm}&type=video&maxResults=1&key=${KEY}`);
setVideoId(response.data.items[0].id.videoId)
setDescription(response.data.items[0].snippet.description)
setTitle(response.data.items[0].snippet.title)
setSearchResults(response.data.items)
console.log(response.data.items)
}
useEffect(() => {
const fetchRelatedVideos = async () => {
try {
let response = await axios.get(`https://www.googleapis.com/youtube/v3/search?key=${KEY}&part=snippet&maxResults=3&type=video&relatedToVideoId=${videoId}`, {
});
setRelatedVideos(response.data.items);
} catch (error) {
console.log(error.message);
}
};
fetchRelatedVideos();
}, [videoId]);
return (
<div>
<div className="video-reg-contain"></div>
<div><SearchBar getSearchResults={getSearchResults}/></div>
<div className = 'video-contain'>
<div className="video-container">
<div className='video-player'>
<VideoPlayer videoId={videoId}
description={description}
title={title}
relatedVideos={relatedVideos}/>
</div>
</div>
</div>
</div>
);
};
export default VideoPage;
I have a movie app which displays a card for each movie in a state.
I would like to use a dynamic search bar to render movies corresponding to the search input value.
For instance, if I start to write "Har", I want to see only movies with a title that begins with "Har".
The app code :
import React, { useState, useEffect } from "react";
import "./App.css";
import Logo from "../components/Logo";
import Search from "../components/Search";
import Add_movie_button from "../components/Add_movie_button";
import Random_movie_button from "../components/Random_movie_button";
import Movie_card from "../components/Movie_card";
import axios from "axios";
const BASE_URL = "https://api.themoviedb.org/3/movie/";
const API_KEY = "4bcd155b9b8734cb8559319cdbfaf62f";
function App() {
const [movieinfos, setMovieinfos] = useState([]);
console.log(movieinfos);
useEffect(() => {
axios
.get("http://localhost:5000")
.then(function (response) {
const movies = response.data.movies;
console.log(response.data.movies);
return Promise.all(
movies.map((movie) =>
axios.get(
`${BASE_URL}${movie.movieid}?api_key=${API_KEY}&language=fr`
)
)
);
})
.then((responses) => {
console.log(responses);
setMovieinfos(
responses.map((response) => ({
Genres: response.data.genres,
Overview: response.data.overview,
Poster: response.data.poster_path,
Company: response.data.production_companies,
Release: response.data.release_date,
Title: response.data.title,
Id: response.data.id,
}))
);
});
}, []);
return (
<div className="App">
<div className="Header">
<Logo />
</div>
<div className="Menu">
<Search movieinfos={movieinfos} setMovieinfos={setMovieinfos} />
<Add_movie_button />
<Random_movie_button data={movieinfos} />
</div>
<div className="Movies">
{movieinfos.map((movie) => (
<Movie_card key={movie.Title} data={movie} />
))}
</div>
</div>
);
}
export default App;
The search bar code :
import React from "react";
import "./style.css";
const Search = (props) => {
console.log(props);
return (
<div className="Search">
<input
type="search"
id="Search_input"
placeholder="Rechercher un film ..."
value= //WHAT DO I NEED TO WRITE HERE ?
onChange={(event) =>
/*WHAT DO I NEED TO WRITE HERE ?*/ event.target.value
}
/>
</div>
);
};
export default Search;
You could create a state variable
[searchWord, setSearchWord] = useState('')
your input would then contain
value={searchWord}
onChange={e => setSearchWord(e.target.value)}
You could then filter your array movieinfos with the searchWord and map the returning array to display only the movies with the search world
movieinfos.filter(movie => movie.title.includes(searchWord)).map(movie => return <Movie_card key={movie.Title} data={movie} />)
i am beginner in react . when i fetch request from API, i got data in console ,but when i am trying to display data in web page in that time data isn't show.
I want to display data in web page.
here is my console log
https://ibb.co/YLmLQz1
App.js
import React from 'react';
import './App.css';
import Header from './components/Header';
import Movie from './components/Movies';
const App = () => {
return (
<div className="App">
<Header />
<div className='container'>
<Movie />
</div>
</div>
);
}
export default App;
Header.js
In header file i created my navbar and search form
import React, { useState } from 'react'
const Header = () => {
const [search, setSearch] = useState('');
return (
<div className="jumbotron">
<h1 className="display-1">
<i className="material-icons brand-icon">LatestMovie</i> Movie
</h1>
<div className="input-group w-50 mx-auto">
<input
type="text"
className="form-control"
placeholder="Search Your Movie..."
value={search}
onChange={e => setSearch(e.target.value)}
/>
<div className="input-group-append">
<button className="btn btn-dark">
Search Movie
</button>
</div>
</div>
</div>
)
}
export default Header;
Movies.js
here i fetch my movies request throght axios
import React, { useEffect, useState } from 'react'
import Axios from 'axios';
const Movie = () => {
const [movies, setMovie] = useState([]);
const apiurl = "http://www.omdbapi.com/?apikey=642b793e&s=marvel"
const getMovies = async () => {
const res = await Axios.get(apiurl);
console.log(res);
setMovie(res.data.hits);
}
useEffect(() => {
getMovies();
}, []);
return (
<div className='row'>
{
movies && movies.map(movie => (
<div className='col-md-3'>
<div className='card'>
<div className='card-body'>
<h4>{movie.Year}</h4>
</div>
</div>
</div>
))
}
</div>
)
}
export default Movie;