mercredi 11 mars 2020

If statement not working when passing props to functional component using Reactjs?

I have just started to learn React and the if statement I have inside my functional component (in ChooseInputType.js shown below) is returning 'false' even though I would expect it to return 'true'. My simplified code is below - can anyone spot the problem? I would like to use Hooks rather than Classes if that's relevant!

Form.js

import React from 'react';
import ChooseInputType from './ChooseInputType';

function App(){
    return(
        <ChooseInputType 
            type="select"
        ></ChooseInputType >
);
}

ChooseInputType.js

function ChooseInputType({type}){
    if({type} ==='select'){
        return (<div>True: Type is {type} </div>);
    else{
        return (<div>False: Type is {type} </div>);
    }
}
export default ChooseInputType;

As you can see from Form.js above, the type property being passed into the ChooseInputType component is equal to "select" and yet the result returned is incorrectly displaying the following:

Result

False: Type is select

This does not happen if I create a variable within ChooseInputType.js (as below), so it must be something about the way I'm passing the type property to the ChooseInputType component?

    function ChooseInputType({type}){
    //I have removed the props part by creating a type variable here
        const type="select";
        if(type ==='select'){
            return (<div>True</div>);
        else{
            return (<div>False</div>);
        }
    }
    export default ChooseInputType;

I'd be grateful for any pointers!

Many thanks,

Katie

Aucun commentaire:

Enregistrer un commentaire