admin管理员组

文章数量:1296454

I want to add a button inside my input in React. Now I know I could place it there by setting the button absolute and moving in on there using css but I assume that there is a better option to do it?

My moving a field there with absolute value then the search text might go under button.

This is the end result I would like to have but having a normal button there would suffice also.

Here is my input box code:

In this case I can put 2 boxes under eachother and when I place a button inside input I get an error that input can't have any child elements.

I want to add a button inside my input in React. Now I know I could place it there by setting the button absolute and moving in on there using css but I assume that there is a better option to do it?

My moving a field there with absolute value then the search text might go under button.

This is the end result I would like to have but having a normal button there would suffice also.

Here is my input box code:

In this case I can put 2 boxes under eachother and when I place a button inside input I get an error that input can't have any child elements.

Share asked May 12, 2020 at 10:26 RichardRichard 1,1174 gold badges21 silver badges61 bronze badges 1
  • There isn't a better way to do it, as you've seen from that error you can't put elements inside an <input/> so using CSS to make icon appear inside them is your only choice. This is also what all the CSS libraries like Bootstrap and Material UI do – Jayce444 Commented May 12, 2020 at 10:32
Add a ment  | 

3 Answers 3

Reset to default 4

Just a simple code snippet, how you can achieve what you are asking :


.inputWithButton {
  position: relative;
  height: 100px;
  width : 200px;
}

.inputWithButton input{
    width: 70%;
    height: 25px;
    padding-right: 60px;
}

.inputWithButton button {
  position: absolute;
  right: 0;
  top : 5px;
}
<div class='inputWithButton'>
  <input type="text"/>
  <button>Search</button>
</div>

You can also check same change on :

If your intention is to have just a "search button", may I remend the Input Group from react-bootstrap lib. You can add a button with whatever you want inside of it. (Using v2.1.0 - Bootstrap 5)

<InputGroup className="mb-3">
  <FormControl placeholder="Search" />
  <Button variant="outline-secondary">

本文标签: javascriptAdd button inside Input field ReactJSStack Overflow