Debug School

rakesh kumar
rakesh kumar

Posted on

How to renders data statically and dynamically when event type triggered in react js

How to renders data statically when I click button in react js
How to renders data statically when I select dropdown in react js
How to renders data statically when I select dropdown in react js
How to renders data dynamically when I button in react js
How to renders data dynamically when I select dropdown in react js
How to renders data dynamically when I submit form in react js
How to renders data country,state and city dynamically in react js

How to renders data statically when I click button in react js

import React, { useState } from 'react';

const App = () => {
  const [name, setName] = useState('John Doe');
  const [age, setAge] = useState(25);
  const [height, setHeight] = useState(170);

  const handleClick = () => {
    // Update the values
    setName('Jane Smith');
    setAge(30);
    setHeight(180);
  };

  return (
    <div>
      <h1>Person Information</h1>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <p>Height: {height} cm</p>
      <button onClick={handleClick}>Change Info</button>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we define three state variables: name, age, and height, using the useState hook. The initial values are set to 'John Doe', 25, and 170 respectively.

The handleClick function is called when the button is clicked. Inside the function, we update the values of name, age, and height using their respective setter functions setName, setAge, and setHeight. The new values are 'Jane Smith', 30, and 180.

In the JSX portion, we display the current values of name, age, and height. When the button is clicked, the handleClick function is invoked, and the state values are updated. React then re-renders the component with the updated values, displaying 'Jane Smith', 30, and 180.

How to renders data statically when I select dropdown in react js

import React, { useState } from 'react';

const App = () => {
  const [name, setName] = useState('');
  const [age, setAge] = useState('');
  const [height, setHeight] = useState('');

  const handleNameChange = (event) => {
    setName(event.target.value);
  };

  const handleAgeChange = (event) => {
    setAge(event.target.value);
  };

  const handleHeightChange = (event) => {
    setHeight(event.target.value);
  };

  return (
    <div>
      <h1>Person Information</h1>
      <label>
        Name:
        <input type="text" value={name} onChange={handleNameChange} />
      </label>
      <br />
      <label>
        Age:
        <input type="text" value={age} onChange={handleAgeChange} />
      </label>
      <br />
      <label>
        Height:
        <select value={height} onChange={handleHeightChange}>
          <option value="">Select Height</option>
          <option value="160">160 cm</option>
          <option value="170">170 cm</option>
          <option value="180">180 cm</option>
        </select>
      </label>
      <br />
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <p>Height: {height} cm</p>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we define three state variables: name, age, and height, using the useState hook. The initial values are set to empty strings.

We have three separate event handlers: handleNameChange, handleAgeChange, and handleHeightChange, which are triggered whenever the corresponding input fields or dropdown selection changes.

In the JSX portion, we render input fields for name and age, and a select dropdown for height. The value of each input field or dropdown is set to the respective state variable (value={name}, value={age}, value={height}) and is updated through the corresponding event handlers (onChange={handleNameChange}, onChange={handleAgeChange}, onChange={handleHeightChange}).

As the user types into the input fields or selects an option from the dropdown, the corresponding state variable is updated, and React re-renders the component, reflecting the updated values of name, age, and height in the displayed paragraphs

How to renders data dynamically when I button in react js

To dynamically fetch data from a database and update the height, name, and age when a button is clicked in React.js, you'll typically need to use an asynchronous function or an API call to retrieve the data. Here's an example code demonstrating the concept:

import React, { useState } from 'react';

const App = () => {
  const [name, setName] = useState('');
  const [age, setAge] = useState('');
  const [height, setHeight] = useState('');

const fetchDataFromDatabase = async () => {
  try {
    const response = await fetch('https://api.example.com/data'); // Replace with your API endpoint
    const data = await response.json();

    // Update the state with the fetched data
    setName(data.name);
    setAge(data.age);
    setHeight(data.height);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

  return (
    <div>
      <h1>Person Information</h1>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <p>Height: {height} cm</p>
      <button onClick={fetchDataFromDatabase}>Fetch Data</button>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we define three state variables: name, age, and height, using the useState hook. The initial values are empty strings.

The fetchDataFromDatabase function is triggered when the button is clicked. Inside the function, an asynchronous API call or database fetch is performed to retrieve the data. This can be customized based on your specific database and backend setup.

Once the data is fetched successfully, the state variables name, age, and height are updated using their respective setter functions (setName, setAge, setHeight), with the values received from the database.

In the JSX portion, we display the current values of name, age, and height. When the button is clicked, the fetchDataFromDatabase function is invoked, triggering the API call to fetch the data. Once the data is retrieved and the state is updated, React re-renders the component with the updated values, displaying the fetched name, age, and height.

Please note that the specific implementation of fetching data from a database may vary depending on the backend and database setup. You would need to replace 'your_api_endpoint' with the actual endpoint URL or implement the database retrieval logic according to your specific requirements.

How to renders data dynamically when I select dropdown in react js

To dynamically fetch data from a database and update the height, name, and age based on user input in React.js, you can combine the concepts of fetching data and handling input changes. Here's an example code that demonstrates this:

import React, { useState } from 'react';

const App = () => {
  const [name, setName] = useState('');
  const [age, setAge] = useState('');
  const [height, setHeight] = useState('');

  const fetchDataFromDatabase = async () => {
    try {
      // Perform an API call or database fetch to retrieve the data based on user input
      const response = await fetch(`your_api_endpoint?name=${name}&age=${age}&height=${height}`);
      const data = await response.json();

      // Update the state with the fetched data
      setName(data.name);
      setAge(data.age);
      setHeight(data.height);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  const handleNameChange = (event) => {
    setName(event.target.value);
  };

  const handleAgeChange = (event) => {
    setAge(event.target.value);
  };

  const handleHeightChange = (event) => {
    setHeight(event.target.value);
  };

  return (
    <div>
      <h1>Person Information</h1>
      <label>
        Name:
        <input type="text" value={name} onChange={handleNameChange} />
      </label>
      <br />
      <label>
        Age:
        <input type="text" value={age} onChange={handleAgeChange} />
      </label>
      <br />
      <label>
        Height:
        <select value={height} onChange={handleHeightChange}>
          <option value="">Select Height</option>
          <option value="160">160 cm</option>
          <option value="170">170 cm</option>
          <option value="180">180 cm</option>
        </select>
      </label>
      <br />
      <button onClick={fetchDataFromDatabase}>Fetch Data</button>
      <br />
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <p>Height: {height} cm</p>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we have combined the concepts of fetching data and handling input changes.

The fetchDataFromDatabase function is triggered when the "Fetch Data" button is clicked. Inside the function, an asynchronous API call or database fetch is performed to retrieve the data based on the user input (name, age, and height). You should replace 'your_api_endpoint' with the actual API endpoint or the appropriate logic to fetch data from your database.

The input fields for name and age, as well as the select dropdown for height, have their respective event handlers (handleNameChange, handleAgeChange, handleHeightChange) to update the corresponding state variables (name, age, height) as the user types or selects an option.

When the user clicks the "Fetch Data" button, the fetchDataFromDatabase function is called, triggering the API call or database fetch with the user-inputted values. Once the data is retrieved, the state variables (name, age, height) are updated, and React re-renders the component to display the fetched data.

How to renders data dynamically when I submit form in react js

Certainly! Here's an example code that demonstrates submitting a form and dynamically fetching data from a database based on the form inputs in React.js:

import React, { useState } from 'react';

const App = () => {
  const [name, setName] = useState('');
  const [age, setAge] = useState('');
  const [height, setHeight] = useState('');

  const handleSubmit = async (event) => {
    event.preventDefault();

    try {
      const response = await fetch(`your_api_endpoint?name=${name}&age=${age}&height=${height}`);
      const data = await response.json();

      setName(data.name);
      setAge(data.age);
      setHeight(data.height);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  const handleNameChange = (event) => {
    setName(event.target.value);
  };

  const handleAgeChange = (event) => {
    setAge(event.target.value);
  };

  const handleHeightChange = (event) => {
    setHeight(event.target.value);
  };

  return (
    <div>
      <h1>Person Information</h1>
      <form onSubmit={handleSubmit}>
        <label>
          Name:
          <input type="text" value={name} onChange={handleNameChange} />
        </label>
        <br />
        <label>
          Age:
          <input type="text" value={age} onChange={handleAgeChange} />
        </label>
        <br />
        <label>
          Height:
          <select value={height} onChange={handleHeightChange}>
            <option value="">Select Height</option>
            <option value="160">160 cm</option>
            <option value="170">170 cm</option>
            <option value="180">180 cm</option>
          </select>
        </label>
        <br />
        <button type="submit">Submit</button>
      </form>
      <br />
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <p>Height: {height} cm</p>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we have a form that allows the user to input their name, age, and select their height. When the form is submitted by clicking the "Submit" button or pressing Enter, the handleSubmit function is called.

Inside the handleSubmit function, we prevent the default form submission behavior using event.preventDefault() to prevent a page refresh. Then, an API call or database fetch is performed using the form inputs (name, age, height) as query parameters in the URL.

The response from the API call is parsed as JSON, and the data is used to update the name, age, and height state variables.

The handleNameChange, handleAgeChange, and handleHeightChange functions are responsible for updating the respective state variables as the user types or selects options in the form inputs.

The form submission is bound to the handleSubmit function using the onSubmit event of the form element.

Below the form, the updated values of name, age, and height are displayed in the

tags.

Please replace 'your_api_endpoint' with the actual endpoint URL or implement the database retrieval logic according to your specific requirements.

Another example

import React, { useState } from 'react';

const App = () => {
  const [name, setName] = useState('');
  const [age, setAge] = useState('');
  const [height, setHeight] = useState('');

  const handleSubmit = async (event) => {
    event.preventDefault();

    try {
      // Perform an API call or database fetch to retrieve the data
      // Replace 'your_api_endpoint' with the actual endpoint URL
      const response = await fetch('your_api_endpoint');
      const data = await response.json();

      setName(data.name);
      setAge(data.age);
      setHeight(data.height);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  return (
    <div>
      <h1>Person Information</h1>
      <form onSubmit={handleSubmit}>
        <label>
          Name:
          <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
        </label>
        <br />
        <label>
          Age:
          <input type="text" value={age} onChange={(e) => setAge(e.target.value)} />
        </label>
        <br />
        <label>
          Height:
          <input type="text" value={height} onChange={(e) => setHeight(e.target.value)} />
        </label>
        <br />
        <button type="submit">Submit</button>
      </form>
      <br />
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <p>Height: {height} cm</p>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we have a form that allows the user to input their name, age, and height. When the form is submitted by clicking the "Submit" button or pressing Enter, the handleSubmit function is called.

Inside the handleSubmit function, we prevent the default form submission behavior using event.preventDefault() to prevent a page refresh. Then, an API call or database fetch is performed to retrieve the data.

Replace 'your_api_endpoint' with the actual endpoint URL or implement the database retrieval logic according to your specific requirements.

The fetched data is used to update the name, age, and height state variables, which triggers a re-render and displays the updated values in the

tags below the form.

The name, age, and height state variables are updated as the user types or changes the input values using the onChange event on the respective input fields.

How to renders data country,state and city dynamically w in react js

Certainly! Here's an example code that demonstrates fetching country and state data from a database and populating dropdowns in React.js:

import React, { useState, useEffect } from 'react';

const App = () => {
  const [countries, setCountries] = useState([]);
  const [selectedCountry, setSelectedCountry] = useState('');
  const [states, setStates] = useState([]);
  const [selectedState, setSelectedState] = useState('');

  useEffect(() => {
    const fetchCountries = async () => {
      try {
        // Perform an API call or database fetch to retrieve the country data
        // Replace 'your_countries_api_endpoint' with the actual endpoint URL
        const response = await fetch('your_countries_api_endpoint');
        const data = await response.json();

        setCountries(data);
      } catch (error) {
        console.error('Error fetching countries:', error);
      }
    };

    fetchCountries();
  }, []);

  const handleCountryChange = async (event) => {
    const selectedCountry = event.target.value;
    setSelectedCountry(selectedCountry);

    try {
      // Perform an API call or database fetch to retrieve the state data for the selected country
      // Replace 'your_states_api_endpoint' with the actual endpoint URL including the selectedCountry parameter
      const response = await fetch(`your_states_api_endpoint?country=${selectedCountry}`);
      const data = await response.json();

      setStates(data);
      setSelectedState('');
    } catch (error) {
      console.error('Error fetching states:', error);
    }
  };

  const handleStateChange = (event) => {
    setSelectedState(event.target.value);
  };

  return (
    <div>
      <h1>Country and State Dropdowns</h1>
      <label>
        Country:
        <select value={selectedCountry} onChange={handleCountryChange}>
          <option value="">Select Country</option>
          {countries.map((country) => (
            <option key={country.id} value={country.id}>
              {country.name}
            </option>
          ))}
        </select>
      </label>
      <br />
      <label>
        State:
        <select value={selectedState} onChange={handleStateChange}>
          <option value="">Select State</option>
          {states.map((state) => (
            <option key={state.id} value={state.id}>
              {state.name}
            </option>
          ))}
        </select>
      </label>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we have a component called App that renders two dropdowns for country and state selection. The country dropdown is populated with data fetched from the countries API endpoint, and the state dropdown is populated based on the selected country.

Inside the useEffect hook, we fetch the country data by making an API call or database fetch to retrieve the countries. The fetched data is then stored in the countries state variable using the setCountries function.

The handleCountryChange function is triggered when the country dropdown value changes. It updates the selectedCountry state variable and makes an API call or database fetch to retrieve the corresponding states for the selected country. The fetched state data is stored in the states state variable using the setStates function.

The handleStateChange function updates the selectedState state variable when the state dropdown value changes.

Both dropdowns are bound to their respective state variables (selectedCountry and selectedState) and listen for the onChange event to trigger their respective change handler functions.

The fetched country and state data is mapped to elements inside the dropdowns using the map function, dynamically populating the options based on

Top comments (0)