Skip to content

Instantly share code, notes, and snippets.

@vickonrails
Created September 16, 2019 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vickonrails/326b4c13aece41b692acc84554bb7d45 to your computer and use it in GitHub Desktop.
Save vickonrails/326b4c13aece41b692acc84554bb7d45 to your computer and use it in GitHub Desktop.
import React, { useState } from "react";
import styled from "styled-components";
import "./App.css";
// Styled components definitions for all components
const Header = styled.header``;
const Nav = styled.nav``;
const MainContent = styled.main``;
const Container = styled.div``;
const InputForm = styled.form`
border: none;
`;
const InputField = styled.input``;
const NotesList = styled.section``;
const Button = styled.button``;
// React Components Code
const App: React.FC = () => {
// Managing state with React Hooks
const [titleValue, setTitleValue]: [
string,
(newValue: string) => void
] = useState("");
const [contentValue, setContentValue]: [
string,
(newValue: string) => void
] = useState("");
const [notes, setNotes]: [Array<any>, Function] = useState([
{
title: "First Note",
content: "You normally know how things like these turn out, don't you?"
}
]);
// Event handlers for Input and Content fields
const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setTitleValue(e.target.value);
};
const handleContentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setContentValue(e.target.value);
};
const addNote = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
let newNote = { title: titleValue, content: contentValue };
setNotes((prevNotes: object[]) => [prevNotes.slice(), newNote]);
// Empty both Input Fields
setContentValue("");
setTitleValue("");
};
return (
<>
<Header>
<Nav>
<Container>
<a href="/">Notes App</a>
</Container>
</Nav>
<MainContent>
<Container>
<InputForm onSubmit={addNote}>
<InputField
type="text"
onChange={handleTitleChange}
value={titleValue}
/>
<InputField
type="text"
onChange={handleContentChange}
value={contentValue}
/>
<Button type="submit">Add Note</Button>
<NotesList>
{notes.map(note => {
return (
<ul>
<li>
<p>{note.title}</p>
<p>{note.content}</p>
</li>
</ul>
);
})}
</NotesList>
</InputForm>
</Container>
</MainContent>
</Header>
</>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment