Course Content
Introduction to React
Introduction to React
Passing Data into Components
It is very useful to be able to pass data into the components. The syntax of passing data into a component is similar to the syntax for assigning attributes in HTML.
Consider, for example, we have a component called Main
, and we want to pass a string called "Hello World"
into it. We can do so using the following code:
<Main text="Hello World" />
In the component βMainβ, we can access this value though the `props` object:
function Main(props) {
return <h1>{props.text}</h1>
}
The above component will create a <h1>
element with the "Hello World" text inside it. Notice that we use the term text
as the attribute name, therefore, when accessing the value from inside the component, we refer to the text
attribute of the props
object: props.text
. The name text
was an arbitrary choice, in fact, we can name it anything we like, for example:
<Main headingContent="Hello World" />
In this case, we will use the term headingContent
to access the value that has been passed:
function Main(props) {
return <h1>{props.headingContent}</h1>
}
We can also pass multiple strings into a single component:
<Main text_1="First String" text_2="Second String" text_3="Third String" />
In this case, the method for accessing the values passed will be the same:
function Main(props) {
return (
<div>
<p>{props.text_1}</p>
<p>{props.text_2}</p>
<p>{props.text_3}</p>
</div>
);
}
To simplify the above code, we can just pass a single array that contains all the strings:
let paragraphs = [
'First String',
'Second String',
'Third String'
]
<Main text={paragraphs} />
We can pass values of any data type ranging from integers to complex objects! It is important to note that when passing raw integer values, we need to enclose them in braces:
<Main value={1}/>
Thanks for your feedback!