0

I have a react component shown below and I'm trying to conditionally render some components. The goal is that when the current session is a host, the function AppropriatePage should return the HostWorkflow component, however I run into the Uncaught TypeError.

I referred to this to do this.

export default class HostPage extends Component {
    constructor(props) {
        super(props);
        
        this.state = {
            participants: 0,
            questions: 0,
            host: true,
            session_id: -1,
        };
        this.session_code = this.props.match.params.session_code;
    }   
HostWorkflow() {
        return (<Grid container spacing={1}>
            <Grid item xs={12} align="left">
                <Button color='secondary' onClick={this.handleEndSession}>End Session</Button>
            </Grid>
            <Grid item xs={4} align="left">
                <p>SESSION {this.session_code}</p>
            </Grid>
            <Grid item xs={4} align="center">
                <p>PARTICIPANTS {this.state.participants}</p>
            </Grid>
            <Grid item xs={4} align="right">
                <p>QUESTIONS {this.state.questions}</p>
            </Grid>
        </Grid>);
    }

    AppropriatePage(props) {
        const is_host = props.host;
        if (is_host) {
            console.log("TEST MY IF");
            return (<this.HostWorkflow />);
        }
        return <p>NOT HOST</p>;
    }
    render() {
        return (<this.AppropriatePage host={this.state.host} />);
    }
}
Name123
  • 29
  • 4
  • 1
    The problem is that when `React.createElement` calls `AppropriatePage`, it doesn't set `this` to anything in particular, so `this` within the call is `undefined`. You *could* get around it by using arrow functions instead of method syntax, but for what it's worth, I'd suggest splitting those out into their own components instead, passing them any necessary state as props. – T.J. Crowder Nov 19 '21 at 08:08
  • I initially had them as separate react files, but I had them as router paths and I needed one component to be able to change the state of the other component. And since they were in the router I had no way of passing the function to the component in the route. Your suggestion worked though! – Name123 Nov 19 '21 at 22:28

0 Answers0