Home > Software engineering >  How can I show boolen values (true and false) to user in react.js?
How can I show boolen values (true and false) to user in react.js?

Time:08-16

I'm building an e-commerce site with react js and asp.net core web api. When adding a product in react, the biddable value of the product should be given by the person who added the product, and this value should be false by default. Its equivalent in the isOfferable database is kept as a bool value. So I want the user to select a value as false or true and when I say add product, it should be added to the products in the database, but I could not find how to keep the bool value in react.js.

My AddProduct.js

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import '../../Css/AddProduct.css'

import { ProductAddSchema } from "../../validations/productAddSchema"
import { Dropdown } from 'semantic-ui-react'
import {useFormik} from 'formik'


function AddProduct() {

  //const [baseImage,setBaseImage] =useState("")

  //fetch data 
  const [colors, SetColors] = useState([])
  const [brands, SetBrands] = useState([])
  const [categories, SetCategories] = useState([])
  const [usedStatus, SetUsedStatus] = useState([])

 
  useEffect(() => {
    getAll()

  }, [])




  async function getAll() {

    //getall colors
    axios.get('http://localhost:64082/api/color/getall')
      .then(response => {
        SetColors(response.data)
      }).catch(error => {
        return alert("Error: "   error);
      })

    //getall brands
    axios.get('http://localhost:64082/api/brand/getall')
      .then(response => {
        SetBrands(response.data)
      }).catch(error => {
        return alert("Error: "   error);
      })


    //getall categories
    axios.get('http://localhost:64082/api/categories/getall')
      .then(response => {
        SetCategories(response.data)
      }).catch(error => {
        return alert("Error: "   error);
      })

    //getall usingstatus (new or used)
    axios.get('http://localhost:64082/api/usingstatus/getall')
      .then(response => {
        SetUsedStatus(response.data)
      }).catch(error => {
        return alert("Error: "   error);
      })


  }


  const { handleSubmit, handleChange, values, errors, touched } =
    useFormik({

      initialValues: {
        name: "",
        description: "",
        colorId: "",
        brandId: "",
        categoryId: "",
        price: "",
        isOfferable:false
       
      },
      onSubmit: (values) => {
        console.log(values);
        try {
          axios({
            method: "post",
            url: "http://localhost:64082/api/products/add",
            data: { values }

          });
          return alert("Success!");
        } catch (error) {
          return alert("Error: "   error);
        }

      },
      validationSchema: ProductAddSchema
    })



  
  return (

    <div className='space'>


      <div className="create">
        <h2>Add a New Product</h2>
        <form onSubmit={handleSubmit}>
          <label>Product Name:</label>
          <input
            type="text"
            name='name'
            value={values.name}
            onChange={handleChange}
            placeholder="product name"
          />

          {errors.name && touched.name && (
            <div >{errors.name}</div>
          )}

          <label>Product Description:</label>
          <textarea
            value={values.description}
            onChange={handleChange}
            name="description"
            placeholder='description'
          ></textarea>

          {errors.description && touched.description && (
            <div >{errors.description}</div>
          )}

          <label>Product color name:</label>
          <select
            name='colorId'
            value={values.colorId}
            onChange={handleChange}>
            <option >select color</option>
            {
              colors?.map((color, index) => {

                return (<option key={index} value={color.colorId}>{color.name}</option>)
              })
            }
          </select>

          {errors.colorId && touched.colorId && (
            <div  >{errors.colorId}</div>
          )}



          <label>Product brand name:</label>
          <select
            name='brandId'
            value={values.brandId}
            onChange={handleChange}>
            <option >select brand</option>
            {
              brands?.map((brand, index) => {
                return (<option key={index} value={brand.brandId}>{brand.name}</option>)
              })
            }
          </select>

          {errors.brandId && touched.brandId && (
            <div >{errors.brandId}</div>
          )}

          <label>Product category name:</label>
          <select
            name='categoryId'
            value={values.categoryId}
            onChange={handleChange}>
            <option >select category</option>
            {
              categories?.map((category, index) => {
                return (<option key={index} value={category.categoryId}>{category.categoryName}</option>)
              })
            }
          </select>
          {errors.categoryId && touched.categoryId && (
            <div >{errors.categoryId}</div>
          )}

          <label>Product Price:</label>
          <input
            type="number"
            name='price'
            value={values.price}
            onChange={handleChange}
            placeholder="price TL"
          />
          {errors.price && touched.price && (
            <div >{errors.price}</div>
          )}



          <select
            name='usingStatusId'
            value={values.usingStatusId}
            onChange={handleChange}
          >
            <option >select used state</option>
            {
              usedStatus.map((state, index) => {


                return (<option key={index} value={state.usingStatusId}>{state.usedStatus}</option>)
              })
            }
          </select>
          {errors.categoryId && touched.categoryId && (
            <div >{errors.categoryId}</div>
          )}



         <label>is Offerable:</label>
          <select
            name='isOfferable'
            value={values.isOfferable}
            onChange={handleChange}>
            
            <option></option>     {/*I tried to do it here but I couldn't*/}
            <option></option>

          
          </select>
          {errors.isOfferable && touched.isOfferable && (
            <div >{errors.isOfferable}</div>
          )} 


          <button type='submit' >Add Product</button>

        </form>
      </div>
    </div>
  );
}

export default AddProduct;

CodePudding user response:

false, null, undefined, and true are valid children but. They simply don't render anything and are ignored in react. So if you want to render any of the above for example false you have to write an expression that will return a text representing the boolean example:

const MyComponent = () => {
   const status = false;
   return (
        <div>
           <h1>{!status && <span>false</span>}
        </div>  
)}

CodePudding user response:

It's not very clear as the previous commenter writes.

However, the way to store a variable or piece of data in React is by using: useState() hook.

const [value, setValue] = useState(false);
  • Related