I am fresh to react and useState hooks (still learning). I want to create show more/less button with use of an Array of images and React hooks. I import the images into div, I wanted to set button on the last and the show the images on the click of button.
I am getting the error:
text.slice is not function
The thing is, the code is written with use of function component.
here's my code:
import React from 'react';
import { useState } from 'react';
import '../assets/css/Product.css';
const ReadMore = ({ children }) => {
const text = children;
const [isReadMore, setIsReadMore] = useState(true);
const toggleReadMore = () => {
setIsReadMore(!isReadMore);
};
return (
<p className='text'>
{isReadMore ? text.slice(0, 150) : text}
<span onClick={toggleReadMore} className='read-or-hide'>
{isReadMore ? '...read more' : ' show less'}
</span>
</p>
);
};
export const Product = () => {
const card_image = [
{
image: 'CLT_Food_BeverageBar.jpg',
title: 'Charlotte',
subtitle: '(CLT)',
button: 'Explore Lounge',
},
{
image: 'Centurion_Cropped_0001_Bar.jpg',
title: 'Dallas',
subtitle: '(DFW)',
button: 'Explore Lounge',
},
{
image: 'DEN_GameRoom-LR_1200x540.jpg',
title: 'Denver',
subtitle: '(DEN)',
button: 'Explore Lounge',
},
{
image: 'IAH_Bar&Buffet_1200x600.jpg',
title: 'Houston',
subtitle: '(IAH)',
button: 'Explore Lounge',
},
{
image: 'amxtcl_Lounge_01_cmyk_1200x600.jpg',
title: 'Las Vegas',
subtitle: '(LAS)',
button: 'Explore Lounge',
},
{
image: 'LAX_hero.jpg',
title: 'Los Angeles',
subtitle: '(LAX)',
button: 'Explore Lounge',
},
{
image: 'LoungeAreaTalent1200x600.jpg',
title: 'Miami',
subtitle: '(MIA)',
button: 'Explore Lounge',
},
{
image: 'JFK_Carousel_3.jpg',
title: 'New York',
subtitle: '(JFX)',
button: 'Explore Lounge',
},
];
return (
<div>
<div className='container'>
<ReadMore>
<div className='row introduction'>
{card_image.map((card) => (
<div className='col-lg-3 pt-5'>
<div
className='location_card'
style={{
backgroundImage: `url(${process.env.REACT_APP_ASSET_URL}/card_image/${card.image})`,
objectFit: 'cover',
}}>
<div className='location-overly'>
<h3 className='h2'>
{card.title}
<br />
{card.subtitle}
</h3>
<button
type='button'
class='btn_product '>
{card.button}
</button>
</div>
</div>
</div>
))}
</div>
</ReadMore>
</div>
</div>
);
};
I think you should use conditional rendering, this means that when a state changes, your UI also changes. Sorry, I don't think I explained it that well, so here's some example code.
import * from x "xyz xyz";
const App = () => {
const [showMore, setShowMore] = useState(false);
if(showMore){
return(
<MoreStuff/>
);
}
return(
<DefaultStuff/>
);
}
Resources:
https://www.w3schools.com/react/react_conditional_rendering.asp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.