Components, props and useState of react.js
Reactjs is a javascript library maintained by Facebook and it an open source library. Reactjs introduced to create webapp with clean code and less time.
what is components in reactjs
Components are independent and reusable code with return html and it just like javascript function. it have two type function component and class component. Class component is deprecated in latest updates and now most of developer use function component.
sample code of function component
function Header(){
return(
<div>
// code will be write here
</div>
)
}
export default Header // this line of code will return default component whenever this component will be called
Component can return only one element like <div> ...... </div>
code can be written inside div but another sibling element cannot be created.
to overcome this issue and multiple div coder can use <> </>
this will be counted as element but for html its nothing and we can bypass multiple div issue.
what is props in reactjs
the word 'props' implies 'properties'. props is type of object where the value of attributes of a tag is stored and it can be used as variable to reuse the component.
function Card({name, imgUrl}){
return(
<>
<div className="card mx-4" style={{width: "18rem"}}>
<img src={imgUrl} className="card-img-top" alt="..." />
<div className="card-body">
<h5 className="card-title">{name}</h5>
<p className="card-text">description text goes here</p>
<a href="#" className="btn btn-primary">click here</a>
</div>
</div>
</>
)
}
export default Card
whenever card will be called it can pass props like name
and imgUrl
like <Card name="Rohtash" imgUrl="https://picsum.photos/200/200" />
these attributes will be printed instead of {name}
for attribute name.
useState in Reactjs
useState() is a hook that allows you to have state variable in functional components.
Syntax: const [state, setState] = useState(initialstate)
import { useState } from 'react';
function Card(){
const [text, setText] = useState("Some quick example text to build on the card title and make up the bulk of the card's content.")
return(
<>
<div className="card mx-4" style={{width: "18rem"}}>
<img src={imgUrl} className="card-img-top" alt="..." />
<div className="card-body">
<h5 className="card-title">Rohtash Talan </h5>
<p className="card-text">{text}</p>
<a href="#" onClick={() => setText("You have Click button!")} className="btn btn-primary">Click to Change Text</a>
</div>
</div>
</>
)
}
export default Card
whenever someone click on button it would change the text to You have Click button!
.