2
votes

In my normal React class Components, I have done some checks in the render() method, before returning conditional html rendering. Now, I was using a react functional component, which apparently does not have the render() method... how would I do the conditional checks here? Just Inside normal functions and then return html code from those functions?

e.g Class Component:

render() {
let test;
if (this.state.test ===true) {
    test = (
    <p>This is a test</p>
    )
}

return(
    {test}
)
}

in functional components? :

        return (            
            <p >
                {checkIcon()} //normal Javascript functions?
            </p>
        )
2
Have you tried this? Is there any error? It is totally fine to use normal JS functions.Björn Böing
You need to pass test as an argument. The rest stays pretty much the same.Yury Tarabanko
The documentation gives you an example with a functional component https://reactjs.org/docs/conditional-rendering.htmlAlberto
{checkIcon() && <p>This is a test</p>}hindmost

2 Answers

2
votes

You can think of functional component as a render method of class component where you can do the exact same thing that you do in render except that you will receive props from the arguments instead of this and similarly you won't have state unless your using hooks. So you would pass test as a prop to the functional component

const MyComponent = ({test}) =>{

    let value;
    if (test ===true) {
        test = (
        <p>This is a test</p>
        )
    }

    return(
        {value}
    )

}
2
votes

As stated by others you can do anything inside a render function, the same things you could do with a class component. You can think of your functional components as the render function of your class ones...

Functional components, by the way, should not contain that much business logic, it'd be better to enhance them with HOCs and function composition.

You might want to have a look at recompose, in which my example takes inspiration from. (change the test attribute and press run code snippet)

// First create a Generic HOC that embedds the branching logic for you.
const branch = (predicate, LeftComponent) => RightComponent => props => (
  predicate(props) ? <LeftComponent {...props} /> : <RightComponent {...props} />
);

// Leave your view component the only job of displaying data to the screen. Avoid any control flow.
const Test = () => 'this is a test component';
const Value = ({ value }) => <div>The Value is {value}</div>;

// Create a final component that branches accordingly with the needed check (if props.test is true)
const Component = branch(
  props => props.test,
  Test
)(Value);


ReactDOM.render(
  <Component test={true} value="£100" />,
  document.getElementById('container')
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="container"></div>