These are some of the commonly used react patterns:
1.Element
- Elements are anything inside angle brackets.
<div></div>
<App />
- Components return elements.
2.Component
- These are nothing but functions which return a React Element
function App(){
return <h1> Hello World!!!</h1>
}
3.Expressions
- use curly braces to embed expression in JSX
function Greeting() {
let name = "sridhar";
return <div>Hi {name}!</div>;
}
4.defaultProps
- Specify default values for props with defaultProps.
function App(props) {
return <div>Hi {props.name}!</div>;
}
App.defaultProps = {
name: "Guest"
};
5.Destructuring Props
- Destructuring is an ES6 feature which will be used commonly in react used to destructure objects and arrays.
let person = { name: "sridhar"}
let { name} = person
- Similarly, we can destructure Arrays
let things = ["one", "two"];
let [first, second] = things;
- Destructuring is used a lot in functional components. These component declarations are as below
function Greeting(props) {
return <div>Hi {props.name}!</div>;
}
function Greeting({ name }) {
return <div>Hi {name}!</div>;
}
- There's is a syntax for collecting props into an object. It is react parameter syntax and it looks like this
function Greeting({ name, ...restProps }) {
return <div>Hi {name}!</div>;
}
- Those three dots (...) take all the remaining properties and assign them to the object restProps.
6.Conditional rendering
You can't use if/else statements inside component declarations. So conditional (ternary) operator and short-circuit evaluation are your friends.
If
{
condition && <span>Rendered when `truthy`</span>;
}
unless
{
condition || <span>Rendered when `falsy`</span>;
}
if-else
{
condition ? (
<span>Rendered when `truthy`</span>
) : (
<span>Rendered when `falsy`</span>
);
}
If you have any doubts related to this article or anything related to tech or software-engineering in general, drop a comment here or you can message me on twitter @ksridhar02.