Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: How to do conditional checks from render() method in functional Components?

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>
        )
like image 410
Marc_L Avatar asked Sep 16 '25 11:09

Marc_L


2 Answers

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>
like image 191
Hitmands Avatar answered Sep 19 '25 03:09

Hitmands


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}
    )

}
like image 28
Shubham Khatri Avatar answered Sep 19 '25 01:09

Shubham Khatri