Append Input By Button Click using React

Viewed 20

enter image description here

I want to do something like that. Clicking the button will spawn input element. I checked some codes but all codes spawn like

food category food category food name food name

it should be order by clicked which button. How should I update my code?

const foodCategoryInput = () => {

}



function NewMenu() {
    return (
        <div>
            <h1>Create New Menu</h1>
            <button onClick={foodCategoryInput}>Add Food Category</button>
            <button>Add Food Name</button>
            <div id='menuItems'>
                <input type='text' placeholder='Food Category'></input>
                <input type='text' placeholder='Food Name'></input>
                <input type='text' placeholder='Food Name'></input>
                <input type='text' placeholder='Food Name'></input>
                <input type='text' placeholder='Food Category'></input>




            </div>
        </div>
    );
}
1 Answers

As with most questions regarding MVC-style libraries and frameworks, if you are asking about how to do it in the DOM, you've already lost the thread.

The key, in these types of libraries, is to separate the model from the presentation. You have a model: you want to get Food Categories and Food Names in a specific order. You just need to make that into code:

// Example stateless functional component
const SFC = props => ( <div><input type="text" placeholder={(props.type === 'name' ? 'Food Name' : 'Food Category')} data-id={props.id} value={props.value} onChange={props.change} /></div>
);

// Example class component
class Thingy extends React.Component {
    render() {
        const foods = [{
          key: 1,
          type: 'name',
          value: ''
        }, {
          key: 2,
          type: 'category',
          value: ''
        }];
        const {
          title
        } = this.props;
        console.log("rendered");
        return ( <div>
            <div>{title}</div> 
            {
              foods.map(food => ( 
                <SFC type={food.type}
                     key={food.key}
                     id={food.key}
                     value={food.value}
                     change={(e) => {
                      console.log(e.target.value);
                     }
                   } />
                )
              )
            }
          </div>);
       }
    }

    // Render it
    ReactDOM.render(<Thingy title="I'm the thingy" />,
                    document.getElementById("root")
                   );
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

This is the general idea. I leave getting the updating of the elements and storing back into the array for you. There are plenty of tutorials online about that.

Related