Thinking in React and making a counter app in react
Before reading this blog learn about what is react and why react?, hello world, React DOM, JSX, Component and props and also Learn about State & lifecycle, Handling Events, Conditional Rendering, Lists & Keys, Forms, Lifting State UP
React is, in our opinion, the premier way to build big, fast Web apps with JavaScript. It has scaled very well for us at Facebook and Instagram.
One of the many great parts of React is how it makes you think about apps as you build them.
To make any product or app. follow these :
- Design mockups or wireframes
- Break the UI into component hierarchy. A component should ideally only do one thing. If it ends up growing, it should be decomposed into smaller subcomponents.
- Build A Static Version in React . To build a static version of your app that renders your data model, you’ll want to build components that reuse other components and pass data using props. props are a way of passing data from parent to child. If you’re familiar with the concept of state, don’t use state at all to build this static version. State is reserved only for interactivity, that is, data that changes over time. Since this is a static version of the app, you don’t need it.
- Identify The Minimal (but complete) Representation Of UI State. To make your UI interactive, you need to be able to trigger changes to your underlying data model. React achieves this with state. you first need to think of the minimal set of mutable state that your app needs. The key here is DRY: Don’t Repeat Yourself.
- Identify Where Your State Should Live. Identify every component that renders something based on that state. Find a common owner component (a single component above all the components that need the state in the hierarchy).
Create a react app using
1npx create-react-app counter2cd counter3npm start
folder stracture
1-src2 -components3 `Counter.jsx4 -index.js
inside index.js file
1//index.js2 import React from 'react';3import {render} from 'react-dom';4import Counter from "./components/Counter"5render(<Counter />, document.getElementById('root'));
inside Counter.jsx
1class App extends React.Component {2 constructor() {3 super();4 this.state = { counter: 0 };5 }6 render() {7 return (8 <>9 <div className="container">10 <h1>Counter</h1>11 <h2>{this.state.counter}</h2>12 <div className="wrapper">13 <button className="button"14 onClick={() => {15 this.setState({ counter: this.state.counter + 1 });16 }}1718 >19 Increment20 </button>21 <button className="button"22 onClick={() => {23 this.setState({ counter: this.state.counter - 1 });2425 }}2627 >28 Decrement29 </button>30 <button className="button"31 onClick={() => this.setState({ counter: 0 })}32 >33 Reset34 </button>35 </div>36 </div>37 </>3839 );4041 }4243}