How do I call the function for getClass
for the className
inside this example? The way I have it written out does not seem to call getClass
.
var CreateList = React.createClass({
getClass: function() {
//some code to return className
},
render: function() {
return(
<div className{this.getClass}>Example</div>
);
}
});
Before React 16.8, Class components were the only way to track state and lifecycle on a React component. Function components were considered "state-less". With the addition of Hooks, Function components are now almost equivalent to Class components.
To be a component function returning JSX should be used as <Component /> and not as Component (). When a functional component is used as <Component /> it will have a lifecycle and can have a state. When a function is called directly as Component () it will just run and (probably) return something. No lifecycle, no hooks, none of the React magic.
If there is a constructor () function in your component, this function will be called when the component gets initiated. The constructor function is where you initiate the component's properties. In React, component properties should be kept in an object called state.
I haven't found a single mention about calling functional components directly in React docs, however, there is one technique where such a possibility is demonstrated - render props. After some experiments, I came to quite a curious conclusion. What is a Component at all?
You're referencing the instance of the getClass()
function as opposed to calling the function. Try tweaking it like so:
render: function() {
return(
<div className={this.getClass()}>Example</div>
);
}
className{this.getClass}
won't compile. Try this:
var CreateList = React.createClass({
getClass: function() {
//some code to return className
},
render: function() {
return(
<div className={this.getClass()}>Example</div>
);
}
});
If you want the div to have a class name that starts with 'className', then prepend that string to the result of the call: className={'className' + this.getClass()}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With