How to use input field data before submit to apply some logic to create input for a third input field

How to use input field data before submit to apply some logic to create input for a third input field

I have three input fields in my React app and I just want to get the input of the fields BBreite and BHoehe before submit to do some logic to the input values and this logic automatically creates a value for the third field BMark. These three values will afterwards be stored in a database. I only find solutions for after the submit but not before the submit.

Code:

import React, { useState } from 'react';
import BackButton from '../components/BackButton';
import Spinner from '../components/Spinner';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { useSnackbar } from 'notistack';

const CreateBooks = () => {
  const [BMark, setBMark] = useState('');
  const [BHoehe, setBHoehe] = useState('');
  const [BBreite, setBBreite] = useState('');
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const { enqueueSnackbar } = useSnackbar();

  const handleSaveBook = () => {
    const data = {
      BMark,
      BHoehe,
      BBreite,
    };
    setLoading(true);
    axios
      .post('http://localhost:5555/books', data)
      .then(() => {
        setLoading(false);
        enqueueSnackbar('Book Created successfully', { variant: 'success' });
        navigate('/');
      })
      .catch((error) => {
        setLoading(false);
        // alert('An error happened. Please Chack console');
        enqueueSnackbar('Error', { variant: 'error' });
        console.log(error);
      });
  };

  return (
    <div className='p-4'>
      <BackButton />
      <h1 className='text-3xl my-4'>Create Book</h1>
      {loading ? <Spinner /> : ''}
      <div className='flex flex-col border-2 border-sky-400 rounded-xl w-[600px] p-4 mx-auto'>
        <div className='my-4'>
          <label className='text-xl mr-4 text-gray-500'>BMark</label>
          <input
            type='text'
            value={BMark}
            name="BMark"
            onChange={(e) => setBMark(e.target.value)}
            className='border-2 border-gray-500 px-4 py-2 w-full'
          />
        </div>
        <div className='my-4'>
          <label className='text-xl mr-4 text-gray-500'>BHoehe</label>
          <input
            type='text'
            value={BHoehe}
            name="BHoehe"
            onChange={(e) => setBHoehe(e.target.value)}
            className='border-2 border-gray-500 px-4 py-2  w-full '
          />
        </div>
        <div className='my-4'>
          <label className='text-xl mr-4 text-gray-500'>BBreite</label>
          <input
            type='number'
            value={BBreite}
            name="BBreite"
            onChange={(e) => setBBreite(e.target.value)}
            className='border-2 border-gray-500 px-4 py-2  w-full '
          />
        </div>
        <button className='p-2 bg-sky-300 m-8' onClick={handleSaveBook}>
          Save
        </button>
      </div>
    </div>
  );
}

export default CreateBooks

Answer

So, it looks like you want to calculate the value of BMark before submitting the form based on the values of BBreite and BHoehe. You can easily handle this by either updating BMark in the onChange events or using useEffect to recalculate BMark whenever BBreite or BHoehe changes.

You can update BMark directly within the onChange function for the BBreite or BHoehe fields. Here's an example of how you could do that:

const handleInputChange = (e) => {
  const { name, value } = e.target;
  
  if (name === 'BBreite') {
    setBBreite(value);
  } else if (name === 'BHoehe') {
    setBHoehe(value);
  }

  // Calculate BMark based on BBreite and BHoehe
  const calculatedBMark = // your logic here
  setBMark(calculatedBMark);
};


This way, every time you change BBreite or BHoehe, BMark gets updated automatically.

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions