{"title":"React.js Card","url":"https://seanbehan.ca/posts/react-card","description":"Building a reusable, nestable card component while learning how React composition works.","author":"Sean Behan","published":"2021-02-18T00:27:04.000Z","updated":null,"draft":false,"tags":["css","javascript","programming","react"],"readingMinutes":2,"image":null,"sections":[{"id":"introduction","text":"Introduction","level":2},{"id":"creating-the-card-component","text":"Creating the Card Component","level":2},{"id":"styling-the-card","text":"Styling the Card","level":2},{"id":"using-the-card-component","text":"Using the Card Component","level":2},{"id":"conclusion","text":"Conclusion","level":2}],"content_format":"text/markdown","content_url":"https://seanbehan.ca/posts/react-card.md","content":"### Introduction\n\nI've been learning React so that I can build my web applications for others and\n\nmyself. React is component based. You create reusable components and render\n\nthem with data. Here I created a card component that lets me insert cards. They\n\ncan even contain other cards and are easy to understand from the App.js.\n\n### Creating the Card Component\n\nTo create a new component I just create a new file called `Card.js` and import\n\nit at the top of `App.js`.\n\n```javascript\nimport Card from './Card.js';\n```\n\nThen inside `Card.js` I can create my Card. At the top I import my styles and\n\nreturn the JSX Card object.\n\n```javascript\nimport './Card.css';\n\nfunction Card(props) {\n\treturn (\n\t\t<div className=\"Card\">\n\t\t\t<h2 className=\"CardTitle\">{props.cardTitle}</h2>\n\t\t\t<p className=\"CardContent\">{props.children}</p>\n\t\t</div>\n\t);\n}\n\nexport default Card;\n```\n\nAt the bottom I set the default export to Card so that we can import it\n\nproperly in `App.js`.\n\n### Styling the Card\n\nMy styles are fairly simple, they just create a nice looking card.\n\n```css\n.Card {\n\ttext-align: center;\n\tbackground-color: lightgrey;\n\tborder: 1px solid grey;\n\tborder-radius: 0.5em;\n\tmargin: 1em;\n\theight: 20em;\n\toverflow: hidden;\n}\n\n.CardTitle {\n\tfont-size: 1em;\n}\n\n.CardContent {\n\tbackground-color: white;\n\theight: 100%;\n\tborder-radius: 0.5em;\n\tborder-top-left-radius: 0em;\n\tborder-top-right-radius: 0em;\n\tpadding: 1em;\n}\n```\n\n### Using the Card Component\n\nThat's great but we still have to insert our card in App.js. Now that we've\n\ncreated a component and imported it all I have to do in App.js to create a card\n\nis this.\n\n```jsx\n<Card cardTitle=\"Example Card Title\">Hello World</Card>\n```\n\n### Conclusion\n\nFinally we can see that this builds a card.\n\n![react card](https://seanbehan.ca/img/reactjs-card.webp)\n\nThis can be used for building any kind of component, such as dialog boxes,\n\nforms, or anything you can imagine in HTML/CSS.\n"}