React components: Student data (student.js)

React Components: Student Data (student.js)

In a typical React application, data is passed around as props between components. In this scenario, we'll be creating a Student component that will display a student's name, age, and grade.

Step 1: Creating the Student Component

We'll start by creating a new file called student.js and importing React:


import React from 'react';

Next, we'll define our Student component:


class Student extends React.Component {
  render() {
    return (
      
        Student Name
        Name: {this.props.name}
        Age: {this.props.age}
        Grade: {this.props.grade}
      
    );
  }
}

In the code above, we've defined a new class called Student that extends the React.Component class. We've also defined a render() method that returns a div containing the student's name, age, and grade. Notice that we're using the props object to access the data that's passed in from the parent component.

Step 2: Using the Student Component

Now that we've defined our Student component, let's use it in another component. Here's an example:


import React from 'react';
import Student from './student.js';

class App extends React.Component {
  render() {
    return (
      
        
      
    );
  }
}

In the code above, we've imported the Student component and used it in our App component. We're passing in the student's name, age, and grade as props. When the App component is rendered, it will display the Student component with the data that we've passed in.

Alternative Approach: Using Functional Components

An alternate approach to creating a component is to use a functional component. Here's an example of how we could rewrite our Student component using a functional component:


import React from 'react';

function Student(props) {
  return (
    
      Student Name
      Name: {props.name}
      Age: {props.age}
      Grade: {props.grade}
    
  );
}

export default Student;

In the code above, we've defined a new function called Student that takes in props as a parameter. We're also using the props object to access the student's name, age, and grade. Notice that we're not using the this keyword since we're not defining a class.

To use the functional component, we would import it and use it in our App component just like we did before:


import React from 'react';
import Student from './student.js';

function App() {
  return (
    
      
    
  );
}

export default App;

Conclusion

In conclusion, React components allow us to reuse code and pass data between components. By defining a new component that accepts props, we can display data in a consistent and reusable way. We can choose to define our components as classes or functions, depending on our needs.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe