Skip to main content

Passing props

You can make your components more dynamic by passing them data. This looks quite similarly to how regular HTML elements have attributes. Instead now, we will define them ourselves. These attributes on React components are called "props", short for properties.

Header.jsx
import { useState } from 'react';
import { Toggle } from '../toggle/';

export const Header = () => {
const [isMenuActive, setIsMenuActive] = useState(false);

const toggleMenu = () => {
setIsMenuActive(!isMenuActive);
}

return (
<Toggle title={isMenuActive ? "Close" : "Open"} toggleMenu={toggleMenu} />
);
}

Notice the curly braces around the variable; a variable or condition used as prop value should be wrapped in them. string, number and boolean values should be wrapped in double quotes. If the prop is present, but its value is omitted (<Toggle isMenuOpen /> for instance), the prop's value is simply set to true.

Alternatively you could spread the properties like so:

<Toggle {...{ title, toggleMenu }} />

Then, within the Toggle component you can grab the passed properties through the first argument in the component. The name could be anything, but we like to choose props, as it's widely recognized:

Toggle.jsx
export const Toggle = (props) => (
<button onClick={props.toggleMenu}>{props.title}</button>
)

Finally, we can deconstruct our variables to shorten our code and make it more readable by doing so:

Toggle.jsx
export const Toggle = ({title, toggleMenu}) => (
<button onClick={toggleMenu}>{title}</button>
)

Further reading