Can a stateless functional component have more parameters?

Question

In the context of this exercise, can a stateless functional component have more parameters, other than props and state?

Answer

No, stateless functional components in React can only accept props and state as optional parameters. As a result, you cannot do something like the following, which adds other parameters other than props or state,

export const MyComponentClass = (props, param2, param3) => {
  return ...
}

If you need to pass any values to the component, you should always do so by passing them as props, without the need for adding other parameters.

3 Likes

Not multiple parameters but we can pass multiple arguments when we create our props from our parent component. Thus, if you have the need to use multiple values in your stateless functional component you can simply do the following:

class ParentName extends React.Component {
 (...)
  render() {
    return (
          <StatelessFuncCompName myPropName={value1, value2, value3} />
    );
  }
}

On your Stateless Functional Component your can do the following:

const StatelessFuncCompName = (props) => {
    const variable_one = props.value1;
    const variable_two = props.value2;
    const variable_three = props.value3;

// And use them accordingly in your function
}

I believe I learned that from React Docs. Correct me someone if I’m wrong. Thanks!

10 Likes

I have an additional question to all that has been explained in this exercise:
If the stateless functional component is written as a JavaScript function, and therefore the React.Component statement is no longer used, do we still have to import the React.js library in the first line of our code?

3 Likes

Yes, we do. We still use the react library but we are not extending any class from the react-built “COMPONENT CLASS”.

Also, saying “stateless functional component is written as a JavaScript function” is like saying " component classes are written as JavaScript classes". React is a Javascript Library which ultimately makes it Javascript.

5 Likes

Very helpful thanks.

I dont know if you’re right or wrong. But I think this is the way to go if you want to pass multiple arguments inside a Stateless Functional Component:
In Our Parent Class Component:

class ParentName extends React.Component {
 (...)
  render() {
    let value1='apple';
    let value2='orange';
    return (
          <StatelessFuncCompName myProp1={value1} myProp2={value2} />
    );
  }
}

In Our Stateless Functional Component:

const StatelessFuncCompName = (props) => {
    const variable_one = props.myProp1;
    const variable_two = props.myProp2;
//AND value1 will get stored in variable_one and value2 in variable_two
// And use them accordingly in your function
}

Correct me If I am Wrong. :slight_smile:

It looks correct, but in essence, those are not arguments but props.

How would we use “state” parameter in a stateless function?

1 Like