Step 3: Refactor
Let’s refactor the code by adding the following components
components/Notes.jsx
import Note from "./Note";
import PropTypes from "prop-types";
function Notes(props) {
const { notes } = props;
return (
<>
{notes
.map((note) => (
<Note note={note}/>
))}
</>
);
}
export default Notes;
Notes.propTypes = {
notes: PropTypes.arrayOf(
PropTypes.shape({
title: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
})
),
};
components/Note.jsx
import PropTypes from "prop-types";
function Note(props) {
const { note } = props;
return (
<div>
<p>{note.title}</p>
<p>{note.text}</p>
</div>
);
}
export default Note;
Note.propTypes = {
note: PropTypes.shape({
title: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
}),
};
Notice these component rely on the prop-types
library to validate the props. You must install it as a dependency:
yarn add prop-types
Next, update the App.jsx
as follows:
+ import Notes from "./components/Notes";
function App() {
return (
<>
- {
- notes.map(note => (
- <div>
- <p>{note.title}</p>
- <p>{note.text}</p>
- </div>
- ))
- }
+ <Notes notes={notes} />
</>
);
}
export default App;