2

I am trying to return multiple functions inside render, but its not getting call from another component:---

class OptionPanel extends React.Component {

constructor(props){
    super(props);
    this.onRemove = this.onRemove.bind(this);
    this.onArrowUp = this.onArrowUp.bind(this);
    this.onArrowDown = this.onArrowDown.bind(this);                
}

onRemove(event){
    event.preventDefault();
    this.props.dispatch.deleteElement(this.props.DesignPanel.selectedElemId);
    {/*event.currentTarget.parentElement.parentElement.parentElement.remove();*/}
} 

onArrowUp(event){
    event.preventDefault();
    this.props.dispatch.moveElementUp(this.props.DesignPanel.selectedElemId);
}

render(){
   return( 
       <div>
       {this.onRemove()}
       {this.onArrowUp()}
       </div>
   )
} }

Would this be the correct way of calling a function inside a render method?

3 Answers 3

1

What you're doing in your code-snipped is, that you're directly calling the methods (onRemove() and onArrowUp(). They will be called and whatever they return will be rendered as well.

So:

Would this be the correct way of calling a function inside a render method?

Yes, this is the right way, however it only makes sense, if these functions will return any content, that should be rendered (like additional components).

If you want to bind these functions to certain events, you have to put the functions as attributes to components.

For a button it would be:

<button type="button" onClick={this.onClickHandle()}>Click me</button>

So whenever the button will be clicked, the method "onClickHandle" will be called.

Sign up to request clarification or add additional context in comments.

Comments

0

You don't need to extend React.Component if you only want to export functions from it

You can create a separate file action.js

and have

export function onRemove(event, dispatch, DesignPanel){
    event.preventDefault();
    dispatch.deleteElement(DesignPanel.selectedElemId);

} 

export function onArrowUp(event, dispatch, DesignPanel){
    event.preventDefault();
    dispatch.moveElementUp(DesignPanel.selectedElemId);
}

and then import it in the component from where you need to call them like

 import {onArrowUp, onRemove} from './path/to/action.js'

Comments

0

You miss binding the event handlers to html tags events

f.e

If you want to bind it to onClick and keyUp events

render(){
   return( 
       <div>
       <button onClick="{this.onRemove()}">
       <input keyUp="{this.onArrowUp()}">
       </div>
   )
} 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.