They are JSX elements that have styling (CSS) baked in!
They come from the NPM package styled-components
Let's make a circle
It's a string, it's a function, it's a component.
IT'S ALL THREE!
import styled from 'styled-components';
const Circle = styled.div`
border-radius: 50%;
height: 200px;
width: 200px;
background-color: chartreuse;
margin: 50px auto;
`;
export default Circle;
Let's make a card
import React from 'react';
import styled from 'styled-components';
const StyledDiv = styled.div`
align-items: flex-start;
background-color: white;
border-radius: 10px;
filter: drop-shadow(0 0 0.25rem black);
flex-direction: column;
justify-content: flex-start;
padding: 10px;
width: 300px;
`;
const Card = props => {
return <StyledDiv>{props.children}</StyledDiv>;
};
export default Card;
import React from 'react';
import styled from 'styled-components';
const StyledDiv = styled.div`
align-items: flex-start;
background-color: white;
border-radius: 10px;
filter: drop-shadow(0 0 0.25rem black);
flex-direction: column;
justify-content: flex-start;
padding: 10px;
width: ${(props) => props.width || '300px'};
`;
const Card = props => {
return <StyledDiv>{props.children}</StyledDiv>;
};
export default Card;
Let's make the width a prop on the card.
template literal interpolation syntax
default operator
Grouping components into a special hierarchy
1. atoms - tiniest UI elements on a page, e.g. a button or an input.
2. molecules - basic functionality of a few atoms combined together, e.g. a nav bar consists of several buttons.
3. organisms - a functioning module of molecules and atoms, e.g. a full header would have navigation and a search bar.
4. templates - a way of laying out organisms, molecules, and atoms on a page, e.g. a blog website might have a "base" template and a "blog" template.
5. page - an specific instance of a template, e.g. the home page is an implemented base template.
React projects are prone to getting super disorganized!
If every component's file is in the same folder, there is no information about the actual component tree hierarchy.
Without some organization, we'll spend lots of time looking for files, and our mental models will suffer.
1. atoms - styled components or simple wrappers around JSX elements. These should be "dumb components", i.e. purely visual with props and no state. Examples: a styled button, a styled input box, a card (styled div),etc.
2. molecules - components that import several atoms to create slightly more complicated, but still "dumb" components. Examples: a navbar, a user card, etc.
3. organisms - components that import atoms or molecules. This is generally where we can start to think of "smart" components, or components with state. It's easy to remember because organisms have brains! Examples: a form component, a filterable list, etc.
I highly recommend checking out ARc (Atomic React), particularly the example source files, for inspiration on how to model your React apps in practice. There is also a branch for Redux.