Home > Software design >  React bootstrap5 form select default value? (not react-bootstrap)
React bootstrap5 form select default value? (not react-bootstrap)

Time:08-25

I make a React bootstrap (not react-bootstrap) and Laravel project.

It's only a taskscheduler

This app fulfill with success CRUD operations (except U for now in the frontend, but that doesn't matter now).

But the in the form there are some problem.

The form has select element (priority)

It's default value same as the last value if I added something.

The form's input element (description) work properly and if I add again a task this field will be empty again.

I want same the priority field.

The initial data for datas state come from Laravel.

I not want use now react-bootstrap.

I don't use redux now.

I don't want use third party package for the form now.

Thank you

App.js

import React, { useState, useRef } from "react";
import ReactDOM from "react-dom";
import Item from "./Item";
import Modelem from "./Modelem";
import axios from "axios";
import "../../css/app.css";

const inputs = {
    id: "",
    priority: "",
    description: "",
};

function App() {
    const [datas, setDatas] = useState(data);
    const [newdata, setNewdata] = useState(inputs);
    const [errors, setErrors] = useState(inputs);
    const [success, setSuccess] = useState(false);
    const closeRef = useRef(null);
   
    const handleSubmit = () => {
      
        axios
            .post(
                "/",
                {
                    id: "",
                    priority: newdata.priority,
                    description: newdata.description,
                },
                {
                    headers: {
                        "Content-Type": "application/json",
                        "X-CSRF-TOKEN": token,
                        "X-Requested-With": "XMLHttpRequest",
                    },
                }
            )
            .then(function (response) {
                setDatas(response.data);
                setErrors(inputs);
                setNewdata(inputs);
                setSuccess(true);
                closeRef.current.click();
            })
            .catch(function (error) {               
                handleError(error.response.data.errors);
                setSuccess(false);
            });
    };

    const showerror = (key) => {
        return errors[key] ? (
            <span className="invalid-feedback ">{errors[key]}</span>
        ) : (
            ""
        );
    };

    const inputclasses = (key, classes) => {
        return errors[key] ? classes   " is-invalid" : classes;
    };

    const handleDelete = (id) => { 
         axios
             .delete("/delete/"   id, {
                 headers: {
                     "Content-Type": "application/json",
                     "X-CSRF-TOKEN": token,
                     "X-Requested-With": "XMLHttpRequest",
                 },
             })
             .then(function (response) {
                 console.log("ez most????????")
                 setDatas(response.data);
             })
             .catch(function (error) {
                 console.log(error);
             })
             .finally(() => {
                 setSuccess(false);
             });
     };

    const handleError = (msgs) => {
        const err = {};
        for (let key in msgs) {
            err[key] = msgs[key][0];
        }
        setErrors(err);
    };
    return (
        <>
            <div className="container text-center">    
                {success && (
                                <div className="alert alert-success  alert-dismissible fade show mt-3">
                                    Sikeres mentés!{" "}
                                    <button
                                        type="button"
                                        className="btn-close"
                                        data-bs-dismiss="alert"
                                        aria-label="Close"
                                    ></button>
                                </div>
                            )}
                <h4 className="text-start px-5">Today</h4>
                <ul>
                    {datas.tasks.map((task, index) => (
                        <Item
                            task={task}
                            key={index}
                            handledelete={handleDelete}
                        />
                    ))}
                </ul>
            </div>

            <div className="container text-start px-5 ">
                <Modelem
                    setnewdata={setNewdata}
                    newdata={newdata}
                    handlesubmit={handleSubmit}
                    myref={closeRef}
                    myerror={showerror}
                    myinputclasses={inputclasses}
                />
            </div>
        </>
    );
}

export default App;

if (document.getElementById("root")) {
    ReactDOM.render(<App />, document.getElementById("root"));
}

Item.js

import React from "react";

export default function Item(props) {
    const { named_prior, description,id } = props.task;
    return (
        <li
            className="list-group-item d-flex justify-content-between align-items-center only-bottom-border py-1"
            id="#nincsborder"
        >
            <div>              
                <button
                    type="button"
                    className={
                        `btn btn-info btn-circle bg-white no-border `  
                        named_prior[1]
                    }
                >
                    <i className="fa-regular fa-circle"></i>
                </button>
                {description}
            </div>
            
            <span className="badge badge-primary badge-pill text-secondary">
                {named_prior[0]}
            </span>
            <button className="btn btn-danger" onClick={()=>props.handledelete(id)}>Delete</button>
        </li>
    );
}

Modelem.js

import React, { useState } from "react";
import ReactDOM from "react-dom";

const inputs = {
    id: "",
    priority: "",
    description: "",
};

export default function Modelem(props) {
    const { newdata, setnewdata, handlesubmit } = props;   
    return (
        <div>
            <button
                type="button"
                className="btn btn-outline-danger"
                data-bs-toggle="modal"
                data-bs-target="#exampleModal"
                id="nincsborder"
            >
                <i className="fa-solid fa-plus"></i> Add Task
            </button>

            <div
                className="modal fade"
                id="exampleModal"
                tabIndex="-1"
                role="dialog"
                aria-labelledby="exampleModalLabel"
                aria-hidden="true"
            >
                <div className="modal-dialog" role="document">
                    <div className="modal-content">
                        <div className="modal-header">
                            <h5 className="modal-title" id="exampleModalLabel">
                                Add a Task!
                            </h5>
                            <button
                                type="button"
                                className="close"
                                data-bs-dismiss="modal"
                                aria-label="Close"
                            >
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div className="modal-body">
                            <form>
                                <div className="mb-3">
                                    <label
                                        htmlFor="description"
                                        className="form-label"
                                    >
                                        Description:
                                    </label>
                                    <input
                                        type="text"
                                        className={props.myinputclasses(
                                            "description",
                                            "form-control"
                                        )}
                                        id="description"
                                        value={newdata.description}
                                        onChange={function (e) {
                                            /* console.log(newdata);*/
                                            return setnewdata({
                                                ...newdata,
                                                description: e.target.value,
                                            });
                                        }}
                                    />
                                      {props.myerror("description")}
                                </div>

                                <div className="mb-3">
                                    <label
                                        htmlFor="priority"
                                        className="form-label"
                                    >
                                        Priority:
                                    </label>
                                    <select
                                        id="priority"
                                        className={props.myinputclasses(
                                            "priority",
                                            "form-select"
                                        )}
                                        onChange={function (e) {
                                            /* console.log(newdata);*/
                                            return setnewdata({
                                                ...newdata,
                                                priority: e.target.value,
                                            });
                                        }}
                                    >
                                        <option value={newdata.priority}> - choose - </option>
                                        <option value={1}>Important</option>
                                        <option value={2}>Avarage</option>
                                        <option value={3}>Non-Important</option>
                                    </select>
                                    {props.myerror("priority")}
                                </div>
                            </form>
                        </div>
                        <div className="modal-footer">
                            <button
                                type="button"
                                className="btn btn-secondary"
                                data-bs-dismiss="modal"
                                ref={props.myref}
                            >
                                Close
                            </button>
                            <button
                                onClick={handlesubmit}
                                type="button"
                                className="btn btn-primary"
                            >
                                Save changes
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

if (document.getElementById("modelem")) {
    ReactDOM.render(<Modelem />, document.getElementById("modelem"));
}

CodePudding user response:

enter image description here

You have to make few changes to select element (refer screenshot)

  • Related