02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School

Integrating JSON into React Components

In this lesson, we explored how to build React components using ES6 classes. Here's a comprehensive guide:


What Are ES6 React Classes?

  • React components are reusable pieces of UI logic.
  • Using ES6 classes to define components allows for a structured approach with built-in lifecycle methods like render.

Step-by-Step Guide to Creating a React Component

  1. Setup:
    Ensure you have React and ReactDOM installed:

    npm install react react-dom
    
  2. Create a Components Directory:

    • In your project’s src folder, create a new folder named components.
    • This structure keeps your React components organized.
  3. Build the React Component:

    • Create a file named App.js inside the components folder.
    • Write the following code:
      import React from 'react';
      
      class App extends React.Component {
          render() {
              return (
                  <div>
                      <h1>Hello, World!</h1>
                  </div>
              );
          }
      }
      
      export default App;
      
  4. Understand Key Concepts:

    • import React from 'react': Loads the React library to use JSX and define components.
    • class App extends React.Component: Defines a new React component named App.
    • render(): A required method that returns the component’s UI in JSX format.
  5. Integrate the Component:

    • Open your client.js (or equivalent entry file) and import the App component:
      import React from 'react';
      import ReactDOM from 'react-dom';
      import App from './components/App';
      
      ReactDOM.render(<App />, document.getElementById('react-root'));
      
    • Ensure the index.html file contains a <div> with id="react-root".
  6. Test the Application:

    • Run the development server:
      npm start
      
    • Open your browser and confirm that "Hello, World!" is displayed.

Why Use React and ReactDOM Separately?

  • React: Handles the creation and management of components.
  • ReactDOM: Manages rendering components to the DOM.
  • This separation allows React to work in non-DOM environments like React Native.

What Is JSX?

  • JSX is a syntax extension for JavaScript that looks similar to HTML.
  • JSX makes it intuitive to write UI logic and structure.

Example:

return (
    <div>
        <h1>Hello, World!</h1>
    </div>
);

Key JSX Rules

  1. JSX must return a single parent element.

    • Correct:
      return (
          <div>
              <h1>Title</h1>
              <p>Description</p>
          </div>
      );
      
    • Incorrect:
      return (
          <h1>Title</h1>
          <p>Description</p>
      );
      
  2. Use camelCase for HTML attributes:

    return <div className="container"></div>; // Correct
    

Next Steps

Now that we’ve built and integrated a React component, the next lesson will focus on using JSON data within the component. Stay tuned!

2024

In 2024, React development has continued to evolve, and while the ES6 class-based approach is still valid, it has largely been replaced by functional components with React Hooks. Here's how the approach from this lesson compares to modern best practices:


Modern React Development in 2024

Why Functional Components?

  • Functional components are simpler and more concise than class components.
  • With Hooks, functional components can now handle state and lifecycle methods, making them a powerful alternative to class components.
  • The React team actively encourages the use of functional components in new projects.

Updated Guide for 2024

1. Install Required Libraries

Use the latest React libraries:

npm install react react-dom

2. Create Functional Components

Instead of ES6 classes, use a functional component with Hooks:

Example: App.js

import React from 'react';

const App = () => {
    return (
        <div>
            <h1>Hello, World!</h1>
        </div>
    );
};

export default App;

3. Why React Hooks?

  • Simplified State Management: Replace this.state and setState with the useState Hook:

    import React, { useState } from 'react';
    
    const Counter = () => {
        const [count, setCount] = useState(0);
    
        return (
            <div>
                <p>Count: {count}</p>
                <button onClick={() => setCount(count + 1)}>Increment</button>
            </div>
        );
    };
    
    export default Counter;
    
  • Replace Lifecycle Methods with useEffect: Handle side effects like data fetching or subscriptions with the useEffect Hook:

    import React, { useEffect } from 'react';
    
    const DataFetcher = () => {
        useEffect(() => {
            console.log('Component mounted!');
            return () => console.log('Cleanup on unmount!');
        }, []); // Empty dependency array means this runs only once.
    
        return <p>Fetching data...</p>;
    };
    
    export default DataFetcher;
    

4. Modern JSX Rules and Features

  • Fragments for Multiple Elements: No need to wrap elements in an unnecessary div—use <React.Fragment> or shorthand <>:

    return (
        <>
            <h1>Title</h1>
            <p>Description</p>
        </>
    );
    
  • TypeScript for Better Type Safety: Modern projects increasingly use TypeScript to ensure type safety and scalability:

    import React from 'react';
    
    type Props = {
        title: string;
    };
    
    const App: React.FC<Props> = ({ title }) => {
        return <h1>{title}</h1>;
    };
    
    export default App;
    

Modern File Organization

In 2024, teams often adopt scalable folder structures:

src/
├── components/
│   ├── App.jsx
│   ├── Counter.jsx
│   └── DataFetcher.jsx
├── hooks/
│   └── useCustomHook.js
├── context/
│   └── AppContext.js
├── styles/
│   └── app.css
├── utils/
│   └── helpers.js
└── main.jsx

ReactDOM in 2024

React now defaults to createRoot instead of ReactDOM.render, introduced in React 18. This optimizes rendering with Concurrent Mode:
Example: main.jsx

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './components/App';

const rootElement = document.getElementById('react-root');
const root = createRoot(rootElement);

root.render(<App />);

Comparison of Approaches

Feature2016 ES6 Classes2024 Functional Components + Hooks
SyntaxClass-basedFunction-based
State Managementthis.state, setStateuseState
Lifecycle MethodsMethods like componentDidMountuseEffect
ComplexityHigher (verbose)Lower (concise)
Type SafetyOptionalOften TypeScript
Render APIReactDOM.rendercreateRoot

Conclusion

While class components are still supported, modern React development in 2024 emphasizes functional components with Hooks for simplicity and flexibility. If this course were updated today, it would likely focus on using functional components, React Hooks (useState, useEffect), and TypeScript, along with React's latest features like createRoot.

Video Transcript

00:01Now that we have a React component, it's time for us
00:04to integrate our JSON data into that component.
00:08In the process, we're gonna take a look at JSX
00:11and the JSX spread feature, which is new as well.
00:14We're gonna take a look at how
00:15to integrate properties into react components
00:19and we're going to integrate that JSON file.
00:22So let's jump right into it.
00:25Alright, let's continue down the path so far
00:28and we're very close to wrapping up this section,
00:31but we really want to use the data
00:33that we're loading up from our JSON file.
00:36Let's just use name and age for now.
00:39And to do that I wanna show you
00:40how do you send information into a component
00:43of react using JSX?
00:46The first step that I'm gonna do is I'm gonna define a
00:49property just like we would in HTML.
00:52Then I'll open and close a curly bracket
00:55and inside of this section I'll go ahead
00:58and send in the information that I want to have sent
01:02to that component.
01:04Let me just word wrap and let's go ahead
01:06and do the same thing also for our age.
01:08And I'll just open and close around bracket
01:10and send that data that age into that region as well.
01:16Now this is A-J-S-J-S-X construct that enables us
01:21to inject into a some native JavaScript.
01:25The next thing that I'm gonna do is I'm gonna go into my app
01:28component and actually use the
01:29information that we've just sent.
01:31Now in React, the way we do that is we use something
01:35that's called props.
01:37Those are properties that that we're sending out.
01:39So what I'm gonna do is I'm gonna delete this return value
01:42and instead of that I want
01:43to send it out a more complex structure.
01:47And I'm gonna go ahead and I'm gonna set here a diviv,
01:49making sure that I'm opening and closing that div.
01:53Now inside I'm gonna send here an H one just like we had
01:56before, and I'm also gonna send a paragraph.
02:00Now what I'm gonna do is I'm gonna put
02:02here, let's say my name.
02:03So again, open and close, a round bracket, uh,
02:05curly bracket, and then put
02:07inside the native JavaScript code.
02:09In this case, I'm going to use the builtin, this
02:14props property that will give me access to the properties
02:17that have been sent to this app component.
02:19And in this case I wanna fetch the name,
02:21which is surprisingly my name.
02:24I could also integrate it.
02:25It for example, he is at least years old.
02:29And I could go ahead
02:30and in that area, just put again a round a curly bracket
02:34and send and call in the props age.
02:38If I go ahead and test this out in the browser,
02:40we should now see if we don't have an error.
02:44Boop, let's see what's going on.
02:49Alright, so let me, let's give it another shot.
02:51So first of all, let me go ahead and save this
02:53and I'm gonna go into my client itself to check
02:55and see if I have your, anything that stands out
02:58as something odd.
03:00But really I don't see any problem.
03:02Oh, and I must have did, I probably didn't save it earlier.
03:05So I went ahead and saved both files and here we go Ben.
03:08He is at least 33 years old. Beautiful.
03:12So that is how I send in properties.
03:13And I wanna show you just one more thing
03:15that you could do in JSX before we wrap up this title.
03:20So far I'm using only the name and the age,
03:24but maybe in reality I want to use everything inside
03:27of this JSO object.
03:29The easiest way to do that is instead
03:31of using these properties, and let me just go ahead
03:34and remove them and I'll leave them here for you.
03:36So you'll be able to look at them.
03:38I'm gonna open and close a curly bracket
03:40and then type dot, dot, dot.
03:42And then the name of the object that I wanna break up open
03:46and send into react.
03:49The react component.
03:50What will actually happen is a lot of variables such
03:53as name, age, smart friends,
03:56eyes will be all sent into the app.
03:59And in this case we could have your, for example,
04:02we could uh, have your some sort of, uh, a logic set
04:06that we could have your how about we'll have your some sort
04:08of a variable.
04:10And I'm gonna send here, um, is smart
04:14and I'm gonna set here if this props
04:18smart is true, he is smart, will come out.
04:23If he isn't smart, I will have a, he is not smart.
04:27And by the way, if you're not familiar to this,
04:28with this construct, it's called ary operator.
04:32And the tur ter ary operator really is just you have your
04:36condition or a Boolean and then a question mark.
04:40If the condition matches, then the first item will happen.
04:44And after that you have a colon.
04:45And the second would, if it's the L.
04:47So it's kind of like a very condensed if else.
04:50Now that I have here, this is smart,
04:52which is probably not correct,
04:53but this is gonna be smart message as a variable,
04:58I could go ahead and just add that into my props here
05:01and set here a smart message as another property
05:06that is being sent through.
05:07And again, if the property smart is in existence,
05:11which it should be because we're sending it in
05:13and its value is true, then it should send us he is smart
05:16and let's go ahead and save this and let's go ahead
05:18and save our client also to make sure
05:20that we don't make the same mistake twice.
05:22And if I go ahead and automatically look at it,
05:24we'll see that he is smart.
05:26But if I go into my JSON and I change it to be false
05:30and I go back in there, we'll see he is not smart.
05:34So there we go. That is
05:35how you build react components in E ES six
05:38and how you pass properties into them.
05:40In this section we learned how
05:43to create JSON structures.
05:46We learned how to import them
05:48and we've learned also how
05:49to create react components in E ES six
05:52and integrate into them JSON data. In this
05:56Lecture we saw how to integrate properties into react
05:59components and by that, saw how to use that JSON data
06:03that we've created throughout this chapter.
06:06The next chapter is gonna be about a new data type
06:09and a new topic and a new visualization
06:12where we're gonna take a look at web services.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!