CodeBlanks Logo Icon CodeBlanks

Props

Learn to pass data to components with props.

What are props?

Props (short for property) is data passed into a component from outside. It lets you customize the component. You can call the same component with different data.

A component receives props as an object. Usually you destructure it: function Greeting({ name }) { ... }. Here name is the name of the passed prop.

When calling, you give the prop value: <Greeting name='Alex' />. Inside the component, you access this value with {name}.

Passing and using a prop

To pass a prop into a component, you write it like an attribute on the JSX tag: <Greeting name='Alex' />. Here name is the attribute name and 'Alex' is its value.

In the component definition, you receive this prop with destructuring: function Greeting({ name }) { return <Text>Hello, {name}</Text>; }.

This way, a single Greeting component can be reused for different names.

Practice Greeting with props

Write a Greeting component that takes the name prop via destructuring and returns <Text>Hello, {name}</Text>. App should call <Greeting name='Alex' />.

Starter code

App.js
// Write Greeting with name prop
// Call it in App with name='Alex'
function App() {
  return null;
}

Sample solution

App.js
function Greeting({ name }) {
  return (
    <Text>Hello, {name}</Text>
  );
}

function App() {
  return (
    <Greeting name='Alex' />
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the props concepts

Term Meaning
props Component input
{ name } Destructuring
name Prop name
<Greeting name=... Passing prop

2 How do you access the name prop?

App.js
function Greeting({ name }) { ... }
  • {name} Correct answer
  • props.name
  • name()
  • $name

Explanation: After destructuring, {name} accesses it.

3 Destructuring

Question
function Greeting(____) { return <Text>Hello, {name}</Text>; }
Answer
function Greeting({ name }) { return <Text>Hello, {name}</Text>; }

Explanation: { name } does destructuring.

All lessons in Beginner