Components
Components are the building blocks of a React application. They contained logic and templates that are reused throughout your applications. Components are essentially functions that return some JSX that can then be imported and used by parent components.
export default function Component() {
return <h1>Some component!</h1>;
}
Props
Props provide a way to pass data from a parent component into a child component to somehow influence their behavior. This is a one way flow, meaning changes to these props only flow from the parent to the child, but not the reverse.
// Parent
function Parent() {
return <Child color="red" />;
}
// Child
function Child(props) {
return <h1>{props.color}</h1>;
}
// or
function Child({ color }) {
return <h1>{color}</h1>;
}
Props however can also be functions, which is how you would handle passing data from the child back to the parent.
function Parent() {
const onSearch = (term) => {
console.log("Searching for", term);
};
return <Child onSubmit={onSearch} />;
}
import { useState } from "react";
function Child({ onSubmit }) {
const [term, setTerm] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
onSubmit(term);
};
return (
<form onSubmit={handleSubmit}>
<input value={term} onChange={(e) => setTerm(e.target.value)} />
</form>
);
}
Children Prop
There is a special prop called children
which works similarly to slots in Vue. When you use a component and pass in some text or elements within the opening and closing tags, that gets passed as a prop children
which you can use within your component.
function Child({ children }) {
return <h1>{children}</h1>;
}
function Parent() {
return <Child>This is my children!</Child>;
}
With Typescript
When using Typescript, you can define an interface for your props to improve intelisense in your IDE.
interface MyProps {
color: string | null; // can be either string or null
shade?: string; // optional prop
}
function Child({ color, shade });
Feeding classNames to child components
To pass classNames to your child components, we can use a package called classnames
to aggregate multiple classes.
import classNames from "classnames";
function Child({ className }) {
const classes = classNames("myclass1 myclass2", className);
return <div className={classes}>My component with custom classes!</div>;
}