Home > OS >  How to change react styling dependent on condition
How to change react styling dependent on condition

Time:06-14

import "./index.scss";
import { BsInfoCircleFill } from "react-icons/bs";
import { BsCheckCircleFill } from "react-icons/bs";
import { MdOutlineWarning } from "react-icons/md";

function Alert(props) {
  if (props.icon === <BsInfoCircleFill />) {
    
  }
  return (
    <div className="alert-box">
      <div className="alert-info">
        <h3>{props.icon}</h3>
        <p>{props.message}</p>
      </div>
    </div>
  );
}

export default Alert;

I basically want to add/change the color of the alert boxes depending on which icon is being displayed, i have tried several approaches but to no avail. I have attached the component code and the app.js file

import Alert from "./Alert";
import "./index.scss";

import { BsInfoCircleFill } from "react-icons/bs";
import { BsCheckCircleFill } from "react-icons/bs";
import { MdOutlineWarning } from "react-icons/md";

function App() {
  return (
    <div className="App">
      <div className="main">
        <Alert icon={<BsInfoCircleFill />} message="blah blah blah" />

        <Alert icon={<BsCheckCircleFill />} message="blah blah blah" />
        <Alert icon={<MdOutlineWarning />} message="blah blah blah" />
        <Alert icon={<MdOutlineWarning />} message="blah blah blah" />
      </div>
    </div>
  );
}

export default App;

CodePudding user response:

It appears that this Alert component is your own component. In that case, you pass additional props into each of these Alerts in the app.js, and then do the conditional styling from within the Alert component.

CodePudding user response:

Use if statements, that's the magic of react. For example:

import "./index.scss";

import { BsInfoCircleFill } from "react-icons/bs";
import { BsCheckCircleFill } from "react-icons/bs";
import { MdOutlineWarning } from "react-icons/md";

function App() {
    if (/* considiton here */) {
        return (
            <div className="App">
                <div className="main">
                    <Alert icon={<MdOutlineWarning />} message="blah blah blah" />
                </div>
            </div>
        );
    } else if ( /* another condition */ ) {
        return (
            <div className="App">
                <div className="main">
                    <Alert icon={<MdOutlineWarning />} message="blah blah blah" />
                </div>
            </div>
        );
    }
}

export default App;

Setting the condition is up to you, you can set react state variables based on what's currently active then do something different based on those state variables.

  • Related