Search code examples
javascriptreactjsconditional-rendering

Conditional rendering a component with using Radio button


New Tasks.js

import React, { useState } from "react";
import './NewTask.css';
import TaskDetails from "./TaskDetails";
import TaskSetting from "./TaskSetting";

const NewTask = () => {
    const [checked, setChecked] = useState("inPerson");


    return (
        <div className="newtask-div">
            <h3 className="header">New Task</h3>
            <ul className="task-item">
                <li style={{ fontSize: "17px" }}>Select Task Type: </li>
                <li>
                    <input
                        type="radio"
                        checked={checked === "inPerson"}
                        name="inPerson" value="inPerson"
                        onChange={(e) => {
                            setChecked(e.target.value)
                            console.log("show task details")
                        }}
                    />
                    <lable>In Person</lable>
                </li>
                <li>
                    <input
                        type="radio"
                        checked={checked === "online"}
                        name="online" value="online"
                        onChange={(e) => {
                            setChecked(e.target.value)
                            console.log("dont show task detail")
                        }}
                    />
                    <lable>Online</lable>
                </li>
            </ul>

            <TaskDetails />

        </div>
    )
}
export default NewTask

I am trying to use the radio button to conditional rendering the Component. Ex: when clicking the "inPerson" it will render out the "TaskDetail" component and show others component when using "online". Is there any method to achieve this?


Solution

  • You can render components conditionally based on selected value like below:

    ...
    
    {
       checked === "inPerson" && 
       <InpersonComponents />
    }
    {
       checked === "online" && 
       <OnlineComponents />
    }
    
    ...