If I simply have:
const App = function() { return ( <div>{this.renderList()}</div> ) }
How do I define the renderList
method?
I can't do const renderList = function() {}
(nor with var
or let
). I can't do renderList() {}
.
What's the right syntax?
A stateless function component is a typical React component that is defined as a function that does not manage any state. There are no constructors needed, no classes to initialize, and no lifecycle hooks to worry about. These functions simply take props as an input and return JSX as an output.
Note that the bind keyword isn't necessary for the stateless component.
The core purpose of a React component is to define the displayed view and bind it to the code that drives its behavior. React's functional components distill this down to the simplest possible profile: a function that receives properties and returns a JSX definition.
Stateless components are those components which don't have any state at all, which means you can't use this. setState inside these components. It is like a normal function with no render method. It has no lifecycle, so it is not possible to use lifecycle methods such as componentDidMount and other hooks.
I am hesitant to give a solution to this because inline Stateless Functions
are not supposed to have methods. if you want a method you should use a Class
and theres nothing wrong with using a class. Its all based on what you need to do. Stateless Functions
are designed to be a super light weight way to render something that doesn't need methods, or a state or even a this context (in terms of a class).
you should be doing 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 wouldn't recommend (but does solve your question in the way you want it to) would be like this.
const App = () => { let renderList = () => { return <span>Something Here</span> } return <div>{renderList()}</div> }
The reason why its generally a bad practice is because you are creating a function and all the memory allocation needed every render cycle. Subsequently, the internal diffing optimizations that react provides is generally useless if you do this because a new function gives a different signature than the prior render cycle. If this had a lot of children, they would all be forced to re-render!
You can use Hooks to do this. I would recommend using memo
to memoize the function, this way you aren't creating it in memory each render cycle.
const RenderList = React.memo(props => ( <span>Something Here</span> ))
const App = function() { const renderList = ()=> { return "this variables" } return ( <div>{renderList()}</div> ) }
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