Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call function inside of className react.js

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>
        );
    }
});
like image 346
Chipe Avatar asked Dec 01 '15 01:12

Chipe


People also ask

What is the difference between class and function components in react?

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.

How to return JSX from a function in react?

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.

When is the constructor of a React component called?

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.

Is it possible to call a functional component directly in react?

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?


2 Answers

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>
    );
}
like image 71
pseudoramble Avatar answered Sep 20 '22 01:09

pseudoramble


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()}.

like image 40
Hunan Rostomyan Avatar answered Sep 22 '22 01:09

Hunan Rostomyan