React JS returning as HTML - reactjs

I know that I am horrible at React JS but I couldn't find anything specific for this one
I want to return this function into my tsx file and write it on screen but it should be in a component
function getUsers() {
const Users = ({ users } : { users:any }) => {
return (
<div>
{users.map((user : any, i : any) => (
<div className="card">
<img className="card-img-top" src={userPic} alt="Card image cap" />
<div className="card-body">
<h5 className="card-title">{user.name}</h5>
<h6 className="card-subtitle mb-2 text-muted">{user.email}</h6>
</div>
</div>
))}
</div>
)
};
return Users;
}```

ReactDOMServer has a function called renderToStaticMarkup that can take some JSX and return the static HTML as a string.
The issue you'll likely have is it isn't formatted with indentation etc.
Your function will probably look something like this:
const generateHtml = (users: any[]) => {
const html = (
<div>
{users.map((user: any, i: any) => (
<div className="card" key={i.toString()}>
<img className="card-img-top" src={user.userPic} alt="Card image cap" />
<div className="card-body">
<h5 className="card-title">{user.name}</h5>
<h6 className="card-subtitle mb-2 text-muted">{user.email}</h6>
</div>
</div>
))}
</div>
);
return ReactDOMServer.renderToStaticMarkup(html);
};
The resulting HTML is:
<div><div class="card"><img class="card-img-top" src="1.png" alt="Card image cap"/><div class="card-body"><h5 class="card-title"></h5><h6 class="card-subtitle mb-2 text-muted"></h6></div></div></div>

Related

how to get product id from sanity.io for every button that clicked in reactjs?

i'm trying to make product detail page but i am struggle to solve this problem. I fetch products from sanity.io and return the data using map. i want whenever i click the detail btn it's direct me to detail page and get the information of product
here is my code
const Products = () => {
const [allProducts, setAllProducts] = useState([]);
useEffect(() => {
async function getAllProducts() {
const allProduct = '*[_type == "product"]';
const response = await client.fetch(allProduct);
setAllProducts(await response);
}
getAllProducts();
}, []);
return (
<>
<Navbar />
<div className="container-fluid ">
<div className="row g-3 mb-5 ">
{allProducts.map((product) => {
console.log(product);
return (
<div className="col-12 col-md-3" key={product._id}>
<div className="card">
<img
src={urlFor(product.image[0])}
className="card-img-top"
alt={product.name}
/>
<div className="card-body">
<h1>${product.price}</h1>
<h5 className="card-title">{product.name} </h5>
<h6>{product.detail}</h6>
<div>
<Link to="/detail" className="btn btn-danger m-2">
Detail
</Link>
</div>
</div>
</div>
</div>
);
})}
</div>
<Footer />
</div>
</>
);
};

reactJS doesn't render the data after being fetched in useEffect hook

I have an API using axios which will fetch a list of products. I have called it inside useEffect() hook with [] as the second argument. I check the data before running into return command of the functional component and the data is there, but my ProductCard component are not rendered. Could you please help me with this?
FeaturedProducts.js
const FeaturedProducts = (props) => {
const [productList, setProductList] = useState([]);
// const productList = useSelector(productListSelector);
useEffect(async () => {
let rs = await fetchFeaturedProducts();
setProductList(rs);
}, []);
console.log(productList);
return (
<div className="container-fluid pt-5">
<div className="text-center mb-4">
<h2 className="section-title px-5"><span className="px-2">Featured</span></h2>
</div>
<div className="row px-xl-5 pb-3">
{
productList.map(product => {
<ProductCard id={product.id} name={product.name} price={product.price} img="abc"/> // need img={product.img}
})
}
</div>
</div>
);
}
export default FeaturedProducts;
fetchFeaturedProducts()
const fetchFeaturedProducts = async () => {
try {
let response = await AxiosClient.post("/product/search", {
searchType: "desc",
searchBy: "average_rating"
});
let data = response.data.data;
return data;
}
catch (error) {
raiseErrorMessages(error.response.data.errors);
return [];
}
}
ProductCard.js
const ProductCard = (props) => {
const detailUrl = "/product?id=" + toString(props.id);
return (
<div className="col-lg-3 col-md-6 col-sm-12 pb-1">
<div className="card product-item border-0 mb-4">
<div className="card-header product-img position-relative overflow-hidden bg-transparent border p-0">
<img className="img-fluid w-100" src={props.img} alt="" />
</div>
<div className="card-body border-left border-right text-center p-0 pt-4 pb-3">
<h6 className="text-truncate mb-3">{props.name}</h6>
<div className="d-flex justify-content-center">
<h6>{props.price}</h6>
{/* <h6 className="text-muted ml-2"><del>{props.price}</del></h6> */}
</div>
</div>
<div className="card-footer d-flex justify-content-between bg-light border">
<i className="fas fa-eye text-primary mr-1" />View Detail
<i className="fas fa-shopping-cart text-primary mr-1" />Add To Cart
</div>
</div>
</div>
)
}
export default ProductCard;
Thank you for your precious time.
that happens because you missed a return when you mapped your data
// .....
{
productList.map(product => {
return (<ProductCard id={product.id} name={product.name}
price={product.price} img="abc"/>) // need img=
{product.img}
})
}
or you can use ()
{
productList.map(product => (
<ProductCard id={product.id} name={product.name}
price={product.price} img="abc"/>) // need img=
{product.img})
}

showing the applicants of a job in reactjs using id

Iam trying to make a react application whereby users are applying for a job and also creating a report that will show the profile of the users who have applied for the job. Iam welcome to any ideas that can be given to me since I would like to have a logic on how to implement that.
Here is my code below:
DriverCard.js
import React from "react";
import member2 from "../../../dist/images/user2.png";
const DriverCard = ({cardValues}) => {
return (
<>
<div className="col-lg-3 col-md-3 col-sm-4 col-6 p-0 mb-5">
<div className="text-center">
<div className="mb-2">
<img
src={cardValues ? `${cardValues.location.title}` : member2}
className="rounded-circle"
height="85px"
width="85px"
alt="members"
/>
</div>
<h6 className="mb-0 textHeading">
{cardValues ? cardValues.name : `John Doe`}
</h6>
<span className="text-muted textStyle"> #JohntheD 5h</span>
<hr
style={{
width: "50%",
marginTop: 4,
marginBottom: 1,
}}
/>
<h6 className="textStyle mt-1">
{cardValues ? `${cardValues.licenseAge} +years licence` : `NA`}
</h6>
<h6 className="textStyle">
{cardValues ? `${cardValues.experience} +years experience` : `NA`}
</h6>
</div>
</div>
</>
);
};
export default DriverCard;
This is the report file that is suppossed to show the jobcard and the profile for the applicants.
import React, { useEffect, useState } from "react";
import {useHistory} from "react-router-dom";
import map from "lodash/map"
import { getSpecificJobCard } from "../../Api/index";
import arrowBack from "../../dist/images/arrowBack.svg";
import DriverCard from "./Job_Components/DriverCard";
import JobCardDetails from "./Job_Components/JobCardDetails";
import NextPageButtons from "../Main/DashBoard_Buttons/NextPageButtons";
const JobDetails = ({jobpostId}) => {
const [jobCard, setjobCard] = useState([]);
const history = useHistory();
console.log("param val",jobpostId);
useEffect(() => {
(async () => {
let jobCardRespData = await getSpecificJobCard(jobpostId);
setjobCard(jobCardRespData);
console.log("jobcard response:", jobCardRespData);
})();
}, []);
console.log("resp list ----- ", jobCard);
return (
<div className="">
<div className="col-md-10 m-auto">
<span style={{ cursor: "pointer" }} className="">
<img src={arrowBack} alt="" className="img-fluid" />
</span>
<div className="row">
<div className="col-lg-4 mt-5">
<div className="row">
{}
<JobCardDetails job={jobCard} />
</div>
</div>
<div className="col-lg-8 mt-5">
<div className="row">
<DriverCard/>
{/* <DriverCard /> */}
</div>
</div>
</div>
<div className="row">
<div className="col-lg-12">
<div className="row">
</div>
</div>
</div>
</div>
<div className="col-lg-12 my-3 border-top">
<NextPageButtons/>
</div>
</div>
);
};
export default JobDetails;

How to render popup for specific element in react?

I have a list of items and for every item (.item-wrapper) i want to get a video popup with unique videoId.
I have prepared videoPopup component for that but for every item I get the the last 'videoId' of 'elements' array (the same videoId for every item).
On the other hand when I am not using PopupVideo component and just loop through items iframes I get the proper id for specific item - that is just for test purpose.
(The commented out line)
I am super new to React so I am aware that problem may be also super easy to solve.
Thanks!
Code for displaying items:
class Training extends Component {
constructor(props) {
super(props);
this.state = {
popupShowed: false
};
}
togglePopup = event => {
this.setState({
popupShowed: !this.state.popupShowed
});
};
onClosePopup = () => {
this.togglePopup();
};
content = () => {
const elements = ["76979871", "72675442", "337398380"];
const items = [];
for (const [index, value] of elements.entries()) {
items.push(
<div className="item-wrapper d-flex mb-4" key={index}>
<div className="item-col training-num text-white font-weight-normal d-flex align-items-center justify-content-center">
<span>{index < 10 ? "0" + index : index}</span>
</div>
<div className="item-col desc-col">
<h3 className="text-white title font-weight-normal">
Dlaczego warto?
</h3>
<div className="text-wrapper training-desc text-white">
<p>
Dowiesz się dlaczego Social Media Ninja to Zawód Przyszłości.
Dostaniesz wiedzę na temat oferowania i briefowania klientów i
dowiesz się jak zarabiać na social mediach.
</p>
</div>
</div>
<div className="item-col text-white time-col">
<div className="inside-wrapper">
<p className="text-nowrap">
<strong>Czas trwania:</strong> 2:25:00
<br />
<strong>Twój postęp:</strong> 90%
</p>
</div>
</div>
<div className="item-col play-col d-flex align-items-center justify-content-center d-flex align-items-center justify-content-center">
<div className="play-wrapper" onClick={this.togglePopup}>
<svg
enableBackground="new 0 0 60.001 60.001"
viewBox="0 0 60.001 60.001"
xmlns="http://www.w3.org/2000/svg"
className="play-button"
>
<path d="m59.895 58.531-29-58c-.34-.678-1.449-.678-1.789 0l-29 58c-.155.31-.139.678.044.973.182.294.504.474.85.474h58c.347 0 .668-.18.851-.474.182-.295.199-.663.044-.973zm-57.277-.553 27.382-54.764 27.382 54.764z" />
</svg>
<span className="text-white mt-2 d-inline-block">zobacz</span>
{/* <iframe src={'https://player.vimeo.com/video/' + value} width="500" height="600" frameBorder="0" allowFullScreen mozallowfullscreen="true" allowFullScreen></iframe> */}
</div>
</div>
{this.state.popupShowed ? (
<PopupVideo videoId={value} closePopup={this.onClosePopup} />
) : null}
</div>
);
}
return <div className="list-wrapper">{items}</div>;
};
render() {
return <Layout content={this.content()} />;
}
}
export default Training;
Code for displaying popupVideo:
class PopupVideo extends Component {
componentDidMount = () => {
var iframe = document.querySelector("iframe");
var player = new Player(iframe);
player.on("play", function() {
console.log("played the video!");
});
};
render() {
return (
<div className="popup video-popup">
<div className="popup-inner d-flex align-items-center d-flex justify-content-center">
<div className="video">
<span
onClick={this.props.closePopup}
className="close-video d-flex align-items-center justify-content-center"
>
<img
src=""
alt="close video"
/>
</span>
<div className="embed-container">
<iframe
src={
"https://player.vimeo.com/video/" +
this.props.videoId +
"?api=1&autoplay=0#t=0"
}
title="Nazwa szkolenia"
frameBorder="0"
allowFullScreen
mozallowfullscreen="true"
allowFullScreen
></iframe>
</div>
<div className="video-nav">
<div className="video-progress"></div>
<div className="d-flex align-items-center py-4">
<div className="play">
<span className="play-video"></span>
</div>
<div className="stop">
<span className="stop-video"></span>
</div>
<div className="volume">
<span className="volume-video"></span>
</div>
<div className="time">00:00 / 05:50</div>
<div className="break"></div>
<div className="title">
<h4>
<strong className="mr-3 pr-3">01</strong>Dlaczego warto ?
</h4>
</div>
<div className="button">
<button className="btn btn-secondary d-flex justify-content-center text-uppercase text-light font-weight-bold px-4">
Zobacz następny
</button>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default PopupVideo;
I do not have any error messages in the console.
Okay so i simplified the components to show you a good pattern to handle this kind of problems.
First create a VideoContainer to hold all the videoIds in the state.
We are going to return an array of Video components and pass the videoId as props to each one.
This container will be responsible to just provide the data to the other components
class VideoContainer extends Component {
state = {
videoIds: ["76979871", "72675442", "337398380"]
};
renderVideo = videoId => <Video key={videoId} videoId={videoId} />
render() {
const { videoIds } = this.state;
return videoIds.map(this.renderVideo);
}
}
Then create a Video component which will hold the popupShowed in state and will include the PopupVideo component only when popupShowed is true using && pass in the videoId and the togglePopup handler as props.
Now every Video is an independent component which hold the state for showing the PopupVideo
class Video extends Component {
state = {
popupShowed: false
};
togglePopup = () => {
this.setState(prevState => ({
popupShowed: !prevState.popupShowed
}));
};
render() {
const { popupShowed } = this.state;
const { videoId } = this.props;
return (
<div className="item-wrapper d-flex mb-4">
<button onClick={this.togglePopup}>Show Popup</button>
{popupShowed && (
<PopupVideo videoId={videoId} closePopup={this.togglePopup} />
)}
</div>
);
}
}
And last PopupVideo
const PopupVideo = ({ videoId, closePopup }) => (
<div className="popup video-popup">
<span onClick={closePopup}>
<img
src="https://rahimblak.com/images/video-close.png"
alt="close video"
/>
</span>
<div className="embed-container">
<iframe
src={
"https://player.vimeo.com/video/" +
videoId +
"?api=1&autoplay=0#t=0"
}
title="Nazwa szkolenia"
frameBorder="0"
allowFullScreen
mozallowfullscreen="true"
/>
</div>
</div>
);
sandbox

I am trying to import a different product list from an array named clothingproducts

I have three arrays one with all of the items and the other two with specific items. When I change the array name in context it works but when i create another context file with the same code (contextc) I get this error TypeError: Cannot read property 'products' of undefined
return value.products.map(product => {
import React, { Component } from "react";
import Product from "./Product";
import { ProductConsumer } from "../contextc";
export default class Productlist extends Component {
render() {
return (
<React.Fragment>
<header className="bg py-5 mb0 container-fluid clothing border-bottom border-danger">
<div className="container h-100">
<div className="row h-100 align-items-center">
<div className="col-lg-12">
<h1 className="display-4 text-white mt-5 mb-2 text-center">
Clothing
</h1>
<p className="lead mb-5 text-white-50 text-center">
Our latest Releases.
</p>
</div>
</div>
</div>
</header>
<div className="py-0 ">
<div className="container">
<div className="row">
<ProductConsumer>
{value => {
return value.products.map(product => {
return <Product key={product.id} product={product} />;
});
}}
</ProductConsumer>
</div>
</div>
</div>
</React.Fragment>
);
}
}
this is happening because value is undefined.

Resources