In react, how to display component only after all data is available? - javascript

I have a component that displays images. The component has a menu bar as well.
During initially server request, this component always shows the menu bar for a split second because the actually image is not loaded yet.
How to display the menu bar only after the image is ready?
EDITED:
I can determine when the URLs to the images are loaded and available. But how to tell if the actually image itself is ready?

You can do it like this:
function YourComponent () {
const [imgLoaded, setImgLoaded] = useState(false);
const handleImgLoad = () => {
setImgLoaded(true);
}
return(
<>
<img onLoad={handleImgLoad} src="..." alt="..." />
{imgLoaded ? <MenuBar /> : <></>}
</>
);
}

You can use partial rendering
for example
import React, { useEffect, useState } from 'react';
function App() {
const [data, setData] = useState(null);
useEffect(()=>{
setData(true);
}, []);
return (
<div>
{data && <div> after data is not null this will be visible</div>}
</div>
);
}
export default App;

You can set a state as below and load the menu based on this value;
const [ImageLoaded, setImageLoaded] = useState(false);

You can have a loading state set to true by default, this way:
const [loading, setLoading] = useState(true);
After you have all your data fetched, you set it to false:
setLoading(false)
And your render will be something like this:
return (
<div>
{loading ? <p>loading...</p> : <MyComponent/>}
</div>
)

Related

How do I use the output of one axios request as a dependency for another when rendering components in React?

I have been struggling with this for some time and I am not sure how to solve the issue.
Basically, I am trying to render some components onto my Index page, this is my code below:
App.js
import Index from "./Components/Index"
import axios from "axios"
export default function App() {
const [movieList, setMovieList] = React.useState([])
let featured = []
let coming = []
let showing = []
React.useEffect(() => {
console.log("Ran App Effects")
axios.get(`API_CALL_TO_GET_LIST_OF_MOVIES`)
.then(res =>{
setMovieList(res.data)
})
}, [])
return(
<div>
{movieList.map(movie =>{
if(movie.status === 'featured'){
featured.push(movie.api_ID)
} else if (movie.status === 'upcoming'){
coming.push(movie.api_ID)
} else{
showing.push(movie.api_ID)
}
})}
<Index featured={featured} coming={coming} showing={showing}/>
</div>
)
}
In the code above I am receiving an array of Objects and based on what is in their status I am putting them in some empty arrays and sending them as props into my Index component.
This is what my index component looks like:
import React from "react"
import Header from "./Header"
import Footer from "./Footer"
import MovieCard from "./MovieCard"
import axios from "axios"
export default function Index(props) {
const [featuredMovies, setFeaturedMovies] = React.useState([])
const [comingMovies, setComingMovies] = React.useState([])
//const featured = [419704,338762,495764,38700,454626,475557]
//const coming = [400160,514847,556678,508439,524047,572751]
React.useEffect(() => {
console.log("Ran Effect")
axios.all(props.featured.map(l => axios.get(`API_CALL_TO_GET_SPECIFIC_MOVIE/${l}`)))
.then(axios.spread(function (...res){
setFeaturedMovies(res)
}))
.catch((err) => console.log(err))
axios.all(props.coming.map(l => axios.get(`API_CALL_TO_GET_SPECIFIC_MOVIE/${l}`)))
.then(axios.spread(function (...res){
setComingMovies(res)
}))
.catch((err) => console.log(err))
}, [])
return(
<body>
<Header />
<section className="home">
<div className="container">
<div className="row">
<div className="col-12">
<a className="home__title">FEATURED MOVIES</a>
</div>
{ featuredMovies.map(movie =>{
return <MovieCard movie={movie} featured={true} />
}) }
{console.log(props.featured)}
</div>
</div>
</section>
<section className="home">
<div className="container">
<div className="row">
<div className="col-12">
<a className="home__title">COMING SOON</a>
</div>
{ comingMovies.map(movie =>{
return <MovieCard movie={movie} featured={false} />
})}
</div>
</div>
</section>
<Footer/>
</body>
)
}
The issue I am running into is, whenever I run the app for the first time it works fine but then when I hit the refresh button the components do not render anymore
The only time it re-renders when I refresh the page is when I uncomment,
//const featured = [419704,338762,495764,38700,454626,475557]
//const coming = [400160,514847,556678,508439,524047,572751]
and replace the props.featured.map and props.coming.map with featured.map and coming.map hence using the hard coded values and not the values passed in from the props.
Any help with this would be much appreciated as I am completely stuck and currently pulling my hair out.
I took the liberty to tinker with your code. In the example below I've rearranged the data into three sets with the help of useMemo and by checking the status property of each movie. It is important to keep any data related logic outside of the render logic.
I also moved around some of your HTML structure. You were outputting a <body> tag inside of a <div>. The outer layer should be in control of the outer HTML structure, so I moved that HTML to the App component.
import { useState, useEffect, useMemo } from 'react'
import Header from "./Components/Header"
import Footer from "./Components/Footer"
import Index from "./Components/Index"
import axios from "axios"
export default function App() {
const [movieList, setMovieList] = useState([])
const featuredMovies = useMemo(() => {
return movieList.filter(({ status }) => status === 'featured');
}, [movieList]);
const upcomingMovies = useMemo(() => {
return movieList.filter(({ status }) => status === 'upcoming');
}, [movieList]);
const showingMovies = useMemo(() => {
return movieList.filter(({ status }) => status !== 'featured' && status !== 'upcoming');
}, [movieList]);
useEffect(() => {
axios.get(`API_CALL_TO_GET_LIST_OF_MOVIES`)
.then(res =>{
setMovieList(res.data)
})
}, [])
return (
<body>
<Header />
<Index data={featuredMovies} title="Featured Movies" featured={true} />
<Index data={upcomingMovies} title="Coming Soon" />
<Index data={showingMovies} title="Showing Now" />
<Footer/>
</body>
)
}
Since we now have three sets of movies (featured, upcoming, and playing) it would also make sense to have three components that handle those data sets instead of having one that handles multiple. Each Index component gets its own data set and other props to render the movies within it.
import MovieCard from "./MovieCard"
export default function Index({ data, title, featured = false }) {
return (
<section className="home">
<div className="container">
<div className="row">
<div className="col-12">
<a className="home__title">{title}</a>
</div>
{data.map(movie => {
return <MovieCard movie={movie} featured={featured} />
})}
</div>
</div>
</section>
);
}

React - toggle text and class in an HTML element?

I am trying to create a system where I can easily click a given sentence on the page and have it toggle to a different sentence with a different color upon click. I am new to react native and trying to figure out the best way to handle it. So far I have been able to get a toggle working but having trouble figuring out how to change the class as everything is getting handled within a single div.
const ButtonExample = () => {
const [status, setStatus] = useState(false);
return (
<div className="textline" onClick={() => setStatus(!status)}>
{`${status ? 'state 1' : 'state 2'}`}
</div>
);
};
How can I make state 1 and state 2 into separate return statements that return separate texts + classes but toggle back and forth?
you can just create a component for it, create a state to track of toggle state and receive style of text as prop
in React code sandbox : https://codesandbox.io/s/confident-rain-e4zyd?file=/src/App.js
import React, { useState } from "react";
import "./styles.css";
export default function ToggleText({ text1, text2, className1, className2 }) {
const [state, toggle] = useState(true);
const className = `initial-style ${state ? className1 : className2}`;
return (
<div className={className} onClick={() => toggle(!state)}>
{state ? text1 : text2}
</div>
);
}
in React-Native codesandbox : https://codesandbox.io/s/eloquent-cerf-k3eb0?file=/src/ToggleText.js:0-465
import React, { useState } from "react";
import { Text, View } from "react-native";
import styles from "./style";
export default function ToggleText({ text1, text2, style1, style2 }) {
const [state, toggle] = useState(true);
return (
<View style={styles.container}>
<Text
style={[styles.initialTextStyle, state ? style1 : style2]}
onPress={() => toggle(!state)}
>
{state ? text1 : text2}
</Text>
</View>
);
}
This should be something you're looking for:
import React from "react"
const Sentence = ({ className, displayValue, setStatus }) => {
return (
<div
className={className}
onClick={() => setStatus((prevState) => !prevState)}
>
{displayValue}
</div>
);
};
const ButtonExample = () => {
const [status, setStatus] = React.useState(false);
return status ? (
<Sentence
className="textLine"
displayValue="state 1"
setStatus={setStatus}
/>
) : (
<Sentence
className="textLineTwo"
displayValue="state 2"
setStatus={setStatus}
/>
);
};
You have a Sentence component that takes in three props. One for a different className, one for a different value to be displayed and each will need access to the function that will be changing the status state. Each setter from a hook also has access to a function call, where you can get the previous (current) state value, so you don't need to pass in the current state value.
Sandbox

how can i make a component re render in react

so i'm creating my first fullstack website and once a user signs in it gets stored in the localStorage and i want to display the name of the user in my header once he is logged in but my header is not re rendering so nothing happens : this is the header before logging in
header
and this is how i want it to Be after signing in :
header after logging in this is my Layout code:
import "../assets/sass/categoriesbar.scss";
import Header from "./Header/Header";
const Layout = (props) => {
return (
<>
<Header/>
<main>
{ props.children}
</main>
</>
);
}
export default Layout;
and this is the toolBar in my Header :
const ToolBar = () => {
const history = useHistory();
let currentUser= JSON.parse(localStorage.getItem("user-info"));
const logoutHandler = () => {
localStorage.clear("user-info");
history.push("/login");
};
return (
<>
<div className={classes.NavigationBar}>
<h1>
<Link to="/">Pharmashop</Link>
</h1>
<NavLinks logout={logoutHandler}/>
{localStorage.getItem("user-info")?
<h5>Welcome {currentUser.name} !</h5>
:
<RegisterButton />
}
</div>
</>
);
};
export default ToolBar;
please help me it's frustrating
PS: this is my first stackoverflow question sorry if it's unorganized and unclear and sorry for my bad english.
Hazem, welcome to Stack Overflow.
In react, if you want the component to re-render when some data changes, that info must be in the component state. In your code the current user is a const, not bind to the component's state. This is how it could auto re-render when the user logs in:
const ToolBar = () => {
const [currentUser, setCurrentUser] = useState(JSON.parse(localStorage.getItem("user-info")));
const logoutHandler = () => {
localStorage.clear("user-info");
history.push("/login");
};
return (
<>
<div className={classes.NavigationBar}>
<h1>
<Link to="/">Pharmashop</Link>
</h1>
<NavLinks logout={logoutHandler}/>
{currentUser?
<h5>Welcome {currentUser.name} !</h5>
:
<RegisterButton />
}
</div>
</>
);
};
export default ToolBar;
See more about state in the official documentation.

How to add a priority to react components?

I want my Home component to load first and then everything else? How can I achieve this?
Or can I load resources in the background while I'm showing a spinner and then show the whole page? Something like this..
useEffect(() => {
setTimeout(() => {
setIsLoading(false);
}, 2500);
}, []);
return isLoading ? (
<Spinner />
) : (
<div className="App">WholePage</div>
What I would do is use the useEffect hook for the priority component that you want to load first and set a state in there to load the remaining components.
My code would look something like this:
function App(){
const [homeLoaded,setHomeLoaded] = useState(false)
const getHomeLoaded = (homeLoaded) => {
setHomeLoaded(homeLoaded)
}
return(
<>
<Home gethomeLoaded = {getHomeLoaded}/>
{homeLoaded ? <OtherComponents>:null}
</>
)
}
The home component would look something like this:
function Home(){
useEffect(() => {
props.getHomeLoaded(true)
}, []);
return(
<div>Your home content goes here</div>
)
}
What I am essentially doing is passing a state to the parent component from Home so that I can set homeLoaded to true only after Home component is loaded

How can I access a state value done in react hooks in another js file

I am working on a search bar in react which in another file will make a call to the unsplash-api,
I have a search bar component and I am thinking of doing the api call in the main file or if other wise advised in another file in the src folder
So far I have setup a component and setup the initial hook but I dont know how to go forward
import React, { useState } from 'react';
import './SearchBar.css';
const SearchBar = () => {
const [search, setSearch] = useState('');
return (
<form>
<input className="Search" placeholder="Search Images" />
<button type="submit" id="submit" className="search-button">
<i className="icon">search</i>
</button>
</form>
);
};
export default SearchBar;
See if that's what you're looking for. I replaced the form for a div to avoid submit behavior in the snippet. But the logic is the same. You'll need to do event.preventDefault on the submission event.
function mockSearchAPI(searchValue) {
return new Promise((resolve,reject) => {
setTimeout(() => resolve('Search results for: ' + searchValue), 2000);
});
}
function App() {
const [searchResults,setSearchResults] = React.useState('');
const [loading, setLoading] = React.useState(false);
function doSearch(searchValue) {
setLoading(true);
mockSearchAPI(searchValue)
.then((results) => {
setSearchResults(results);
setLoading(false);
});
}
return(
<React.Fragment>
<SearchBar
doSearch={doSearch}
/>
{loading &&
<div>Loading...</div>
}
{searchResults &&
<div>{searchResults}</div>
}
</React.Fragment>
);
}
const SearchBar = (props) => {
const [search, setSearch] = React.useState('');
function onClick() {
console.log(search);
props.doSearch(search);
}
return (
<div>
<input
//className="Search"
placeholder="Search Images"
onChange={(event)=>setSearch(event.target.value)}
/>
<button
//type="submit"
//id="submit"
//className="search-button"
onClick={onClick}
>
<i className="icon">search</i>
</button>
</div>
);
};
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
From my understanding you should be able to pass the state in Hooks (from the search bar) to the parent component in these methods.
Use Redux and create a global store with the required state
variable. Then from the search component you will need to update the
state variable in the Redux store, then load this state variable in
the parent component.
Create a state variable from the parent component and have it
passed to the search component as a prop. Then from the search
component, you will update this prop.
I am not not 100% sure if method 2 will work as expected but I am pretty sure method 1 will work.

Categories