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
2
3
function Hello(props) {
return <p>Hello, {props.name}</p>;
}

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
2
3
function Hello(props) {
return <p>Hello, {props.name}</p>;
}

You can also rewrite the above component using Object Destructuring

1
2
3
function Hello({name}) {
return <p>Hello, {name}</p>;
}

Example to invoke a component with property

1
2
3
4
5
6
7
8
function App() {
let person = {name: 'Smith', id:'1'}
return (
<div>
<Welcome name={person.name} />
</div>
);
}

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
2
3
4
5
6
function MyBold(props) {
return <b>{props.children}</b>;
}

// to pass the children to the component
<MyBold>Bob Smith</MyBold>

Conditional Rendering

if number is less than or equals 100, then print the number, else print “num greater than 100”

1
2
3
4
5
6
7
function PrintNum(props) {
if( parseInt(props.num) <= 100 ) {
return <p>{props.num}</p>
} else {
return <p>num &gt; 100</p>
}
}

Inline If with Logical && Operator - This is handy for including an element

1
2
3
4
5
6
7
function App() {
let error = "SOME ERROR";
return (<div>
{error &&
<div>Something went wrong</div>}
</div>);
}

Inline If-Else with Conditional Operator

1
2
3
function PrintNum(props) {
return (parseInt(props.num) <= 100)? <p>props.num</p>: <p>num greater than 100</p>
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function App() {
const students = [
{ id: 88, name: "Alice" },
{ id: 34, name: "Zed" },
{ id: 23, name: "Bob" },
];
const studentList = students.map((student) =>
(<li key={student.id}>
{student.name}
</li>)
);
return (
<ul>
{studentList}
</ul>);
}

Reference