Snuk Snuk - 7 days ago 5
React JSX Question

Render 2 div's in one and make to hidden and to appear in React

I am new in world of coding and i have a problem with my React code.

What is on my code is a search bar. I want when i click on the search button to appear a text area to put some text and when i press X to display the first button(search). First time i use getInitialState with 2 renders(renderOpen and renderNormal) and works! But now i want to make it all in one render and to display it. The code is propretly good but is displaying
2 object and i want to display all in one object.
Thanks!!!



import React from 'react';
import ReactDOM from 'react-dom';


var Button = React.createClass({

getInitialState: function() {
return {search:false}
},

close: function(){
this.setState({search:false})
console.log('test1');
},

open: function(){
this.setState({search:true})
console.log('test2');
},

renderNormal: function (){
return(
<div className="mainDiv">
<div className="search-close">
<img src="search2.png" className="search-button" alt="" onClick={this.open}/>
<layer onClick={this.open} className="layer">
<span className="defaultText">Search
</span>
</layer>
</div>

<div className="search-open">
<span className="layer2">
</span>
<input type="image" src="search2.png" className="search-button2"/>
<input type="text" placeholder="&nbsp;Search" className="text-area"/>
<span className="close-area" onClick={this.close}>x
</span>
</div>
</div>
)
},


render: function() {
if(this.state.search) {
return this.renderNormal(
this.props.search-close);
}else {
return this.renderNormal(
this.props.search-open);
}
}
});


const element = <div>
<Button/>
</div>;
ReactDOM.render(
element,
document.getElementById('root')
);




Answer

You want renderNormal to return just one of the two, like this:

renderNormal: function (){
if(this.state.search) {
    return(
        <div className="mainDiv">
            <div className="search-open">

                <span className="layer2">
                </span>
                <input type="image" src="search2.png" className="search-button2"/>
                <input type="text" placeholder="&nbsp;Search" className="text-area"/>
                 <span className="close-area" onClick={this.close}>x
                 </span>
           </div>
      /div>)        
}
else {
    return (
        <div className="mainDiv">
            <div className="search-close">
                  ....
           </div>
      /div>)        
}
}

With a bit of effort you could avoid repeating the mainDiv container, but the key lesson here is that the render method is pure Javascript, and you can use if statements inside of it. The JSX code that looks like HTML is actually just a special syntax for making Javascript objects... which will be used by the top levels of React to manipulate the DOM just like the HTML. (Well, not quite, but pretty close.)