React Component
React Component
Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
Functional Component
You define a component as a function. The name of the Componet must be CamelCase
1 | function Hello(props) { |
You can render the above component using JSX
1 | <Hello name="Smith" /> |
You can define a component using ES6 class, but this is not preferred now.
Props
- Props is short for “properties.”
- A component’s constructor can take props as parameter.
- props is pass from parent component to child component. In the typical React dataflow, props are the only way that parent components interact with their children.
- props is read-only. If you assign a value to property, React will throw an error.
Hello Component that uses properties
1 | function Hello(props) { |
You can also rewrite the above component using Object Destructuring
1 | function Hello({name}) { |
Example to invoke a component with property
1 | function App() { |
children property
- children is a special property that contains the content between the opening and closing tags when invoking a component.
Example of a component that renders {props.children}
1 | function MyBold(props) { |
Conditional Rendering
if number is less than or equals 100, then print the number, else print “num greater than 100”
1 | function PrintNum(props) { |
Inline If with Logical && Operator - This is handy for including an element
1 | function App() { |
Inline If-Else with Conditional Operator
1 | function PrintNum(props) { |
There are many ways to do conditional rendering, please choose the method that fits best.
Rendering a List
we can use the map()
function to render each element in the list.
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:
1 | function App() { |