Home > Enterprise >  Calling Stateless Functional Components
Calling Stateless Functional Components

Time:09-22

I'm currently learning React and i am working through 'The Road to React' by Robin Wieruch.

I've just refactored some code from a stateful to a functional stateless component like so:

function Search(props) {
  const { value, onChange, children } = props;
  return (
    <form>
      {children} <input
        type="text"
        value={value}
        onChange={onChange}
      /> 
    </form>
  ); 
}

Gets Refactored to:

const Search = ({ value, onChange, children }) => {
  <form>
    {children} <input
    type="text"
    value={value}
    onChange={onChange}
    />
  </form>
}

However nothing is rendering anymore. Are functional stateless components called the same was as stateful ones?

This is how I'm calling the Search component in the App class:

render() {
const { searchTerm, list }  = this.state;
return (
  <div className="App">
    <Search 
      value = { searchTerm }
      onChange = { this.onSearchChange }
    >
      Search
    </Search>
    <Table
      list = { list }
      pattern = { searchTerm }
      onDismiss = { this.onDismiss }
    />
  </div>
)

I'm not receiving an error at all, so i'm not getting much that's pointing me in the right direction, i'm hoping i'm just missing something silly.

Thanks in advance!

CodePudding user response:

In both cases, it's a stateless function only as there's no state and it's not an class component either.

1st case is working correctly because it's returning the element with the return keyword.

2nd refactored case is also correct but you are not returning anything you need to return the element for it to be rendered.

return example

const func = () => {
    ... // any more calculations or code
    return ( // you are returning the element here
        <div>
            ...
        </div>
        )
    }

If there's no calculation or any additional code and you have to return only an element you can directly return it by using (...) instead of {...} as follows

const func = () => ( // you are directly returning element
    <div>
        ...
    </div>
    )

PS: for more info you can check into arrow functions

  • Related