0

I have a Component with an onClick event. This event sets in my global state some boolean to true. How can, depending on this boolean render/hide another component?

I could write something like (pseudocode!)

<ParentCompononet

    conditionalRendering(props) {
        if(props.boolean) {
            <ConditionalComponent />
        } else {
            null
        }

     render () {
         return (
             { conditionalRendering }
         )
/>

Not sure if that would be the right way

2
  • Probably too broad as you currently have it :) Are you able to connect the state variable to the props of the component? Commented May 25, 2017 at 11:24
  • @DavinTryon I think so, yes Commented May 25, 2017 at 11:24

2 Answers 2

2

Once you connect the boolean value to props, you could just do something like this:

const MyComponent = (props) => {

   return { props.myBool && <MyChildComponent /> };

}

or slightly more verbose:

const MyComponent = (props) => {

   if (props.myBool) {
       return <MyChildComponent />;
   } else {
       return null;
   }    
}
Sign up to request clarification or add additional context in comments.

4 Comments

I edited my Q. Nearly what I wrote in pseudocode I think?
Yeah, looks about the same :)
Awesome. Wasnt sure if that is the proper way/best practice to do it!
Does it matter that the state object is an object For example what if instead of props.myBool I had props.obj.myBool and obj was connect to the state?
0

Assuming you have configured react-redux propely, This might be the one you are looking for.

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as Actions from '../../actions';



class User extends Component {
    constructor(props) {
      super(props);

    }

    click=()=>{
    this.props.actions.someEvent();
    }

    render() {

      return (
        <div>
        (this.props.useravailable) ? <div>Hello world!</div> : <div/>
        </div>
      );
    }
}

Login.PropTypes = {
  useravailable: PropTypes.bool.isRequired,
  actions: PropTypes.object.isRequired
}

let mapStateToProps = (state,props) => {
  return {
    useravailable: state.user
  }
}

let mapDispatchToProps = (dispatch) => {
  return {
    actions:bindActionCreators(Actions,dispatch)
  };
}

export default connect(mapStateToProps,mapDispatchToProps)(User);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.