Home > database >  Dynamically modify an attribute of a React element by event
Dynamically modify an attribute of a React element by event

Time:10-27

I am creating an Element in React that contains other elements. One of that element's attributes may have its idtest attribute modified. The declaration of this element is as follows:

    const [currentTest, setCurrentTest] = useState(<PsqMainPanel idtest={idCurrentTest} />);

Once that element is created, and positioned in the template as follows:

                            <li className="nav-item">
                                <a className="nav-link" href="#">
                                    //Main panel with current idtest:
                                    {currentTest}
                                </a>
                            </li>

Finally, in the modification function (which is fired when clicking on a certain element, with the new id value):

    const switchTest = (idtest) => {

       setCurrentTest(<PsqMainPanel idtest={idtest} />); //<--- How to simply modify the one that already exists?
      
    }

I don't really know how I can modify the idtest attribute of the Element PsqMainPanel that is already drawn. I would prefer not to have to redraw it, the ideal would be to modify its id, and that this same element could modify itself, but how can I modify an attribute of an already drawn Element?

Thanks.

CodePudding user response:

You seem to be using the same component in currentTest each time so you should instead store the test ID in currentTest and change your component like this:

const [currentTest, setCurrentTest] = useState(idCurrentTest);
<li className="nav-item">
  <a className="nav-link" href="#">
    <PsqMainPanel idtest={currentTest} />
  </a>
</li>
const switchTest = (idtest) => {
  setCurrentTest(idtest);
}
  • Related