In the last lesson, we see how to output dynamic content lets make our component configurable, flexible and dynamic.
For normal HTML elements we can pass attributes like className which we can add to any HTML attribue and in input element we have value attribute for example now for Person
className
value
Person
import React, { Component } from 'react'; import './App.css'; import Person from './Person/Person'; class App extends Component { render() { return ( <div className="App"> <h1> Heading</h1> <p> Paragraph </p> {/* Setting Attribute */} <Person name="Lucy" age="23" /> <Person name="Max" age="12"> My Hobbies : Dancing {/* Some Additional Data */} </Person> <Person name="Mike" age="34" /> </div> ); } } export default App;
So if we want to output this and maybe we wan to take it forever and for Max we also Adding some extra data i.e hobby. Now all that in place we have to change somthing in our Person component to handle data input.
The Person component can take the attribute and give us access inside our receiving component on object named props.
props
import React from 'react'; const person = (props) => { return <p></p>; }; export default person;
Now actually the name props is up to you but you will receive one argument in you function. One argument which is passed into it by default by React which is an object with all the properties of this component.
Now in react land this is reffered to as prop which is why I Named this argument props and i strongly recommend doing so, so that everyone else understand your code.
prop
Now, that we have props we can get access to that name and age thing. So we can use in our Person component
name
age
import React from 'react'; const person = props => { return ( <p> I am a {props.name} and i am {props.age} year old! </p> ); }; export default person;
class Person extends Component{ render(){ return ( <p> I am a {this.props.name} and i am {this.props.age} year old! </p> ); } }
After saving the code you can check on browser the attributes we defined are bind in the paragraph. So, now we have a reusable component which has a clearly defined component but in the there we use dynamic content which we set from outside in the place where we actually use our component this makes it really reusable. Think about all the possibilities which we will also explore in the course. having an input component where you can set the type from outside. having this Person component which might be styled like a card to output dynamic or different content for the different presence. This is an actually amazing world of features we can access here and it is one important step towards rebuilding greate and flexible components.
What we do about the hobbies we mention inside the Max person component. Let’s have a look at how we can use content which is passed not as an attribute but between the opening and the closing text in the next lesson.