Rendering different youtube videos on button click - reactjs

I created a react app where I display different video games and the app decides which game to play. I also have a file where I stored the data of video games. The goal I'm trying to achieve is to render the youtube video trailer of the corresponding video game when clicking on a button while using React Hooks. I've been using the npm package react-player. If someone could help, I'd appreciate it.
This is the code for the Video Game component:
import React from 'react';
import { Button, message } from 'antd';
import { Row, Col } from 'antd';
import GameEntry from '../GameEntry';
import Games from '../Games';
function VideoGameSection() {
const chooseGame = () => {
var randomGameTitle = [
'Gears 5',
'Halo',
'Hellblade',
'It takes two',
'A Plague Tale',
'Psychonauts',
'Twelve Minutes',
'Ori',
'Streets of Rage',
'Last of Us',
'Boodborne',
'Geenshin Impact',
'Dragon Ball Z:KAKAROT',
'Ghost Tsushima',
'Naruto',
'Overcooked',
'Horizon',
'Tomb Raider',
'Uncharted',
'Person 5 Royal',
'Ratchet',
'Spider-Man',
];
var randomIndex = Math.floor(Math.random() * randomGameTitle.length);
return message.info(
'The game you will play is: ' + randomGameTitle[randomIndex] + '.',
);
};
return (
<div id="video-game" className="block bgGray">
<div className="container-fluid">
<div className="titleHolder">
<h2>Video Games</h2>
<p>A list of current games</p>
<div className="site-button-ghost-wrapper">
<Button
className="gameButton"
type="primary"
danger
ghost
onClick={chooseGame}
>
Pick for me
</Button>
</div>
</div>
<Row gutter={[16, 24]}>
{Games.map((videogame, i) => (
<Col span={8}>
<GameEntry
id={i}
key={i}
title={videogame.title}
imgURL={videogame.imgURL}
description={videogame.console}
/>
</Col>
))}
</Row>
</div>
</div>
);
}
export default VideoGameSection;
This is the code for my game entry component:
import React, { useState } from 'react';
import { Card, Button, Modal } from 'antd';
import YoutubeSection from './Home/YoutubeSection';
const { Meta } = Card;
function GameEntry(props) {
const [isModalVisible, setIsModalVisible] = useState(false);
const showModal = () => {
setIsModalVisible(true);
};
const handleClose = () => {
setIsModalVisible(false);
};
const handleCancel = () => {
setIsModalVisible(false);
};
return (
<div>
<Card
className="gameCard"
hoverable
cover={<img className="cardImg" alt={props.title} src={props.imgURL} />}
>
<div className="cardTitle">
<Meta title={props.title} description={props.description} />
</div>
<>
<Button
className="trailerButton"
type="primary"
block
style={{
color: '#fff',
borderColor: '#fff',
backgroundColor: '#e6544f',
}}
onClick={showModal}
>
Click for trailer
</Button>
<Modal
title={props.title}
width={'725px'}
visible={isModalVisible}
onOk={handleClose}
onCancel={handleCancel}
>
<YoutubeSection />
</Modal>
</>
</Card>
</div>
);
}
export default GameEntry;
This is the code for the youtube component:
import React, { useState } from 'react';
import ReactPlayer from 'react-player';
function YoutubeSection(props) {
return (
<div className="container-fluid">
<ReactPlayer
// url={videoTrailer}
muted={false}
playing={true}
controls={true}
/>
</div>
);
}
export default YoutubeSection;
example of data file:
const Games = [
{
id: 1,
title: 'Gears 5',
imgURL: '../Images/gears-5.jpeg',
console: 'Xbox',
videoID: 'SEpWlFfpEkU&t=7s',
},

You can keep a single Modal component and use it for that.
ModalView.js
import React, { useState } from "react";
import YoutubeSection from "./YoutubeSection";
import { Modal } from "antd";
const ModalView = ({
title,
isModalVisible,
handleClose,
handleCancel,
videoID
}) => {
return (
<Modal
title={title}
width={"725px"}
visible={isModalVisible}
onOk={handleClose}
onCancel={handleCancel}
>
<YoutubeSection videoID={videoID} />
</Modal>
);
};
export default ModalView;
Move the ModalView and its state, control functions to the VideoGameSection.
VideoGameSection.js
import React, { useState } from "react";
import { Button, message } from "antd";
import { Row, Col } from "antd";
import GameEntry from "./GameEntry";
import Games from "./Games";
import ModalView from "./ModalView";
function VideoGameSection() {
const [isModalVisible, setIsModalVisible] = useState(false);
const [currentVideoID, setCurrentVideoID] = useState("");
const showModal = () => {
setIsModalVisible(true);
};
const handleClose = () => {
setIsModalVisible(false);
};
const handleCancel = () => {
setIsModalVisible(false);
};
const chooseGame = () => {
var randomGameTitle = [
"Gears 5",
"Halo",
"Hellblade",
"It takes two",
"A Plague Tale",
"Psychonauts",
"Twelve Minutes",
"Ori",
"Streets of Rage",
"Last of Us",
"Boodborne",
"Geenshin Impact",
"Dragon Ball Z:KAKAROT",
"Ghost Tsushima",
"Naruto",
"Overcooked",
"Horizon",
"Tomb Raider",
"Uncharted",
"Person 5 Royal",
"Ratchet",
"Spider-Man"
];
var randomIndex = Math.floor(Math.random() * randomGameTitle.length);
return message.info(
"The game you will play is: " + randomGameTitle[randomIndex] + "."
);
};
return (
<div id="video-game" className="block bgGray">
<div className="container-fluid">
<div className="titleHolder">
<h2>Video Games</h2>
<p>A list of current games</p>
<div className="site-button-ghost-wrapper">
<Button
className="gameButton"
type="primary"
danger
ghost
onClick={chooseGame}
>
Pick for me
</Button>
</div>
</div>
<Row gutter={[16, 24]}>
{Games.map((videogame, i) => (
<Col span={8}>
<GameEntry
id={i}
key={i}
title={videogame.title}
imgURL={videogame.imgURL}
description={videogame.console}
videoID={videogame.videoID}
setCurrentVideoID={setCurrentVideoID}
showModal={showModal}
/>
</Col>
))}
<ModalView
videoID={currentVideoID}
handleClose={handleClose}
isModalVisible={isModalVisible}
/>
</Row>
</div>
</div>
);
}
export default VideoGameSection;
Access the videoID passed via ModalView. You can save gameId instead of videoID to get any other info of the game Ex:title.
YoutubeSection.js
import React, { useState } from "react";
import ReactPlayer from "react-player";
function YoutubeSection(props) {
return (
<div className="container-fluid">
<ReactPlayer
url={`https://www.youtube.com/watch?v=${props.videoID}`}
muted={false}
playing={true}
controls={true}
/>
</div>
);
}
export default YoutubeSection;
GameEntry.js
import React, { useState } from "react";
import { Card, Button, Modal } from "antd";
import YoutubeSection from "./YoutubeSection";
const { Meta } = Card;
function GameEntry(props) {
return (
<div>
<Card
className="gameCard"
hoverable
cover={<img className="cardImg" alt={props.title} src={props.imgURL} />}
>
<div className="cardTitle">
<Meta title={props.title} description={props.description} />
</div>
<>
<Button
className="trailerButton"
type="primary"
block
style={{
color: "#fff",
borderColor: "#fff",
backgroundColor: "#e6544f"
}}
onClick={() => {
props.setCurrentVideoID(props.videoID);
props.showModal();
}}
>
Click for trailer
</Button>
</>
</Card>
</div>
);
}
export default GameEntry;
Code sandbox => https://codesandbox.io/s/flamboyant-dan-z0kc0?file=/src/ModalView.js

Related

how to trigger "react bootstrap modal" (containing intro.gif) and close modal after intro.gif finishes?

i want to trigger Modal (containing intro.gif) in Electron React Boiletplate on application start, and the modal should close after "intro.gif" finishes.
below is what I've tried so far.
Home.tsx
import { useState } from 'react';
import { Button, Modal } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import Intro from '../../../assets/intro.gif';
function ModalComp() {
const values = [true, 'sm-down', 'md-down', 'lg-down', 'xl-down', 'xxl-down'];
const [fullscreen, setFullscreen] = useState(true);
const [show, setShow] = useState(false);
function handleShow(breakpoint) {
setFullscreen(breakpoint);
setShow(true);
}
return (
<>
{values.map((v, idx) => (
<Button key={idx} className="me-2 mb-2" onClick={() => handleShow(v)}>
Full screen
{typeof v === 'string' && `below ${v.split('-')[0]}`}
</Button>
))}
<Modal show={show} fullscreen={fullscreen} onHide={() => setShow(false)}>
<img src={Intro} className="img-fluid" alt="" />
</Modal>
</>
);
}
function Home() {
return (
<div>
{/* modal start */}
<ModalComp />
{/* modal end */}
</div>
);
}
export default Home;

in MERN, Response given and using useState to update new state with new fetched data, but not visually visible in my website even though logic works

By using console.log(responseData.places) I have checked the fetching works since I am using a hook for this and seems to work fine until I setLoadedPlaces with is the method I use to update the loadedPlaces which I later use to get the values to fill the frontend part of the website.
This is the output I get from this console.log I did and the values are correct.
[{…}]
0: address: "sis se puede
busrespect: 'tu puedes',
creator: "6384e2f543f63be1c560effa"
description: "al mundial"
id: "6384e30243f63be1c560f000"
image:"https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Empire_State_Building_%28aerial_view%29.jpg/400px-Empire_State_Building_%28aerial_view%29.jpg"location: {lat: -12.086158, lng: -76.898019}
title: "Peru"
__v: 0
_id: "6384e30243f63be1c560f000"[[Prototype]]:
Objectlength: 1[[Prototype]]: Array(0)
So after this this the code I have in the frontend (SINCE the backend works properly) Let me know if you have any doubts with this logic
This is UserPlaces.js
import React, {useState, useEffect } from 'react';
import PlaceList from '../components/PlaceList';
import { useParams } from 'react-router-dom';
import { useHttpClient } from '../../shared/hooks/http-hook';
import ErrorModal from '../../shared/components/UIElements/ErrorModal';
import LoadingSpinner from '../../shared/components/UIElements/LoadingSpinner';
const UserPlaces = () => {
const {loadedPlaces, setLoadedPlaces} = useState();
const {isLoading, error, sendRequest, clearError } = useHttpClient();
const userId = useParams().userId;
useEffect(() => {
const fetchPlaces = async () => {
try {
const responseData = await sendRequest(
`http://localhost:5000/api/places/user/${userId}`
);
console.log(responseData.bus_stops)
setLoadedPlaces(responseData.bus_stops);
} catch (err) {}
};
fetchPlaces();
}, [sendRequest, userId]);
return (
<React.Fragment>
<ErrorModal error={error} onClear={clearError} />
{isLoading && (
<div className="center">
<LoadingSpinner />
</div>
)}
{!isLoading && loadedPlaces && <PlaceList items={loadedPlaces} />}
</React.Fragment>
);
};
export default UserPlaces;
This is Place-List.js
import React from 'react';
import "./PlaceList.css"
import Card from '../../shared/components/UIElements/Card'
import PlaceItem from './PlaceItem';
import Button from '../../shared/components/FormElements/Button';
const PlaceList = props => {
if (props.items.length === 0) {
return (
<div className='place-list-center'>
<Card>
<h2>No bus stops available. Be the first one to create one!</h2>
<Button to='/places/new'> Create Bus Stop </Button>
</Card>
</div>
);
}
return (
<ul className="place-list">
{props.items.map(bus_stops => (
<PlaceItem
key={bus_stops.id}
id={bus_stops.id}
image={bus_stops.image}
title={bus_stops.title}
busrespect={bus_stops.busrespect}
description={bus_stops.description}
address={bus_stops.address}
creatorId={bus_stops.creator}
coordinates={bus_stops.location}
/>
))}
</ul>
);
};
export default PlaceList;
This is PlaceItem.js
import React, { useState } from 'react';
import { useContext } from 'react';
import Card from '../../shared/components/UIElements/Card';
import Button from '../../shared/components/FormElements/Button';
import Modal from '../../shared/components/UIElements/Modal';
import Map from '../../shared/components/UIElements/Map';
import {AuthContext} from '../../shared//context/auth-context'
import "./PlaceItem.css";
const PlaceItem = props => {
const auth = useContext(AuthContext);
const [showMap, setShowMap] = useState(false);
const [showConfirmModal, setShowConfirmModal] = useState(false);
const openMapHandler = () => setShowMap(true);
const closeMapHandler = () => setShowMap(false);
const showDeleteWarningHandler = () => {
setShowConfirmModal(true);
};
const cancelDeleteHandler = () => {
setShowConfirmModal(false);
};
const confirmDeleteHandler = () => {
setShowConfirmModal(false); //when clicked close the new Modal
console.log('DELETING...');
};
return (
<React.Fragment>
<Modal show={showMap}
onCancel={closeMapHandler}
header={props.address}
contentClass="place-item__modal-content"
footerClass="place-item__modal-actions"
footer={<Button onClick={closeMapHandler}>Close </Button>}
>
<div className='map-container'>
<Map center={props.coordinates} zoom={16}/> {/* Should be props.coordinates but we writing default data for now until geocoding solved. */}
</div>
</Modal>
<Modal
show={showConfirmModal}
onCancel={cancelDeleteHandler}
header="Are you entirely sure?"
footerClass="place-item__modal-actions"
footer={
<React.Fragment>
<Button inverse onClick={cancelDeleteHandler}>
CANCEL
</Button>
<Button danger onClick={confirmDeleteHandler}>
DELETE
</Button>
</React.Fragment>
}
>
<p>
Do you want to proceed and delete this place? Please note that it
can't be undone thereafter.
</p>
</Modal>
<li className='"place=item'>
<Card className="place-item__content">
<div className='place-item__image'>
<img src={props.image} alt={props.title}/>
</div>
<div className='place-item__info'>
<h2>{props.title}</h2>
<h3>{props.address}</h3>
<p>{props.description}</p>
<p>{props.busrespect}</p>
</div>
<div className='place-item__actions'>
<Button inverse onClick={openMapHandler}> VIEW ON MAP</Button>
{auth.isLoggedIn && (<Button to={`/places/${props.id}`}> EDIT</Button> )}
{auth.isLoggedIn &&<Button danger onClick={showDeleteWarningHandler}> DELETE </Button>}
</div>
</Card>
</li>
</React.Fragment>
);
};
export default PlaceItem;
This is auth-context:
import { createContext } from "react";
export const AuthContext = createContext({
isLoggedIn: false,
userId: null,
login: () => {},
logout: () => {}});
This is is Modal.js
import React from 'react';
import ReactDOM from 'react-dom';
import Backdrop from './Backdrop';
import { CSSTransition } from 'react-transition-group';
import './Modal.css';
const ModalOverlay = props => {
const content =(
<div className={`modal ${props.className}`} style = {props.style}>
<header className={`modal__header ${props.headerClass}`}>
<h2>{props.header}</h2>
</header>
<form
onSubmit={
props.onSubmit ? props.onSubmit : event => event.preventDefault()
}
>
<div className={`modal__content ${props.contentClass}`}>
{props.children}
</div>
<footer className={`modal__content ${props.footerClass}`}>
{props.footer}
</footer>
</form>
</div>
);
return ReactDOM.createPortal(content, document.getElementById('modal-hook'));
};
const Modal = props => {
return (
<React.Fragment>
{props.show && <Backdrop onClick={props.onCancel} />}
<CSSTransition in={props.show}
mountOnEnter
unmountOnExit
timeout={200}
classNames="modal"
>
<ModalOverlay {...props}/>
</CSSTransition>
</React.Fragment>
);
};
export default Modal;
Also Trust the routing is correct since I have checked it already and I am just wondering if the logic in REACT with loadedPlaces, PlaceItema and PlaceList makes sense and it working. Let me know please. It will be really helpful.
Summary: Not getting any error but no visual data appears in the scren just the header of my website and the background (rest is empty) even though logic is functional.
const {loadedPlaces, setLoadedPlaces} = useState();
change the above line to
const [loadedPlaces, setLoadedPlaces] = useState();

setState (In react functional component) is not updating the existing state in react todo app

I have to do app using react and material ui which is combined of these components:
1- App.js
`
import './App.css';
import Header from './components/Header'
import ToDoApp from './components/ToDoApp';
function App() {
return (
<div className="App">
<Header />
<ToDoApp />
</div>
);
}
export default App;
`
2- ToDoApp.js
`
import React from 'react'
import ToDoList from './ToDoList';
import Task from './Task';
import { Container, Grid } from '#mui/material';
import {useState, } from 'react';
export default function ToDoApp() {
const [todos, setTodos] = useState([
{
id: 1,
Title: "Task 1",
done: true
},
{
id: 2,
Title: "Task 2",
done: true
},
])
const deleteTask = (id) => {
// console.log(id);
const newtodos = todos.filter(function(todo) {
return todo.id !== id;
})
setTodos(newtodos);
}
const addTodo = (todoTitle) => {
const lastTodo = todos[todos.length-1];
const newtodosId = lastTodo.id + 1;
const newtodos = todos;
newtodos.push({
id: newtodosId,
title: todoTitle,
done: false,
})
setTodos(newtodos);
console.log(newtodos);
}
return (
<Container maxWidth="sm">
<Grid item xs={12} md={6}>
<ToDoList newTodo={addTodo}/>
<Task ToDoAppList={todos} DeleteTodoTask={deleteTask}/>
</Grid>
</Container>
)
}
`
3- ToDoList.js
`
import * as React from 'react';
import FormControl from '#mui/material/FormControl';
import Typography from '#mui/material/Typography';
import TextField from '#mui/material/TextField';
import IconButton from '#mui/material/IconButton';
import { Add, AddToDriveOutlined } from '#mui/icons-material/';
import { useState } from 'react';
import { useEffect } from 'react';
export default function ToDoList(props) {
const addTodo = props.newTodo
const [todo, setTodo] = useState('')
function writeTodo(e) {
// console.log(e.target.value);
setTodo(e.target.value);
}
const addText = (e) => {
e.preventDefault();
addTodo(todo);
// console.log(todo);
}
return (
<>
<Typography sx={{ mt: 4, mb: 2 }} variant="h6" component="div">
ToDo List
</Typography>
<form onSubmit={(e) => addText(e)}>
<FormControl>
<div
style={{display: 'flex', marginBottom: 20}}>
<TextField
id="standard-helperText"
label="New ToDo"
style={{ width: 450 }}
variant="standard"
value={todo}
onChange={(e) => writeTodo(e)}
/>
<IconButton edge="end" aria-label="create" type="submit">
<Add />
</IconButton>
</div>
</FormControl>
</form>
</>
)
}
`
4-Task.js
`
import React from 'react'
import Paper from '#mui/material/Paper';
import IconButton from '#mui/material/IconButton';
import { Tag, Check, Delete } from '#mui/icons-material';
export default function Task(props) {
const tasks = props.ToDoAppList;
const deleteTask = props.DeleteTodoTask;
const List = tasks.map(task => { return(
<Paper elevation={3} style={{padding: 10, marginTop: 10}} key={task.id}>
<IconButton aria-label="create">
<Tag />
</IconButton>
<span style={{textDecoration: 'line-through'}}>{task.Title}</span>
<IconButton aria-label="delete" style={{float: 'right', color: 'red'}} onClick={()=>deleteTask(task.id)}>
<Delete />
</IconButton>
<IconButton aria-label="check" style={{float: 'right'}}>
<Check />
</IconButton>
</Paper>
)})
return (
<>
{List}
</>
)
}
`
When Submitting the new Todo, the result is not shown on the DOM.
In the ToDoApp.js -> function "addTodo" I used setState to push the new array with the new item, and is sent to ToDoList.js -> form "onSubmit" event in "addText" function. I put the console.log in the function and I am getting the new array but it's not showing on the page.
The tasks listing is handled in the task.js by sending the array through props and using map function to loop over the array.
Note: I handled the delete function in the ToDoApp.js and it's woking with no problem. I don't understand why it's not running with "addTodo" funciton.
First you need to change title to Title (based on your state Schema)
then you dont need to update whole state just add your new task to your current state (function in setTodos)
const addTodo = (todoTitle) => {
const lastTodo = todos[todos.length - 1];
const newtodosId = lastTodo.id + 1;
let newTodo = {
id: newtodosId,
Title: todoTitle,
done: false
};
setTodos((prev)=>[...prev,newTodo])
};

When you click on the button in the console displays the name of the button and the product is not filtered

Good day everyone, I am implementing filtering functionality for a price. I have a function that implements this. When I click on the button, the name of the button itself is displayed in my console, and the product itself is not filtered. Tell me, please, what can it be? The screenshots show the console and my code are infected. Help me please.
app.js file where the whole program is located
import Navbar from './components/Navsbar'
import {useState} from "react"
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import "./App.css";
import {ListProduct} from "./ListProduct";
import data from "./service/data";
import {Home} from './Home'
import AppFilter from './components/Filter';
//import Footer from 'rc-table/lib/Footer';
function App() {
const [filter, setFilter] = useState("");
const [info, setInfo] = useState(data)
const [field,setState] = useState([]);
const searchTerm = (items, term,number) => {
let lower = term.toLowerCase();
if (term.length === 0) return items;
return items.filter((item) => {
let itemLower = item.strDrink.toLowerCase()
return itemLower.indexOf(lower)> -1;
});
};
const onUpdateSearch = (term) => {
setFilter(term);
};
const filterPost =(items,field)=>{
switch(field){
case 'moreThen1000':
return items.filter(item=>item.price > 500);
default:
return items
}
}
const onFilterSelect =(field) =>{
setState(field);
console.log(field)
};
const visible = searchTerm(info.drinks, filter)
const viewable = filterPost(info.drinks,field)
return (
<>
<Router>
<Navbar onUpdateSearch={onUpdateSearch} />
<AppFilter filter={field} onFilterSelect={onFilterSelect}/>
<Routes>
<Route exact path='/' element={<Home />} />
<Route exact path="/ListProduct" element={<ListProduct searchTerm = {visible} onFilterSelect={viewable}/>} />
</Routes>
</Router>
</>
);
}
export default App;
appFilter.js file where the buttons are stored
import React from 'react';
import './Filter.css';
import data from "../service/data";
import "bootstrap/dist/css/bootstrap.min.css";
const AppFilter = (props) => {
const buttonsData = [
{name: 'all', label: 'All cocktails'},
{name: 'moreThen1000', label: 'More expensive than 500$'}
];
const buttons = buttonsData.map(({name, label}) => {
const active = props.filter === name;
const clazz = active ? 'btn-light' : 'btn-outline-light';
return (
<button type="button"
className={`btn ${clazz}`}
key={name}
onClick={() => props.onFilterSelect(name)}>
{label}
</button>
)
})
return (
<div className="btn-group">
{buttons}
</div>
)
}
export default AppFilter;
ListProduct.js file where cards with goods are displayed
import "./ListProduct.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { Container, Row, Col, Card } from "react-bootstrap";
export const ListProduct = (props) => {
const {searchTerm, onFilterSelect} = props
const element = searchTerm.map((item, i) => {
const { strDrinkThumb, strDrink, price } = item;
return (
<div className="card">
<li key={i}>
<Container>
<Row>
<Col>
<Card style={{ width: "18rem" }}>
<Card.Img variant="top" src={strDrinkThumb} />
<Card.Body>
<Card.Title>{strDrink}</Card.Title>
<Card.Text>
{ `Alcohol shop . The price is for one glass
${price}$`}
</Card.Text>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
</li>
</div>
);
});
return <div className="site">
<ul>{ element}</ul>
<div>
<footer className="page-footer font-small blue pt-4">
<div className="container-fluid text-center text-md-left">
<div className="row">
<div className="col-md-6 mt-md-0 mt-3">
<h5 className="text-uppercase">Cocktail shop</h5>
<p>Modern cocktail shop for different choices</p>
</div>
<hr className="clearfix w-100 d-md-none pb-0"/>
<div className="col-md-3 mb-md-0 mb-3">
<h5 className="text-uppercase">Our online resources</h5>
<ul className="list-unstyled">
<li>Our instagram page</li>
<li>Our site</li>
</ul>
</div>
</div>
</div>
<div className="footer-copyright text-center py-3">© 2020 Copyright:
MDBootstrap.com
</div>
</footer>
</div>
</div>;
};

Antd how to do onClick on List or Card action?

Hi i can't figure out how to set up the onclick function for the action below for Antd Card. Could someone help me pls? thanks.
const expand = () =>{
console.log("expand")
}
const IconText = ({ icon, text, cb }) => (
<Space>
<div onClick={e => cb}>
{React.createElement(icon)}
{text}
</div>
</Space>
);
<Card style={{ width: props.width, height: props.height }}
actions={[
<IconText icon={ExpandOutlined} text="Expand" key="list-vertical-star-o" cb={()=>expand}/>,
<IconText icon={MessageOutlined} text="Comments" key="list-vertical-like-o" />,
]}
>
https://ant.design/components/card/
see the callbacks ( Working codesandbox)
cb = {
() => {
expand("Comments");
}
}
also while binding:
<div onClick={e=> cb}>
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Card, Avatar, Space } from "antd";
import {
EditOutlined,
EllipsisOutlined,
SettingOutlined
} from "#ant-design/icons";
const { Meta } = Card;
const IconText = ({ icon, text, cb }) => (
<Space>
<div onClick={cb}>
{/*React.createElement(icon)*/}
{text}
</div>
</Space>
);
const expand = (text) => {
console.log("expand", text);
};
ReactDOM.render(
<Card
style={{ width: 300 }}
cover={
<img
alt="example"
src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
/>
}
actions={[
<IconText
text="Expand"
key="list-vertical-star-o"
cb={() => {
expand("Comments");
}}
/>,
<IconText text="Comments" key="list-vertical-like-o" />,
<SettingOutlined key="setting" />,
<EditOutlined key="edit" />,
<EllipsisOutlined key="ellipsis" />
]}
>
<Meta
avatar={
<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
}
title="Card title"
description="This is the description"
/>
</Card>,
document.getElementById("container")
);

Resources