Dynamic Data in Components in React JS

  • In ReactJS, it's common to render dynamic data inside components. To do this, you can pass data as "props" to a component, or fetch data from an API and store it in the component's "state" or "context".
  • Props: Props are a way to pass data from a parent component to a child component. To use props, you can define a component with a function that takes in props as an argument, and then use those props to render dynamic content.
For example:

function MyComponent(props) {
    return (
        <div>
            <h1>{props.title}</h1>
            <p>{props.description}</p>
        </div>
    );
}

ReactDOM.render(
    <MyComponent title="Welcome" description="This is my website" />,
    document.getElementById('root')
);
  • In this example, the "MyComponent" function takes in a "props" object as an argument, which contains the properties "title" and "description". These props are then used to render dynamic content inside the component.
  • State: State is a way to store data that can change over time, and it's typically used for dynamic data that needs to be updated in response to user actions or API requests. To use state, you can define a component with a class that extends the "React.Component" base class, and then define a "state" object with initial values.
For example:

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            posts: []
        };
    }

    componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/posts')
            .then(response => response.json())
            .then(posts => this.setState({ posts }));
    }

    render() {
        return (
            <div>
                {this.state.posts.map(post => (
                    <div key={post.id}>
                        <h1>{post.title}</h1>
                        <p>{post.body}</p>
                    </div>
                ))}
            </div>
        );
    }
}

ReactDOM.render(
    <MyComponent />,
    document.getElementById('root')
);
  • In this example, the "MyComponent" class defines a "state" object with an empty array for "posts". The "componentDidMount" lifecycle method fetches data from an API and updates the component's state with the retrieved data. Finally, the "render" method maps over the "posts" array and renders dynamic content for each post.
  • Context: Context is a way to share data between components without the need to pass props down through every level of the component tree. It's typically used for global data that needs to be accessed by multiple components. To use context, you can define a context object with initial values, and then wrap your component tree with a "Provider" component that makes the context available to all child components. 
For example:

const MyContext = React.createContext({ count: 0 });

class MyComponent extends React.Component {
    static contextType = MyContext;

    render() {
        return (
            <div>
                <p>Count: {this.context.count}</p>
                <button onClick={() => this.context.setCount(this.context.count + 1)}>
                    Increment
                </button>
            </div>
        );
    }
}

function App() {
    const [count, setCount] = React.useState(0);
    return (
        <MyContext.Provider value={{ count, setCount }}>
            <MyComponent />
        </MyContext.Provider>
    );
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);
  • In this example, the "MyContext" object is created with an initial value of "count: 0

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...