Drop down menu selecting other input field not appearing

I am trying to get an input field to appear when the user selects ‘other’ from the drop down menu. It was only appearing when I first got on the add recipes page, but I changes a few lines and then it stopped appearing all together. I am using FLask for the backend and it is pulling the cuisines from a database.

import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

function AddRecipe() {
  const navigate = useNavigate();
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    ingredients: '',
    directions: '',
    prep_time: '',
    total_servings: '',
    image: '',
    cuisine_id: '',
    user_id: '', 
  });

  const [cuisines, setCuisines] = useState([]);
  const [otherCuisineName, setOtherCuisineName] = useState('');
  const [selectedCuisine, setSelectedCuisine] = useState('');
  const [successMessage, setSuccessMessage] = useState('');

  useEffect(() => {
    fetchCuisines();
  }, []);

  const fetchCuisines = async () => {
    try {
      const response = await fetch('/api/cuisines');
      const data = await response.json();
      setCuisines(data);
    } catch (error) {
      console.error('Error fetching cuisines:', error);
    }
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  const handleCuisineChange = (e) => {
    const value = e.target.value;
    console.log("Selected cuisine:", value);
    setSelectedCuisine(value);
    if (value === 'Other') {
      setOtherCuisineName('');
      document.getElementById('other-cuisine-input').style.display = 'block';
    } else {
      document.getElementById('other-cuisine-input').style.display = 'none';
    }
  };

  const handleOtherCuisineNameChange = (e) => {
    setOtherCuisineName(e.target.value);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    let cuisineId;
    if (selectedCuisine === 'Other') {
      try {
        const response = await fetch('/api/cuisines', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ name: otherCuisineName }),
        });
        const data = await response.json();
        cuisineId = data.id;
      } catch (error) {
        console.error('Error creating new cuisine:', error);
      }
    } else {
      cuisineId = selectedCuisine;
    }
    // Retrieves cuisine id
    formData.cuisine_id = cuisineId;
    try {
      const response = await fetch('/api/recipes', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });
      const data = await response.json();
      console.log('Recipe created:', data);
      setSuccessMessage(`${formData.name} added!`);
      setFormData({
        name: '',
        description: '',
        ingredients: '',
        directions: '',
        prep_time: '',
        total_servings: '',
        image: '',
        cuisine_id: '',
        user_id: '', 
      });
      navigate('/recipes')
    } catch (error) {
      console.error('Error creating recipe:', error);
    }
  };

  return (
    <div className="addrecipe">
      <h2>Add Recipe</h2>
      <form onSubmit={handleSubmit}>
        <div className="addrecipe-card">
          {successMessage && <p>{successMessage}</p>}
          <label>Name:</label>
          <input
            type="text"
            name="name"
            placeholder="recipe name"
            value={formData.name}
            onChange={handleInputChange}
            required
          />
          <div>
            <label>Description:</label>
            <textarea
              name="description"
              placeholder="brief recipe description"
              value={formData.description}
              onChange={handleInputChange}
              required
            />
          </div>
          <div>
            <label>Ingredients:</label>
            <textarea
              name="ingredients"
              placeholder="recipe ingredients separated by commas"
              value={formData.ingredients}
              onChange={handleInputChange}
              required
            />
            <label>Directions:</label>
            <textarea
              name="directions"
              placeholder="recipe directions separated by periods."
              value={formData.directions}
              onChange={handleInputChange}
              required
            />
          </div>
          <div>
            <label>Prep Time (minutes):</label>
            <input
              type="number"
              name="prep_time"
              placeholder="approximate prep time"
              value={formData.prep_time}
              onChange={handleInputChange}
              required
            />
          </div>
          <div>
            <label>Total Servings:</label>
            <input
              type="number"
              name="total_servings"
              placeholder="total servings"
              value={formData.total_servings}
              onChange={handleInputChange}
              required
            />
          </div>
          <div>
            <label>Image Link:</label>
            <input
              type="text"
              name="image"
              value={formData.image}
              onChange={handleInputChange}
            />
          </div>
          <div>
            <label>Cuisine:</label>
            <select
              name="cuisine_id"
              value={selectedCuisine}
              onChange={handleCuisineChange}
              required
            >
              <option value="">Select cuisine...</option>
              {cuisines.map(cuisine => (
                <option key={cuisine.id} value={cuisine.id}>{cuisine.name}</option>
              ))}
              {/* Prevents duplicating of cuisines */}
              {!cuisines.some(cuisine => cuisine.name === 'Other') && (
                <option value="Other">Other</option>
              )}
            </select>

            <input
              id="other-cuisine-input"
              type="text"
              placeholder="Enter custom cuisine name"
              value={otherCuisineName}
              onChange={handleOtherCuisineNameChange}
              style={{ display: selectedCuisine === 'Other' ? 'block' : 'none' }}
            />
          </div>
          <button className="button" type="submit">Add Recipe</button>
        </div>
      </form>
    </div>
  );
}

export default AddRecipe;

New contributor

H.Kruz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật