I have a simple react component to which I want to add a simple math function named doMath that uses property values.
class MyClass extends Component {
constructor( props ) {
super( ...arguments );
}
render() {
const { attributes } = this.props; /* attributes passed from parent component */
const { width, height } = attributes;
return (
/* render something using the width and height values */
)
}
}
I can add the doMath function in the following ways...
Inside the class:
class MyClass extends Component {
constructor( props ) {
super( ...arguments );
}
doMath() {
const { width, height } = this.props.attributes;
const result = 100 / (width / height);
return result;
}
render() {
const { attributes } = this.props; /* attributes passed from parent component */
const { width, height } = attributes;
return (
doMath();
)
}
}
Outside the class as a const:
const doMath = (width, height) {
const result = 100 / (width / height);
return result;
}
class MyClass extends Component {
constructor( props ) {
super( ...arguments );
}
render() {
const { attributes } = this.props; /* attributes passed from parent component */
const { width, height } = attributes;
return (
doMath(width, height);
)
}
}
Inside render as a const:
class MyClass extends Component {
constructor( props ) {
super( ...arguments );
}
render() {
const { attributes } = this.props; /* attributes passed from parent component */
const { width, height } = attributes;
const doMath = (width, height) {
const result = 100 / (width / height);
return result;
}
return (
doMath(width, height);
)
}
}
Seems like I can also add it to componentDidMount or componentDidUpdate
From what I understood it is bad practice to add it in render() but it seems to work everywhere. What is the best practice in this situation?