If you want to learn more about React, start by reading the documentation on how to get started. In essence, React is a UI library that revolves around state, with components built in JSX being reactive to changes in that state.
While you seem to be on the right path, it's important to note that React doesn't rely on back-ticks for creating HTML strings – all of this functionality is handled within the library itself. Your focus should be on understanding the syntax, grasping how state operates, and effectively organizing your components to respond to state changes.
This customized example based on your code snippet should provide you with some clarity:
const { useState } = React;
// Home component accepting deck as props
function Home({ deck }) {
// Setting up state using the deck
const [cards, setCards] = useState(deck);
function handleClick(e) {
const card = e.target.closest('.card');
if (card) {
const { dataset: { id } } = card;
setCards(prev => {
return prev.map(card => {
if (card.id === Number(id)) {
return { ...card, visible: !card.visible };
}
return card;
});
});
}
}
return (
<main>
{cards.map(card => {
return (
<Card
key={card.id}
card={card}
handleClick={handleClick}
/>
);
})}
</main>
);
}
function Card({ card, handleClick }) {
const { id, symbol, visible } = card;
return (
<div
data-id={card.id}
className="card"
onClick={handleClick}
>
<div className={`face ${visible && 'hidden'}`}>
?
</div>
<div className={`face ${!visible && 'hidden'}`}>
{card.symbol}
</div>
</div>
);
}
const deck = [
{ id: 1, symbol: '♠', visible: false },
{ id: 2, symbol: '♥', visible: false },
{ id: 3, symbol: '♦', visible: false },
{ id: 4, symbol: '♣', visible: false }
];
const node = document.getElementById('root');
const root = ReactDOM.createRoot(node);
root.render(<Home deck={deck} />);
.card { width: 75px; height: 100px; display: flex; align-items: center; justify-content: center; border: 1px solid black; font-size: 2rem; }
.card:hover { cursor: pointer; background-color: lightyellow;}
.hidden { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.min.js"></script>
<div id="root"></div>