React 101

Adding many props

Sometimes you have many props and you don't want to specify them one by one on your component. A cleaner approach is to put them in an object (or in a json file) and use the spread operator to specify them on your component:

const myProps = {
    name: "Tom",
    job: "Developer",
    isLeftHanded: true,
    siblings: 3,
    location: "Germany"
}

function MyComponent(props) {
    return(
        <p>{props.name}, {props.anotherProp}</p>
    );
}

<MyComponent {...myProps} anotherProp="hello" />

Adding attributes conditionally in JSX

Sometimes you want to set an attribute on an element based on value of a prop, for example adding special class only to required form fields or adding an event handler only if an input field is of a specific type and so on. For example below we want to add a class to label of required input fields:

<label for="job">Job:</label>
<input id="job" name="job">
<label for="email" class="required">Email:</label>
<input id="email" name="email" required>

The component should decide to add required class and attribute depending on value of required property in props:

export function Field(props) {
    return (
        <>
            <label
                {...(props.required ? {className: 'required'} : {})}
                htmlFor={props.inputId}
            >{props.label}:</label>
            <input
                required={props.required}
                id={props.inputId}
                name={props.inputId} 
            />
        </>
    )
}

<Field label="Job" inputId="job" />
<Field label="Email" inputId="email" required={true} />

Note that if the syntax in jsx is not easy to read, you can always use a function. For example instead of adding an onInput event handler to password input fields like this:

<input { ...(props.inputType === 'password' ? {onInput: onInputHandler} : {}) } />

We can do it via a function like this:

function addHandler() {
    if (props.inputType === 'password') {
        return {onInput: onInputHandler};
    }
}

<input {...addHandler()} />