React: Components, Props, and State
- Submit Forms
- List items
- Navigation pages like Home, Info, Profile etc.
into various “chunks” of the application which are called “components” as they are individual, well, components of the app itself.
So how does React know that all these components need to be rendered as the same app? The programmer tells it to in just that manner. In a React app we “render” these components typically in a “main” or “parent” component as “children” of that parent. Now, React is all about communication due its divided nature, so to get this parent to communicate with its children we employ this rendering technique directly in the JS code of the parent as such:
//our parent component
//our children components
This way the parent component knows what to render and in what order. Styling is handled in a separate css file and JS is written prior to the return() line but after the function declaration.
Now apps are all about data and if our components need that data how is it passed from component to component? Enter “State”, in React we use the useState hook to declare a variable as state, give it a default value, and a method used to update that state. Say we have a button in our Like component we want to change when clicked:
we can set the buttons state as a Boolean like true, and have our component render a button element based on that state. In order for that to work the state must be declared either in the component (if it wont be used elsewhere) or in the parent if we want it to be used in another child component or “sibling” component. In the case of the latter, we must “pass” the state down to the child like this:
//here we set our state, method, and value
const [likeButton, setLikeButton] = useState(true)
//here we pass its state “true” down to the child component
When we pass down these variables they are known as “props” like properties, or as I like to remember them like theatre props passed from one actor to another. Now in our Like component we have access to the state of likeButton and we can use it conditionally in that component. The Reason it has to be declared in the parent if we want to use it in another child is that props can only be passed down to children from the parent and not across to another child.
State, components and props are some of Reacts basic most powerful tools for development of UI, state allows for the ease of data storage and dynamic updating of our apps, as well as easy communication between components. Components allow for easier storage, organization, and therefore easier debugging, of our apps, and props are the package delivery system to bounce data from one component to the next with simple lines of code. React is one of the best program for any software engineer wanting to improve their skills with UI and general app development.