Question in react js

hello guys, i wanna know why this code :

const Button = ({buttonDisplayName, clickHandler})=>{
 <button onClick={clickHandler}>{buttonDisplayName}</button>

run correctly juste whene i change the =>{} by the=> () ;
thanks :slight_smile:

do you meen the function parameters, or the function body?
Button is a JS arrow function. Its also meant to represent a React component. React components should return a HTML element. Your function does not return anything if there is no return statement. You need to put return before the html element. Arrow functions has another feature, they can return a value directly, without explicitely writing return, in case you dont run any additional code within them, before you return the value. To do that, you omit the curly brackets which surround the function body and directly put the value you want to return. For example:

const returnASAP=()=>'some value'

when it comes to writing HTML elements using JSX, its common practice to put them within parenthesis, if the code is larger, so its common to see:

const Button=({buttonDisplayName, clickHandler})=>{
  return (<button onClick={clickHandler}>{buttonDisplayName}</button>)

Like i already explained, since that function is meant to directly return a value, i can omit the return keyword and the curly brackets:

const Button=({buttonDisplayName, clickHandler})=>(<button onClick={clickHandler}>{buttonDisplayName}</button>)

I could even omit the parenthesis as well

In case you are wondering why the function parameters are surrounded by both curly brackets and parenthesis, its because the component is actually accepting its arguments inside the props object. You destructure this object directly in the function parameters and grab the buttonDisplayName and clickHandler properties. Instead, to be more explicit, you can retrieve the props object first, and then, the properties you need:

const Button=(props)=>{
  const {clickHandler, buttonDisplayName}=props
  return (<button onClick={clickHandler}>{buttonDisplayName}</button>)

Notice, this time i destructure the props object inside the function body, so i need to use curly brackets to put the function body and cant omit return.

PS: when you use the Button component, you are likely to place it like so:

<Button clickHandler={someFunction} buttonDisplayName='button name' />

This is very similarly to calling it as a function, that you pass a props object with the two attributes as properties.

@Sylvant i appreciate your clear explanation about the subject , you give me what i want exacutly .really it’s useful explanation.
thanks and i wish you the best :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.