How to define methods in stateless components?

If I just have:

const App = function() { return ( <div>{this.renderList()}</div> ) } 

How to define renderList method?

I can not do const renderList = function() {} (and not with var or let ). I can not do renderList() {} .

What is the correct syntax?

+19
source share
4 answers

I hesitate to give a solution, because built-in Stateless Functions should not have methods. if you want a method, you have to use Class and there is nothing wrong with using a class. It all depends on what you need to do. Stateless Functions are designed to be an ultralight way to visualize something that doesn't need methods, or states, or even that context (in class terms).

you have to do it like this.

 class App extends Component { constructor(){ super(); // note this is a Stateless Component because its a react class without a state defined. } renderList = () => { return <span>Something Here</span>; } render() { return <div>{this.renderList()}</div> } } 

A HACK way that I would not recommend (but solve your question the way you want) would be like this.

 const App = () => { let renderList = () => { return <span>Something Here</span> } return <div>{renderList()}</div> } 

The reason this is usually bad practice is because you create a function and all the memory allocation is required for each rendering cycle. Therefore, the internal difference optimization that provides the response is usually useless if you do this because the new function gives a different signature than the previous render cycle. If it had many children, they would all be forced to re-do!

Edit - Reaction Version 16.8.0 +

You can use hooks for this. I would recommend using memo to remember a function, so you don't create it in memory every render cycle.

 const RenderList = React.memo(props => ( <span>Something Here</span> )) 
+30
source
 const App = function() { const renderList = ()=> { return "this variables" } return ( <div>{renderList()}</div> ) } 
+5
source

Would you like to do something like this

 const App = function() { return ( <div>{renderList()}</div> ) } function renderList(){ return "this variables" } 

Naturally, this is a bad approach, and you are advised that you go through the functions, since the props and stateless component have always been stupid components. Let's say if you use a shorthand, for example, you can make your component like this.

 import {connect} from 'react-redux'; const App = (props) => { return ( <div> {props.renderList} </div> ) } function renderList (){ return "your render logic" } export default connect(null, {renderList})(App) 
0
source

Can you try something like

 const App = () => { return ( <div>{this.renderList()}</div> ) } App.renderList = () => { return 'This is my list' } 
0
source

All Articles