React Component
A Component can seen as a core element of every React UI.
A UI made with react is essentially a combination of multiple components, the components are defined once and can be re-used in multiple parts of the UI and through the use of the Props System they can be dynamic.
Components can either be defined through the use of functions or classes with the latter being used for complex components.
// FUNCTION SYNTAX
const App = () => {
return(
<div>
Hello World
</div>
)
}
// CLASS SYNTAX
class App extends React.Component {
render()
{
return(
<div>Hello World</div>
)
}
}
A component defined using classes has to extend the React.Component class and define a render
method which specifies what exactly that component renders visually on the page.
Props System
React Components can accept input called props(properties) which allows for the same component displaying different information in the same format, just like how the return value of a function might be based on the arguments passed. Lets see what this looks like:
const App = (props) => {
return (
<div>Hello {props.name}</div>
)
}
ReactDOM.render(<App name="Hermes"/>,document.querySelector('#root'));
We have added a bit dynamism to the App component, the name can be specified now. Now if we need to output 'Hello' statements for different names, we would just need to call the component with different names. This illustrates 'Re-usability' of components in react.
const Hello = (props) => {
return (
<div>Hello {props.name}</div>
)
}
const App = () => {
return (
<div>
<Hello name="Hermes"/>
<Hello name="Jack" />
<Hello name="Jill" />
</div>
)
}
ReactDOM.render(<App />,document.querySelector('#root'));
Another Example : https://codepen.io/truepadawan/pen/BaZMBov
Thanks for reading, drop a follow to find out when I drop the next in the series as I learn react.
Top comments (0)