Skip to content

Exercises

Extract components

Let's practice creating components! In the exercises below, you'll be given a chunk of JSX, and your mission is to refactor the code so that it uses a component.

Building a CRM

Let's suppose we're building software.

We've written the markup to display the contact information for 3 contacts, but there's an awful lot of repetition involved. Let's create a new component, ContactCard, and use that component for each of the 3 contacts.

Acceptance Criteria:

  • A brand-new ContactCard component should be created and used for each of the 3 contact cards
  • Props should be created for any bits of information that vary from card to card.

Code Playground

import React from 'react';

function App() {
return (
<ul>
<li className="contact-card">
<h2>Sunita Kumar</h2>
<dl>
<dt>Job</dt>
<dd>Electrical Engineer</dd>
<dt>Email</dt>
<dd>sunita.kumar@acme.co</dd>
</dl>
</li>
<li className="contact-card">
<h2>Henderson G. Sterling II</h2>
<dl>
<dt>Job</dt>
<dd>Receptionist</dd>
<dt>Email</dt>
<dd>henderson-the-second@acme.co</dd>
</dl>
</li>
<li className="contact-card">
<h2>Aoi Kobayashi</h2>
<dl>
<dt>Job</dt>
<dd>President</dd>
<dt>Email</dt>
<dd>kobayashi.aoi@acme.co</dd>
</dl>
</li>
</ul>
);
}

export default App;

Solution:

In this video, we mention that there are ways to dynamically change the rendered tag. This is known as “polymorphism”, and we learn all about it in Module 4.

Creating a “Button” component

Below, we have two <button> elements. Create a Button component, and use it to render both buttons.

Acceptance Criteria:

  • A brand-new Button component should be created and used for both buttons
  • Each Button instance should be able to set its own text content, as well as choose a text/border color. It's up to you to decide how you want to structure this!

Code Playground

import React from 'react';
import { createRoot } from 'react-dom/client';

const root = createRoot(
document.querySelector('#root')
);

root.render(
<div>
<button
style={{
border: '2px solid',
color: 'red',
borderColor: 'red',
background: 'white',
borderRadius: 4,
padding: 16,
margin: 8,
}}
>
Cancel
</button>
<button
style={{
border: '2px solid',
color: 'black',
borderColor: 'black',
background: 'white',
borderRadius: 4,
padding: 16,
margin: 8,
}}
>
Confirm
</button>
</div>
);

Solution: