3

I'm bit new to react i just wanted to know that how can add conditional rendering to a button in my login page, whenever username and password matches to the api username and password, after hitting submit button it should give me new component.

//here is api
const api ='http://localhost:3000/api/login';
//Login Component
export class Login extends Component {
state = {
            username: '',
            password: '',
            confirmuser:'',
            confirmpass:'',
        };
    componentDidMount() {
        axios.get(api).then(response => {
            let number = response.data.username;
            console.log(response);
            let number2 = response.data.password;
             this.setState({ confirmuser:number});
             this.setState({ confirmpass: number2 });
        })
    .catch((err)=>{
        console.log('Looks like something went wroong ',err);
    });
    }
        //HandleClick Method
            handleClick=()=>{
            const username = this.state.username;
            const password= this.state.password;
            const confirmuser=this.state.confirmuser;
            const confirmpass=this.state.confirmpass;
            console.log(confirmuser);
            console.log(username);
            console.log(password);
            console.log(confirmpass);
            if (username == confirmuser && password == confirmpass ){  
                console.log(`username is ${username}`);
            }
            else{
                console.log('Please enter right username or password');
            }
        };
        
     //Rendaring the elements from material-ui
        render() {
            return (
                <div>
                        <div>
                            <AppBar
                                title="Login"
                            />
                            <TextField
                                hintText="Enter your Username"
                                floatingLabelText="Username"
                                onChange={(event, newValue) => this.setState({ username: newValue })}
                            />
                            <br />
                            <TextField
                                type="password"
                                hintText="Enter your Password"
                                floatingLabelText="Password"
                                onChange={(event, newValue) => this.setState({ password: newValue })}
                            />
                            <br /> 
                            <RaisedButton label="Submit" primary={true} style={style} onClick={ (event) => this.handleClick(event)} />
                        </div>
                </div>
            );
        }
    };

How can i render after clicking button submit

3
  • there are 2 methods you can use. one is on success use routing to redirect to your component or just return the correct jsx and render it right there Commented Jan 31, 2018 at 3:07
  • I have tried returning new component in if statement as return( <ComponentAfterLoggedin /> ) But it were giving me component even username and password didn't matched Commented Jan 31, 2018 at 3:26
  • As a side note, your code in handleClick is driving me crazy. You can shorten the assignments to a single line by using ES6 object descructuring :). const {username, password, confirmuser, confirmpass} = this.state Commented Jan 31, 2018 at 3:37

2 Answers 2

5

there are two approaches to this If you want to redirect to anther component. then use react-router 4 to do so. use this.

     handleClick=()=>{
        const username = this.state.username;
        const password= this.state.password;
        const confirmuser=this.state.confirmuser;
        const confirmpass=this.state.confirmpass;
        console.log(confirmuser);
        console.log(username);
        console.log(password);
        console.log(confirmpass);
        if (username == confirmuser && password == confirmpass ){  
               this.props.history.push({ pathname: '/yourcomponent',});
        }
        else{
            console.log('Please enter right username or password');
        }
    };

wrap your component in the withRouter HOC for this to work.

else if you want to render the component in the same page (easier way.) then do this.

       constructor(props){
         super(props);
         this.state={
           loginSuccess:false
         }
     }


   handleClick=()=>{
        const username = this.state.username;
        const password= this.state.password;
        const confirmuser=this.state.confirmuser;
        const confirmpass=this.state.confirmpass;
        console.log(confirmuser);
        console.log(username);
        console.log(password);
        console.log(confirmpass);
        if (username == confirmuser && password == confirmpass ){  
            this.setState({loginSuccess:true});
        }
        else{
            console.log('Please enter right username or password');

        }
    };

     renderComp(){
       if(this.state.loginSuccess===true){
          return(<YourComponent/>);
        }
        else{
            return(<div>Incorrect UserName or Password</div>)
        }
     }

 //Rendaring the elements from material-ui
    render() {
        return (
            <div>
                    <div>
                        <AppBar
                            title="Login"
                        />
                        <TextField
                            hintText="Enter your Username"
                            floatingLabelText="Username"
                            onChange={(event, newValue) => this.setState({ username: newValue })}
                        />
                        <br />
                        <TextField
                            type="password"
                            hintText="Enter your Password"
                            floatingLabelText="Password"
                            onChange={(event, newValue) => this.setState({ password: newValue })}
                        />
                        <br /> 
                        <RaisedButton label="Submit" primary={true} style={style} onClick={ (event) => this.handleClick(event)} />
                    </div>
                       //change here
                         {this.renderComp()}

            </div>
        );
    }
};
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks 1st Method worked for me, how can i send state values to the component which i just pushed?
sending state values is a bit tricky, better if you used redux instead. and use the store.
I just know concepts of redux can i get any code snippet for pushing state values using redux, through history.push
0

There are mainly two ways on top of my head for conditional rendering in general

1. Using a function that returns JSX element

Refer Sujit answer for this.

renderComp(){
   if(this.state.loginSuccess===true){
      return(<YourComponent/>);
    }
    else{
        return(<div>Incorrect UserName or Password</div>)
    }

}

Then in render method, just call it:

{this.renderComp}

2. Using inline conditional

You can do this inline in your render method in part where you need it. For example:

{this.state.loginSuccess? <SuccessComponent/> : <ErrorComponent/>}

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.