Ly Maneug Ly Maneug - 2 months ago 8
React JSX Question

ReactJS: How to fix an element to its current position despite rendering of new element?

I have

<h1/>
and
<input/>
elements, and once a text is inputted, a
<button/>
appears/renders. But it moves the
<h1/>
and
<input/>
more to the left to make space for the
<button/>
.

How can I fix the position of
<h1/>
and
<input/>
elements, so that they do not move and stay at their current positions even when
<button/>
appears/renders?

Here is the code (when text is entered, triggers the _displayButton and sets textEntered to true, which renders the button):

constructor(){
super();

this.state = {
textEntered: false,
nameText: ''
}

this._displayButton = this._displayButton.bind(this)
}

_displayButton(event) {
this.setState({
nameText: event.target.value,
textEntered: true
})
}

<div style={{display: 'flex', flexDirection: 'row', alignItems: 'center'}}>
<h1>Do Not Move Me</h1>
<input
placeholder='Enter Name'
onChange={this._displayButton}
value={this.state.nameText}
/>
{this.state.textEntered ?
<button
type="submit"
/>
: null
}
</div>


EDIT

Before new button renders:

enter image description here

After new button renders:

enter image description here

Answer

Although you might have to make some changes depending on your entire HTML structure and CSS styles, you could do

<div style={{display: 'flex', flexDirection: 'column', alignItems: 'center'}}>

    <div>
        <h1>Do Not Move Me</h1>
        <input
        placeholder='Enter Name'
        onChange={this._displayButton}
        value={this.state.nameText}
        />
    </div>

    <div>
    {this.state.textEntered ?
        <button
        type="submit"
        />
        : null
    }
    </div>

</div>

The main change i made is changed flexDirection from row to column, This makes the div children/sub divs appear below each other instead of appearing beside each other.

Edit:

<div style={{display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-start'}}>

added justifyContent property.

Edit 2:

<div style={{display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>

    <h1>Do Not Move Me</h1>

    <div style={{ position: 'relative', marginLeft: 20 }}>

        <input
        placeholder='Enter Name'
        onChange={this._displayButton}
        value={this.state.nameText}
        />
        {this.state.textEntered ?
            <button type="submit" style={{ position: 'absolute', top: '-10px', right: '-10px', borderRadius: '50%', height: 40, width: 40, backgroundColor: '#881587', border: 'none' }} /> : null
        }

    </div>

</div>

You have to edit the button styles to make it look the way you want.