最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can i add conditional rendering to a button in react - Stack Overflow

programmeradmin0浏览0评论

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 ponent.

//here is api
const api ='http://localhost:3000/api/login';
//Login Component
export class Login extends Component {
state = {
            username: '',
            password: '',
            confirmuser:'',
            confirmpass:'',
        };
    ponentDidMount() {
        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>
            );
        }
    };

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 ponent.

//here is api
const api ='http://localhost:3000/api/login';
//Login Component
export class Login extends Component {
state = {
            username: '',
            password: '',
            confirmuser:'',
            confirmpass:'',
        };
    ponentDidMount() {
        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

Share Improve this question edited Jan 31, 2018 at 4:46 Ujwal Arak asked Jan 31, 2018 at 3:00 Ujwal ArakUjwal Arak 451 gold badge3 silver badges8 bronze badges 3
  • there are 2 methods you can use. one is on success use routing to redirect to your ponent or just return the correct jsx and render it right there – Sujit.Warrier Commented Jan 31, 2018 at 3:07
  • I have tried returning new ponent in if statement as return( <ComponentAfterLoggedin /> ) But it were giving me ponent even username and password didn't matched – Ujwal Arak 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 – Andrew Commented Jan 31, 2018 at 3:37
Add a ment  | 

2 Answers 2

Reset to default 5

there are two approaches to this If you want to redirect to anther ponent. 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: '/yourponent',});
        }
        else{
            console.log('Please enter right username or password');
        }
    };

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

else if you want to render the ponent 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>
        );
    }
};

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/>}
发布评论

评论列表(0)

  1. 暂无评论