user6642297
user6642297

Reputation: 393

Function is not working in React outside render()

My function is not working outside the react render function. When I use function code without the function inside the render then it works. Where I am doing the mistake.

React:

class App extends React.Component {
  constructor(props) {
   super(props);
   this.state={
    calcKeys:[
     {
       "key": "AC",
      },
      {
        "key": "CE",
      },
      {
        "key": "±",
       },
       {
        "key": "/",
        },
        {
         "key": "7",
        },
       ]
      };
      this.displayKeys = this.displayKeys.bind(this);
   }
   displayKeys() {
     <div className="display-keys"> 
       <div className="screen">
          <input type="text" />
        </div>
             {this.state.calcKeys.map(item=>
                <button>{item.key}</button>
             )}
      </div>
   }
   render() {
     return(
       <div className="display-container">
         <displayKeys />
       </div> 
     );
    }
} 
ReactDOM.render(<App />, document.getElementById("root"));

Upvotes: 0

Views: 64

Answers (1)

Add return keyword to displayKeys

displayKeys() {
     return <div className="display-keys"> 
     //...
    </div>
}

And use this sintax for call inner render function: {this.displayKeys()} instead of <displayKeys/>.

Don't use <displayKeys/> because React will treat it as a independent component. If you do, then extract displayKeys on other component. E.g:

const Keys = ({calcKeys})=>(<div className="display-keys"> 
  <div className="screen">
     <input type="text" />
  </div>
  {calcKeys.map(item=><button>{item.key}</button>)}
</div>)

class App extends Component{
//...
  render(){
     return(
       <div className="display-container">
         <Keys calcKeys={this.state.calcKeys}/>
       </div> 
     );
  }
}

Upvotes: 1

Related Questions