React - JSON file won't render - javascript

I am building out a row of react-icons. When selected the icons to display content from a static .JSON file. I am trying to combine the following events:
Change color when clicked
Change/Switch between the static .JSON content when clicked.
I tried to combine the 2 actions inline based on this post.
However, only the color changes, not the .JSON data.
Thank you in advance, any help or guidance would be appreciated.
Here is my code below:
import React, { useState } from "react";
import "../Styles/arrow.css";
import { BsFillPeopleFill } from "react-icons/bs";
import { GiLinkedRings } from "react-icons/gi";
import { GoArrowRight } from "react-icons/go";
function Icon(props) {
const handleClick = (messageKey) => () => props.setSelectedIcon(messageKey);
const [bg, changeBGColor] = React.useState(1);
return (
<div className="icon-arrow">
<div className="arrow">
<div className="arrow-line" />
<div className="arrow-icon">
<GoArrowRight />
</div>
</div>
<div className="icons">
<GiLinkedRings
className="rings"
onClick={() => {
handleClick("rings");
changeBGColor(1);
}}
style={{
backgroundColor: bg === 1 ? "#e3e1dc" : "#ae7a67",
}}
/>
<BsFillPeopleFill
className="family"
onClick={() => {
handleClick("family");
changeBGColor(2);
}}
style={{
backgroundColor: bg === 2 ? "#e3e1dc" : "#ae7a67",
}}
/>
</div>
</div>
);
}
export default Icon;
My .JSON Data: iconmessage.json
{
"rings": {
"image": "rings.jpg",
"title" : "Rings",
"message":"Lorem Ipsum"
},
"family": {
"image": "family.jpg",
"title" : "Family is essential",
"message":"Lorem Ipsum"
}
}
Icons/.JSON being pulled from IconMessage.JSX
import React from "react";
import "../Styles/iconmessage.css";
import messages from "../Static/iconmessage.json";
function IconMessage(props) {
const message = messages[props.selectedIcon]
return (
<div className="icon-message">
<div className="title-message">
<div className="title">{message.title}</div>
<div className="message">{message.message}</div>
</div>
<div className="image">
<img src={`/images/${message.image}`} alt="" srcset="" />
</div>
</div>
)
}
export default IconMessage

What you did what correct from the onClick perspective. I'd say that the problem is the value you pass. Are you sure that when you pass "rings" to selectedIcon, it should render the JSON as you'd wish?
I think the problem is that you access messages.title, messages.message, instead of messages.image.title, messages.image.message.

Related

pass some value back to parent component in next js

In my nextjs project I'm displaying posts from different tags and each post have many tags. I have a post_by_tags component and I'm using that component in different sections on home page to display posts from different tags. I don't want to show repeating content as some posts have same tags and I have a array to keep post ids that are visible to website. Now I want a way to keep post ids from child component to send back to parent component which updates the array so I can filter out these posts from post object. I find some examples but mostly these are tied with onclick or onchange something like that.
Here is my parent component code:
import Head from 'next/head'
import Image from 'next/image'
import Layout from '../components/Layout';
import Hero from '../components/Hero';
import Developed_country from '../components/Developed_country';
import Posts_by_tags from '../components/Post_by_tags';
import Attorneys from '../components/Attorneys';
import Business_formation from '../components/Business_formation';
import Case from '../components/Case';
export async function getServerSideProps(context) {
// Fetch data from external API
const res = await fetch(`https://dashboard.toppstation.com/api/blogs`);
const data = await res.json();
// Pass data to the page via props
return {
props: { blogs:data}
}
}
export default function Home({blogs}) {
const blog_post_id = [];
const pull_data = (data) => {
console.log(data); // LOGS DATA FROM CHILD)
}
return (
<Layout>
<Hero/>
<Developed_country/>
<Posts_by_tags tag='business' bg='bg_grey' posts={blogs} func={pull_data}/>
<Business_formation/>
<Attorneys/>
<Posts_by_tags tag='png' bg='bg_white' posts={blogs} />
<Posts_by_tags tag='image' bg='bg_grey' posts={blogs} />
<Posts_by_tags tag='png' bg='bg_white' posts={blogs} />
<Case/>
</Layout>
)
}
Child component:
import Blogimg from '../public/img/blog.png';
import btn_arrow from '../public/img/btn_arrow.svg';
import styles from '../styles/Home.module.css';
export default function Posts_by_tags(props){
props.func('My name is xyz');
const bg = props.bg;
let align = ['start','center','end'];
let post_tags = [];
const postIds= [];
const blog_posts = props.posts.filter(bpost=>{
bpost.tags.forEach(tag => {
if(tag.toLowerCase() === props.tag){
return postIds.push(bpost._id);
}
})
});
const posts = props.posts.filter(p => {
if( (postIds.indexOf(p._id) !== -1) && p.visibility==true){
return p;
}
}).slice(0,3);
return(
<>
{posts.length == 0 ? null :(
<section id={styles.postsbytags} className={bg}>
<div className='wrapper'>
<div className="container section posts_by_tags section_ptb">
<div className='row'>
<div className='col-sm-12'>
<h3 className={`${styles.heading3} text-center`}><span className={`${styles.heading3span} ${bg}`}>{props.tag}</span></h3>
</div>
</div>
<div className='row pt_100'>
{posts.map( (post, index) =>(
<div id={`post-${post._id}`} className={`col-md-4 d-flex justify-content-md-${align[index]} justify-content-center`} key={post._id}>
<div className={styles.blog_post}>
<div className={`${styles.blog_image} text-center`}>
<span className={styles.blog_tag}>{props.tag}</span>
<Image className="img-fluid" src={post.image} alt={post.title} width={450} height={400} layout='responsive'/>
</div>
<div className='blog_content'>
<h4 className={styles.blog_title}>{post.title}</h4>
<p className={styles.blog_desc}>{post.description.split(' ').slice(0, 10).join(' ')}...</p>
</div>
</div>
</div>
))}
</div>
<div className='row'>
<div className='col-sm-12'>
<div className='blog_category pt_50'>
<a href="" className={ `btn ${styles.btn_tags} `}>See More {props.tag} <i className={styles.btn_icon}><Image src={btn_arrow} alt="btn-icon"/></i></a>
</div>
</div>
</div>
</div>
</div>
</section>
)}
</>
);
}```

React TypeError: setAvailability is not a function

I made a Christmas gifts list with React and I would like to change the available prop from true to false when a user clicks on "I want to offer this gift" but there is an error and I don't know why. The error is : TypeError: setAvailability is not a function
Here is my Book component:
function Book({available, setAvailability}) {
return (
<div className="gift-item-availability">
{ available ? <p className="gift-item-avail">Available</p> : <p className="gift-item-unavail">Booked</p> }
{ available ? <p className="gift-item-action" onClick={()=> setAvailability(false)}>I want to offer this gift</p> : null }
</div>
)
}
export default Book
Here is my Gift Component :
import {React, useState} from "react"
import '../styles/GiftItem.css'
import CurrencyFormat from 'react-currency-format';
import Book from "./Book";
function GiftItem({image, name, available, lien1, lien2, lien3, price, category}) {
const setAvailability = useState({available})
return (
<li className='gift-item'>
<CurrencyFormat value={price} displayType={'text'} thousandSeparator={true} suffix={'€'} renderText={value => <div className="gift-item-price">{value}</div>} />
<div className="gift-item-cover">
<img className="gift-item-cover" src={ window.location.origin + "/img/"+ image } alt={ name } />
</div>
<h2 className="gift-item-name">{ name }</h2>
<div className="gift-item-details">
<Book available={available} setAvailability={setAvailability} />
<div className="gift-item-link">
{ lien3 ? <img src={ window.location.origin + "/img/amazon.png"} alt="Amazon" /> : null }
{ lien1 ? <img src={ window.location.origin + "/img/picwictoys.png"} alt="Pic Wic Toys" /> : null }
{ lien2 ? <img src={ window.location.origin + "/img/king_jouet.png"} alt="King Jouet" /> : null }
</div>
</div>
</li>
)
}
export default GiftItem
And the complete List Component :
import {React, useState} from "react"
import { giftList } from '../data/giftList'
import '../styles/ShoppingList.css'
import GiftItem from './GiftItem'
import Categories from "./Categories"
function ShoppingList() {
const [activeCategory, setActiveCategory] = useState('')
const categories = giftList.reduce(
(acc, gift) =>
acc.includes(gift.category) ? acc : acc.concat(gift.category),
[]
)
return (
<div className='shopping-list'>
<Categories
categories={categories}
setActiveCategory={setActiveCategory}
activeCategory={activeCategory}
/>
<ul className='gift-list'>
{giftList.map(({image, name, available, lien1, lien2, lien3, price, category}) => (
!activeCategory || activeCategory === category ? (
<GiftItem
image={image}
name={name}
available={available}
lien1={lien1}
lien2={lien2}
lien3={lien3}
price={price}
key={name}
/>
) : null
))}
</ul>
</div>
)
}
export default ShoppingList
Thanks a lot for your help !!!
The useState hook returns an array containing two elements, not a function. The first item in the array is the value, the second item is the function used to update that value. Typically you'd destructure it like this:
const [availability, setAvailability] = useState({available})
The useState documentation has some more helpful information.
It should be const [availability, setAvailability] = useState(true);
useState return an array not the function.
you can then use setAvailability(false) to set availability state as false.

ReactJs Hiding Some HTML depend on situation

I want to make the price tag also some other HTML contents hide/show depending on some data entry.
for example, if I get True it should be visible prices if it's gonna be False it must hide.
I'm sharing some code of my pages please give me ideas.
Thank you.
// react
import React from 'react';
// third-party
import classNames from 'classnames';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
// application
import AsyncAction from './AsyncAction';
import Points from './Points';
import { cartAddItem } from '../../store/cart';
import { Quickview16Svg } from '../../svg';
import { quickviewOpen } from '../../store/quickview';
import { url } from '../../services/utils';
function ProductCard(props) {
const {
product,
layout,
quickviewOpen,
cartAddItem,
} = props;
const containerClasses = classNames('product-card', {
'product-card--layout--grid product-card--size--sm': layout === 'grid-sm',
'product-card--layout--grid product-card--size--nl': layout === 'grid-nl',
'product-card--layout--grid product-card--size--lg': layout === 'grid-lg',
'product-card--layout--list': layout === 'list',
'product-card--layout--horizontal': layout === 'horizontal',
});
let badges = [];
let image;
let price;
let features;
if (product.badges.includes('sale')) {
badges.push(<div key="sale" className="product-card__badge product-card__badge--sale">Sale</div>);
}
if (product.badges.includes('hot')) {
badges.push(<div key="hot" className="product-card__badge product-card__badge--hot">Hot</div>);
}
if (product.badges.includes('new')) {
badges.push(<div key="new" className="product-card__badge product-card__badge--new">New</div>);
}
badges = badges.length ? <div className="product-card__badges-list">{badges}</div> : null;
if (product.images && product.images.length > 0) {
image = (
<div className="product-card__image product-image">
<Link to={url.product(product)} className="product-image__body">
<img className="product-image__img" src={product.images[0]} alt="" />
</Link>
</div>
);
}
if (product.discountPrice) {
price = (
<div className="product-card__prices">
<span className="product-card__new-price"><Points value={product.price} /></span>
{' '}
<span className="product-card__old-price"><Points value={product.discountPrice} /></span>
</div>
);
} else {
price = (
<div className="product-card__prices">
<Points value={product.price} />
</div>
);
}
if (product.attributes && product.attributes.length) {
features = (
<ul className="product-card__features-list">
{product.attributes.filter((x) => x.featured).map((attribute, index) => (
<li key={index}>{`${attribute.name}: ${attribute.values.map((x) => x.name).join(', ')}`}</li>
))}
</ul>
);
}
return (
<div className={containerClasses}>
<AsyncAction
action={() => quickviewOpen(product.slug)}
render={({ run, loading }) => (
<button
type="button"
onClick={run}
className={classNames('product-card__quickview', {
'product-card__quickview--preload': loading,
})}
>
<Quickview16Svg />
</button>
)}
/>
{badges}
{image}
<div className="product-card__info">
<div className="product-card__name">
<Link to={url.product(product)}>{product.name}</Link>
<br />
<br />
</div>
{features}
</div>
<div className="product-card__actions">
<div className="product-card__availability">
Availability:
<span className="text-success">In Stock</span>
</div>
{price}
<div className="product-card__buttons">
<AsyncAction
action={() => cartAddItem(product)}
render={({ run, loading }) => (
<React.Fragment>
<button
type="button"
onClick={run}
className={classNames('btn btn-primary product-card__addtocart', {
'btn-loading': loading,
})}
>
Add To Cart
</button>
<button
type="button"
onClick={run}
className={classNames('btn btn-secondary product-card__addtocart product-card__addtocart--list', {
'btn-loading': loading,
})}
>
Add To Cart
</button>
</React.Fragment>
)}
/>
</div>
</div>
</div>
);
}
ProductCard.propTypes = {
/**
* product object
*/
product: PropTypes.object.isRequired,
/**
* product card layout
* one of ['grid-sm', 'grid-nl', 'grid-lg', 'list', 'horizontal']
*/
layout: PropTypes.oneOf(['grid-sm', 'grid-nl', 'grid-lg', 'list', 'horizontal']),
};
const mapStateToProps = () => ({});
const mapDispatchToProps = {
cartAddItem,
quickviewOpen,
};
export default connect(
mapStateToProps,
mapDispatchToProps,
)(ProductCard);
Here I want to hide prices in some onload situations. This is my homepage Carousel.
You can use code like this. It will only render the component if the boolean evaluates to a truthy value.
const { isVisible } = this.props; // Or wherever you want to get your boolean from
return (
<div>
{isVisible && <MyComponent />}
</div>
You refer to Conditional rendering, there are a couple ways to do that:
<div>
{someCondition && <p>The condition is true</p>}
</div>
Or if you want a if else rendering:
<div>
{someCondition ? <p>The condition is true</p> : <p>The condition is false</p>}
</div>
You can find more info in react docs

Having a problem loading in data to child component in react

I am building a gallery where you click on the image and it will load in a separate component using props, this image is a URL, taken from a hard-coded array, where the src is loaded as a background image via CSS. My challenge is connecting the data to that component. I have tried connecting the data from parent to child with callbacks, but no luck. I think what I am trying to do is connect components sideways, and I don't want to use redux, as I am not familiar.
Note: I am aware you can just load the image in GalleryContainer.js using window.location.href = "props.src/", however, I want the image to load in the Image component that will act as a container to hold the image giving the user other options such as downloading the image, etc...
Note: I have tried importing the Image component in Gallery.js and rendering it like so: <Image src={props.src} id={props.id}/>, and I find the data connects just fine, but this does not help keep the component separate.
What I have already :
I have a route in app.js that allows me to go to the image route path just fine it’s loading in the url from props.src in the image component that is my challenge
UPDATE: SOLVED Click here to see the solution!
Here is the code:
GalleryList.js
import Gallery from "./Gallery";
import Header from "./UI/Header";
import Footer from "./UI/Footer";
import styles from "./Gallery.module.css";
const DUMMY_IMAGES = [
{
id: "img1",
src: "https://photos.smugmug.com/photos/i-vbN8fNz/1/X3/i-vbN8fNz-X3.jpg",
},
{
id: "img2",
src: "https://photos.smugmug.com/photos/i-fSkvQJS/1/X3/i-fSkvQJS-X3.jpg",
},
{
id: "img3",
src: "https://photos.smugmug.com/photos/i-pS99jb4/0/X3/i-pS99jb4-X3.jpg",
},
];
const GalleryList = () => {
const imagesList = DUMMY_IMAGES.map((image) => (
<Gallery id={image.id} key={image.id} src={image.src} />
));
return (
<>
<Header />
<ul className={styles.wrapper}>
<li className={styles.list}>{imagesList}</li>
</ul>
Home
<Footer />
</>
);
};
export default GalleryList;
Gallery.js
import GalleryConatiner from "./UI/GalleryContainer";
import styles from "./Gallery.module.css";
const Gallery = (props) => {
return (
<>
<div className={styles["gal-warp"]}>
<GalleryConatiner id={props.id} key={props.id} src={props.src} />
</div>
</>
);
};
export default Gallery;
GalleryContainer.js
import styles from "../Gallery.module.css";
const GalleryConatiner = (props) => {
const selectedImg = () => {
if (props.id) {
// window.location.href = `image/${props.src}`;
window.location.href = "image/"
}
};
return (
<ul>
<li className={styles["gallery-list"]}>
<div
onClick={selectedImg}
className={styles["div-gallery"]}
style={{
backgroundImage: `url(${props.src}`,
height: 250,
backgroundSize: "cover",
}}
></div>
</li>
</ul>
);
};
export default GalleryConatiner;
Image.js
import styles from "./Image.module.css";
const Image = (props) => {
return (
<section>
<h1 className={styles["h1-wrapper"]}>Image:{props.id}</h1>
<div className={styles.wrapper}>
<div
className={styles["image-container"]}
style={{
backgroundImage: `url(${props.src}`,
}}
></div>
</div>
</section>
);
};
export default Image;
You should be able to use the router Link to pass data via "state" on the to property.
From React Router's documentation:
<Link
to={{
pathname: "/images",
state: { imgUrl: props.src }
}}
/>

Map inside map in react ( one is local array of images and the other is title from json )

As being designer and novice to react, I developed code in which local array is displaying as image and json data as title. Titles are working fine but images are not displaying and showing all of arrays in src attribute.
I have used Axios.get() to fetch data from the server.
I am missing out in logic somewhere while developing map inside map. I would be grateful for getting help.
EDIT : I want one image with one title.
CommonMeds.js
import React, { Component } from 'react';
import './CommonMeds.scss';
import MedSection from '../../Components/MedSection/MedSection';
import Axios from 'axios';
class CommonMeds extends Component {
state = {
MedTitle: [],
TitleImg: [
{ imageSrc: require('../../../../images/medstype_1.svg') },
{ imageSrc: require('../../../../images/medstype_2.svg') },
{ imageSrc: require('../../../../images/medstype_3.svg') },
{ imageSrc: require('../../../../images/medstype_4.svg') },
{ imageSrc: require('../../../../images/medstype_5.svg') },
{ imageSrc: require('../../../../images/medstype_6.svg') },
{ imageSrc: require('../../../../images/medstype_7.svg') },
{ imageSrc: require('../../../../images/medstype_8.svg') },
{ imageSrc: require('../../../../images/medstype_9.svg') },
{ imageSrc: require('../../../../images/medstype_10.svg') },
]
};
componentDidMount() {
const medInfo = Axios.get('URL OF JSON DATA');
medInfo.then( response => {
this.setState({MedTitle: response.data.result});
});
}
render() {
const Meds = this.state.MedTitle.map(med => {
const imglable = this.state.TitleImg.map(src => {
return src.imageSrc;
})
return <MedSection
Title={med.medicationCategory}
src = {imglable}
/>;
});
return(
<div className="container">
<h3 className="text-left">Common Medicines with Categories</h3>
<hr />
{Meds}
</div>
);
}
}
export default CommonMeds;
MedSection.js
import React from 'react';
import './MedSection.scss';
import MedicineList from '../MedicineList/MedicineList';
const MedSection = (props) => {
return (
<div className="col-12">
<div className="row">
<div className="col-12 col-md-3 col-lg-2 px-0">
<div className="c-medsimg-box py-4 px-2">
<img src={props.src} alt="Medication Type Icon" className="img-fluid" />
<h5 className="mt-3" key={props.key}>{props.Title}</h5>
</div>
</div>
<div className="col-12 col-md-9 col-lg-10">
<div className="h-100 d-flex align-items-center">
<ul className="c-medslist-ul pl-0 mb-0">
<MedicineList />
</ul>
</div>
</div>
</div>
<hr />
</div>
)
}
export default MedSection;
You are currently creating an array of images for each MedTitle. You could instead take the entry from TitleImage that has the same index as the current med in your loop instead.
You can also make it safe by using the % operator, so that if your MedTitle array is larger than your TitleImage array, you will still get an image.
const Meds = this.state.MedTitle.map((med, index) => {
const src = this.state.TitleImg[index % this.state.TitleImg.length].imageSrc;
return <MedSection Title={med.medicationCategory} src={src} />;
});
As long as length of both arrays are same, it will work.
Try using this.
const imglable = this.state.TitleImg.map(src => {
return src.imageSrc;
})
const Meds = this.state.MedTitle.map((med, index) => {
return <MedSection
Title={med.medicationCategory}
src = {imglable[index]}
/>;
});

Categories

Resources