Conditional within a render in the content display component in React.js - reactjs

I have a component that needs to display the details of a movie according to the id that is passed in the URL (parameter). I'm having difficulty doing the conditional on the RENDER method. It's probably quite simple, but I'm still not very familiar with the React flow. Can you give me an idea?
Ex: Codesandbox
import React, { Component } from "react";
import api from "../../services/api";
export default class Movie extends Component {
state = {
movies: [],
movieId: {}
};
async componentDidMount() {
const { id } = this.props.match.params;
const response = await api.get("");
const currentParams = this.props.match.params;
this.setState({
movies: response.data,
movieId: `${id}`
});
console.log(this.state.movies);
console.log(this.state.movieId);
}
render() {
const movies = this.state.movies,
currentParams = this.state.movieId;
return (
<div className="movie-info">
{this.state.movies.map(movie => (
if( movie.event.id === currentParams ) {
<h1 key={movie.event.id}>{movie.event.title}</h1>
}
))}
</div>
);
}
}

You might not want to use map in this case since you only want to render one movie. You could instead use the find method and render that single movie if it's found.
class Movie extends Component {
// ...
render() {
const { movies, movieId } = this.state;
const movie = movies.find(movie => movie.event.id === movieId);
return (
<div className="movie-info">
{movie ? <h1 key={movie.event.id}>{movie.event.title}</h1> : null}
</div>
);
}
}

Related

if else statement not working in react component

I am trying to implement a condition in my react component . When the user triggers the onClick the state updates allStakes creating one array of 4 values. The problem is that I do not want the user to input more than 4 values so tried to give the limit by doing an if else statement. I tried to add a console.log in both statements.The weird fact is that setState get updated but the csonole.log is never displayed.The component keeps rendering all the values that I insert even if the array is longer than 4. Thanks in advance
import React, { Component } from 'react';
import Stake from './stake';
class FetchRandomBet extends Component {
constructor(props) {
super(props);
this.state = {
loading: true,
bet: null,
value: this.props.value,
allStakes: []
};
}
async componentDidMount() {
const url = "http://localhost:4000/";
const response = await fetch(url);
const data = await response.json();
this.setState({
loading: false,
bet: data.bets,
});
}
render() {
const { valueProp: value } = this.props;
const { bet, loading } = this.state;
const { allStakes } = this.state;
if (loading) {
return <div>loading..</div>;
}
if (!bet) {
return <div>did not get data</div>;
}
return (
< div >
{
loading || !bet ? (
<div>loading..</div>
) : value === 0 ? (
<div className="bet-list">
<ol>
<p>NAME</p>
{
bet.map(post => (
<li key={post.id}>
{post.name}
</li>
))
}
</ol>
<ul>
<p>ODDS</p>
{
bet.map(post => (
<li key={post.id}>
{post.odds[4].oddsDecimal}
<div className="stake-margin">
<Stake
onClick={(newStake) => {
if (allStakes.length <= 3) {
this.setState({ allStakes: [allStakes, ...newStake] })
console.log('stop')
} else if (allStakes.length == 4) {
console.log('more than 3')
}
}}
/>
</div>
</li>
))
}
</ul>
</div>
May be it happens because of incorrect array destructuring. Try to change this code:
this.setState({ allStakes: [allStakes, ...newStake] })
by the next one:
this.setState({ allStakes: [newStake, ...allStakes] })
Your state belongs to your FetchRandomBet component and you are trying to update that from your imported component. There are 2 solutions to that.
1> Wrap your Stake component to a separate component with onClick handler something like this
<div onClick={(newStake) => {
if (allStakes.length <= 3) {
this.setState({
allStakes: [allStakes, ...newStake
]
})
console.log('stop')
} else if (allStakes.length == 4) {
console.log('more than 3')
}
}}><Stake /></div>
Or
2> Pass the state as a prop to the Stake component which will be responsible to update the state for FetchRandomBet. something like this
<Stake parentState={this}/>
And inside the Stake component change the parentState on click of wherever you want.
I solved the problem. I transfered the onClick method in stake component and I handled the upload of the common array with an array useState. I add the value to newStake and when I click ok I retrieve newStake and spread it into a new array and then I check that array. If there is a value should not keep adding otherwise it can add values. It works fine. Thanks anyway
import React, { useState } from 'react';
import CurrencyInput from 'react-currency-input-field';
function Stake(props) {
const [newStake, setStake] = useState(null);
const [allStakes, setStakes] = useState(null);
const changeStake = (e) => {
setStake([e.target.value])
}
const mySubmit = () => {
if (!allStakes) {
setStakes([...newStake, allStakes])
props.onClick(newStake);
} else if (allStakes) {
console.log('stop')
}
}
return (
<>
<CurrencyInput
onChange={changeStake}
style={{
marginLeft: "40px",
width: "50px"
}}
placeholder="Stake"
decimalScale={2}
prefix="£"
/>
<button onClick={mySubmit}>yes</button>
<button>no</button>
{newStake}
</>
);
}
export default Stake;

React - error result map is not a function?

Framework: React
Error type: result.map is not a function
I am following the book Road to learn React, I tried the below code with hacker news API it worked well but it is not working with this API. I don't know why I'm getting this error, please help.
Link to my sandbox --> https://codesandbox.io/s/react-setup-forked-q0hti?file=/src/App.js
import React, { Component } from "react";
// API chunks
const PATH_BASE = "https://jsonplaceholder.typicode.com/todos";
const PATH_SEARCH = "/search";
const PARAM_SEARCH = "query=";
const DEFAULT_QUERY = "redux";
//const url = `${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${DEFAULT_QUERY}`;
//console.log(url);
class App extends Component {
constructor() {
super();
this.state = {
result: null
};
this.hitStories = this.hitStories.bind(this);
}
// handling the local state value
hitStories(result) {
this.setState({
result
});
}
// lifecycle method
// Note: componenetDidMount runs after the render method
componentDidMount() {
fetch(`${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${DEFAULT_QUERY}`)
.then((response) => response.json())
.then((json_result) => this.hitStories(json_result))
.catch((error) => error);
}
render() {
console.log(this.state)
const { result } = this.state;
if (!result) {
return null;
}
return (
<div>
<h2>Fetch API in React</h2>
{result.map((
item
) => (
<div>
{item.title}
</div>
))}
</div>
);
}
}
export default App;
.map is used on an array, your result is not an array but an object. Try this:
render() {
const { result } = this.state;
return result ? (
<div>
<h2>Fetch API in React</h2>
{ Object.values(result).map((item) => (
<div>{item.title}</div>
))
}
</div>
): null;
}

How to fix recursively updating state?

I am bulding an app using newsapi. i am facing two issue on my state. i fetch data using api and assign it to my state. and use it in my view.
Issue no 1
My view gets rendered before my app receives the data.
Issue no 2
When I try to update my state after a new fetch. it recursively updates the set of data again and again.
import React, {Component} from 'react';
import NewsComponent from './NewsComponent/NewsComponent'
class News extends Component {
state = {
displayStatus: false,
newsItems: []
};
toogleDisplayHandler = () => {
if(this.state.displayStatus===true){
this.setState({displayStatus:false})
}
else{
this.setState({displayStatus:true})
}
}
render(){
const NewsAPI = require('newsapi');
const newsapi = new NewsAPI('d6da863f882e4a1a89c5152bd3692fb6');
//console.log(this.props.keyword);
newsapi.v2.topHeadlines({
sources: 'bbc-news,abc-news',
q: this.props.keyword
}).then(response => {
//console.log(response)
response.articles.map(article => {
//console.log(article);
return(
//console.log(this.state.newsItems)
this.setState({
newsItems: [...this.state.newsItems, article],
})
//this.state.newsItems.push(article)
)
});
});
let Article = null;
Article = (
<div>
{
this.state.newsItems.map((news, index) => {
return (
<NewsComponent key={index}
title={news.title}
url={news.url}
description={news.description}
author={news.author}
publish={news.publishedAt}
image={news.urlToImage}
/>
)
})
}
</div>
)
return (
<div className="App">
{Article}
<button onClick={this.toogleDisplayHandler}>
{this.state.displayStatus === true ? "Hide Article" : "Display Articles"}
</button>
</div>
)
}
}
export default News;
Please help me to resolve this issue.
You should never setState in render as that would cause an infinite loop. Do it in componentDidMount or the constructor.
I would also recommend not using map for simply iterating over a list. Array.map is a function that is useful for returning an array that is constructed by iterating over another array. If you want to run some code for each element of an array use Array.forEach instead.
Like this:
import React, { Component } from "react";
import NewsComponent from "./NewsComponent/NewsComponent";
class News extends Component {
state = {
displayStatus: false,
newsItems: []
};
toogleDisplayHandler = () => {
if (this.state.displayStatus === true) {
this.setState({ displayStatus: false });
} else {
this.setState({ displayStatus: true });
}
};
componentDidMount = () => {
const NewsAPI = require("newsapi");
const newsapi = new NewsAPI("d6da863f882e4a1a89c5152bd3692fb6");
newsapi.v2
.topHeadlines({
sources: "bbc-news,abc-news",
q: this.props.keyword
})
.then(response => {
response.articles.forEach(article => {
this.setState({
newsItems: [...this.state.newsItems, article]
});
});
});
};
render() {
let Article = null;
Article = (
<div>
{this.state.newsItems.map((news, index) => {
return (
<NewsComponent
key={index}
title={news.title}
url={news.url}
description={news.description}
author={news.author}
publish={news.publishedAt}
image={news.urlToImage}
/>
);
})}
</div>
);
return (
<div className="App">
{Article}
<button onClick={this.toogleDisplayHandler}>
{this.state.displayStatus === true
? "Hide Article"
: "Display Articles"}
</button>
</div>
);
}
}
export default News;
1) You can add a check either your state has the data which you want to show on screen to render the view.
2) Please use ComponentDidMount React life cycle function to fetch data from an external source and update this data in the state. In the Render method, it will keep calling it recursively.

How can I pass the state from parent component to a child to use in an API call?

I have a React app that queries an API that I built in Spring Boot. The React side should query the database to find a number of Activity objects to populate one Itinerary object. I want to keep track of the Ids of the activities so the app doesn’t return the same one more than once. Here’s how I set it up:
The Itinerary component has an array called "activities" in its state that will hold the ids. This starts out as empty. The Itinerary component also has a function called UpdateActivities() that updates the State with a new id when an activity is added.
UpdateActivities is passed as a callback to the child component Activity as props. The activities array in the state is turned into a string (because I'll be using this in the API call) and also passed as props to the Activity component.
In the Activity component, the callback function is further passed as a prop to the ActivityDetails component and the string of ids is further passed to ActivityDetails as well.
The ActivityDetails component makes the actual API call to my Spring Boot application and uses the callback function to update the State on the parent component. I attempted to save the string of ids to a constant to use in my API call. I want the string to go at the end of the call, so my app will know to skip over any activities with those Ids (currently hard-coded to 1).
The API call doesn't work if I replace 1 with the constant string of ids, because it shows up as empty. Is this an async issue? Is there a way to make it so the React app doesn't make the API call on ActivityDetails until the State is updated on the parent component?
Itinerary Component
class Itinerary extends Component {
constructor(props) {
super(props);
this.state = {
template: null,
activities: []
};
}
updateActivities = (id) => {
const activityList = [...this.state.activities, id];
this.setState({
activities: activityList
})
}
componentDidMount = () => {
const {duration, travelerType, pace} = this.props.userAnswers;
const transport = this.props.userAnswers.internalTravel.sort().join(', ');
const TEMPLATES_URL = `http://localhost:8080/templates/duration/${duration}/travelers/${travelerType}/pace/${pace}/transport/${transport}`;
axios.get(TEMPLATES_URL)
.then(response => {
this.setState({
template: response.data[0].content
});
})
.catch(function (error) {
console.log(error.message);
});
}
render() {
let cities;
if (this.state.template === null) {
cities = <div><h3>Loading...</h3></div>;
} else {
let data = this.state.template.split(", ");
cities = data.map((city, index) => {
return (
<section>
<City
key={index}
day={index + 1}
city={city}
/>
<Activity
key={`${city}${index}`}
day={index + 1}
lastDay={data.length}
city={city}
userAnswers={this.props.userAnswers}
updateActivityState={this.updateActivities}
activityList={this.state.activities.join(', ')}
/>
</section>
)
});
}
return (
<div>
<div className="row">
<div className="col s9">
<h3>{cities}</h3>
</div>
</div>
</div>
);
}
}
export default Itinerary;
Activity Component
class Activity extends Component {
render() {
let city = this.props.city;
if(this.props.day === 1) {
return (
<ActivityDetails
userAnswers={this.props.userAnswers}
city={city}
timeOfDay="evening"
handleActivityList={this.props.updateActivityState}
activities={this.props.activityList}/>
);
} else if (this.props.day === this.props.lastDay) {
return (
<ActivityDetails
userAnswers={this.props.userAnswers}
city={city} timeOfDay="morning"
handleActivityList={this.props.updateActivityState}
activities={this.props.activityList} />
);
} else {
return(
<section>
<ActivityDetails
userAnswers={this.props.userAnswers}
city={city}
timeOfDay="morning"
handleActivityList={this.props.updateActivityState}
activities={this.props.activityList} />
<ActivityDetails
userAnswers={this.props.userAnswers}
city={city}
timeOfDay="afternoon"
handleActivityList={this.props.updateActivityState}
activities={this.props.activityList} />
<ActivityDetails
userAnswers={this.props.userAnswers}
city={city}
timeOfDay="evening"
handleActivityList={this.props.updateActivityState}
activities={this.props.activityList} />
</section>
);
}
}
}
export default Activity;
ActivityDetails Component
class ActivityDetails extends Component {
constructor(props) {
super(props);
this.state = {
activity: 'Loading...',
};
}
componentDidMount() {
const {travelParty, budget, pace, sites} = this.props.userAnswers;
const cityTravel = this.props.userAnswers.cityTravel.sort().join(', ');
const interests = this.props.userAnswers.interests.sort().join(', ');
const entertainment = this.props.userAnswers.entertainment.sort().join(', ');
const currentActivities = this.props.activities;
console.log(`currentActivities: ${currentActivities}`);
const city = this.props.city;
const timeOfDay = this.props.timeOfDay;
const ACTIVITY_URL = `http://localhost:8080/filter/${city}/${timeOfDay}/${travelParty}/${budget}/${pace}/${sites}/${cityTravel}/${interests}/${entertainment}/1`;
console.log(ACTIVITY_URL);
axios.get(ACTIVITY_URL)
.then(response => {
const newActivity = response.data.content;
const updatedActivityId = response.data.id;
this.props.handleActivityList(updatedActivityId);
this.setState({
activity: newActivity,
});
})
.catch(function(error) {
console.log(error.message);
});
}
render () {
return (
<div>{this.state.activity}</div>
);
}
}
export default ActivityDetails;
Revised with ComponentDidMount:
class ActivityDetails extends Component {
constructor(props) {
super(props);
this.state = {
activity: 'Loading...',
};
}
getActivity() {
const {travelParty, budget, pace, sites} = this.props.userAnswers;
const cityTravel = this.props.userAnswers.cityTravel.sort().join(', ');
const interests = this.props.userAnswers.interests.sort().join(', ');
const entertainment = this.props.userAnswers.entertainment.sort().join(', ');
const city = this.props.city;
const timeOfDay = this.props.timeOfDay;
const currentActivities = this.props.activities;
console.log(`currentActivities: ${currentActivities}`);
const ACTIVITY_URL = `http://localhost:8080/filter/${city}/${timeOfDay}/${travelParty}/${budget}/${pace}/${sites}/${cityTravel}/${interests}/${entertainment}/${currentActivities}`;
console.log(ACTIVITY_URL);
axios.get(ACTIVITY_URL)
.then(response => {
const newActivity = response.data.content;
const updatedActivityId = response.data.id;
this.props.handleActivityList(updatedActivityId);
this.setState({activity: newActivity});
})
.catch(function(error) {
console.log(error.message);
});
}
componentDidMount() {
this.getActivity();
}
componentDidUpdate(prevProps) {
if(prevProps.activities !== this.props.activities) {
this.getActivity();
}
}
render () {
return (
<div>{this.state.activity}</div>
);
}
}
export default ActivityDetails;
The API call doesn't work if I replace 1 with the constant string of ids, because it shows up as empty. Is this an async issue?
This makes sense, yes. It's likely doing your Itinerary's fetch at roughly the same time as your ActivityDetails' fetch, so the state.activities there is still an empty array (ergo empty string once you've mutated it and passed it down).
Is there a way to make it so the React app doesn't make the API call on ActivityDetails until the State is updated on the parent component?
Yes, you can use other lifecycle methods to facilitate this. In your case, you probably want componentDidUpdate.
You could do something like:
class ActivityDetails extends Component {
constructor(props) {
super(props);
this.state = {
activity: 'Loading...',
};
}
doMyGet(values) {
const ACTIVITY_URL = `http://localhost:8080/filter/${city}/${timeOfDay}/${travelParty}/${budget}/${pace}/${sites}/${cityTravel}/${interests}/${entertainment}/1`;
console.log(ACTIVITY_URL);
axios.get(ACTIVITY_URL)
.then(response => {
const newActivity = response.data.content;
const updatedActivityId = response.data.id;
this.props.handleActivityList(updatedActivityId);
this.setState({
activity: newActivity,
});
})
.catch(function(error) {
console.log(error.message);
});
}
componentDidMount() {
const {travelParty, budget, pace, sites} = this.props.userAnswers;
const cityTravel = this.props.userAnswers.cityTravel.sort().join(', ');
const interests = this.props.userAnswers.interests.sort().join(', ');
const entertainment = this.props.userAnswers.entertainment.sort().join(', ');
const currentActivities = this.props.activities;
console.log(`currentActivities: ${currentActivities}`);
const city = this.props.city;
const timeOfDay = this.props.timeOfDay;
this.doMyGet(currentActivities)
}
componentDidUpdate(prevProps) {
if (this.props.activities !== prevProps.activities) {
this.doMyGet(this.props.activities)
}
}
render () {
return (
<div>{this.state.activity}</div>
);
}
}
export default ActivityDetails;

React setState fetch API

I am starting to learn React and creating my second project at the moment. I am trying to usi MovieDb API to create a movie search app. Everything is fine when I get the initial list of movies. But onClick on each of the list items I want to show the details of each movie. I have created a few apps like this using vanilla JS and traditional XHR call. This time I am using fetch API which seems straightforward ans simply to use, however when I map through response data to get id of each movie in order to retrieve details separately for each of them I get the full list of details for all the items, which is not the desired effect. I put the list of objects into an array, because after setState in map I was only getting the details for the last element. I know that I am probably doing something wrong within the API call but it might as well be my whole REACT code. I would appreciate any help.
My code
App.js
import React, { Component } from 'react';
import SearchInput from './Components/SearchInput'
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state =
{
value: '',
showComponent: false,
results: [],
images: {},
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleOnChange = this.handleOnChange.bind(this);
this.getImages = this.getImages.bind(this);
this.getData = this.getData.bind(this);
}
ComponentWillMount() {
this.getImages();
this.getData();
}
getImages(d) {
let request = 'https://api.themoviedb.org/3/configuration?api_key=70790634913a5fad270423eb23e97259'
fetch(request)
.then((response) => {
return response.json();
}).then((data) => {
this.setState({
images: data.images
});
});
}
getData() {
let request = new Request('https://api.themoviedb.org/3/search/movie?api_key=70790634913a5fad270423eb23e97259&query='+this.state.value+'');
fetch(request)
.then((response) => {
return response.json();
}).then((data) => {
this.setState({
results: data.results
});
});
}
handleOnChange(e) {
this.setState({value: e.target.value})
}
handleSubmit(e) {
e.preventDefault();
this.getImages();
this.setState({showComponent: true});
this.getData();
}
render() {
return (
<SearchInput handleSubmit={this.handleSubmit} handleOnChange={this.handleOnChange} results={this.state.results} images={this.state.images} value={this.state.value} showComponent={this.state.showComponent}/>
);
}
}
export default App;
SearchInput.js
import React, {Component} from 'react';
import MoviesList from './MoviesList';
class SearchInput extends Component {
render() {
return(
<div className='container'>
<form id='search-form' onSubmit={this.props.handleSubmit}>
<input value={this.props.value} onChange={this.props.handleOnChange} type='text' placeholder='Search movies, tv shows...' name='search-field' id='search-field' />
<button type='submit'>Search</button>
</form>
<ul>
{this.props.showComponent ?
<MoviesList value={this.props.value} results={this.props.results} images={this.props.images}/> : null
}
</ul>
</div>
)
}
}
export default SearchInput;
This is the component where I try to fetch details data
MovieList.js
import React, { Component } from 'react';
import MovieDetails from './MovieDetails';
let details = [];
class MoviesList extends Component {
constructor(props) {
super(props);
this.state = {
showComponent: false,
details: []
}
this.showDetails = this.showDetails.bind(this);
this.getDetails = this.getDetails.bind(this);
}
componentDidMount() {
this.getDetails();
}
getDetails() {
let request = new Request('https://api.themoviedb.org/3/search/movie?api_key=70790634913a5fad270423eb23e97259&query='+this.props.value+'');
fetch(request)
.then((response) => {
return response.json();
}).then((data) => {
data.results.forEach((result, i) => {
let url = 'https://api.themoviedb.org/3/movie/'+ result.id +'?api_key=70790634913a5fad270423eb23e97259&append_to_response=videos,images';
return fetch(url)
.then((response) => {
return response.json();
}).then((data) => {
details.push(data)
this.setState({details: details});
});
});
console.log(details);
});
}
showDetails(id) {
this.setState({showComponent: true}, () => {
console.log(this.state.details)
});
console.log(this.props.results)
}
render() {
let results;
let images = this.props.images;
results = this.props.results.map((result, index) => {
return(
<li ref={result.id} id={result.id} key={result.id} onClick={this.showDetails}>
{result.title}{result.id}
<img src={images.base_url +`${images.poster_sizes?images.poster_sizes[0]: 'err'}` + result.backdrop_path} alt=''/>
</li>
)
});
return (
<div>
{results}
<div>
{this.state.showComponent ? <MovieDetails details={this.state.details} results={this.props.results}/> : null}
</div>
</div>
)
}
}
export default MoviesList;
MovieDetails.js
import React, { Component } from 'react';
class MovieDetails extends Component {
render() {
let details;
details = this.props.details.map((detail,index) => {
if (this.props.results[index].id === detail.id) {
return(
<div key={detail.id}>
{this.props.results[index].id} {detail.id}
</div>
)} else {
console.log('err')
}
});
return(
<ul>
{details}
</ul>
)
}
}
export default MovieDetails;
Theres a lot going on here...
//Here you would attach an onclick listener and would fire your "get details about this specific movie function" sending through either, the id, or full result if you wish.
//Then you getDetails, would need to take an argument, (the id) which you could use to fetch one movie.
getDetails(id){
fetch(id)
displayresults, profit
}
results = this.props.results.map((result, index) => {
return(
<li onClick={() => this.getDetails(result.id) ref={result.id} id={result.id} key={result.id} onClick={this.showDetails}>
{result.title}{result.id}
<img src={images.base_url +`${images.poster_sizes?images.poster_sizes[0]: 'err'}` + result.backdrop_path} alt=''/>
</li>
)
});
Thanks for all the answers but I have actually maanged to sort it out with a bit of help from a friend. In my MovieList I returned a new Component called Movie for each component and there I make a call to API fro movie details using each of the movie details from my map function in MovieList component
Movielist
import React, { Component } from 'react';
import Movie from './Movie';
class MoviesList extends Component {
render() {
let results;
if(this.props.results) {
results = this.props.results.map((result, index) => {
return(
<Movie key={result.id} result={result} images={this.props.images}/>
)
});
}
return (
<div>
{results}
</div>
)
}
}
export default MoviesList;
Movie.js
import React, { Component } from 'react';
import MovieDetails from './MovieDetails';
class Movie extends Component {
constructor(props) {
super(props);
this.state = {
showComponent: false,
details: []
}
this.showDetails = this.showDetails.bind(this);
this.getDetails = this.getDetails.bind(this);
}
componentDidMount() {
this.getDetails();
}
getDetails() {
let request = new Request('https://api.themoviedb.org/3/search/movie?api_key=70790634913a5fad270423eb23e97259&query='+this.props.value+'');
fetch(request)
.then((response) => {
return response.json();
}).then((data) => {
let url = 'https://api.themoviedb.org/3/movie/'+ this.props.result.id +'?api_key=70790634913a5fad270423eb23e97259&append_to_response=videos,images';
return fetch(url)
}).then((response) => {
return response.json();
}).then((data) => {
this.setState({details: data});
});
}
showDetails(id) {
this.setState({showComponent: true}, () => {
console.log(this.state.details)
});
}
render() {
return(
<li ref={this.props.result.id} id={this.props.result.id} key={this.props.result.id} onClick={this.showDetails}>
{this.props.result.title}
<img src={this.props.images.base_url +`${this.props.images.poster_sizes?this.props.images.poster_sizes[0]: 'err'}` + this.props.result.backdrop_path} alt=''/>
{this.state.showComponent ? <MovieDetails details={this.state.details}/> : null}
</li>
)
}
}
export default Movie;

Resources