user12869765
user12869765

Reputation:

Logic to render a component only once

I need help with creating a logic for my React component. If the divider line appears once on the page it should not be rendered again.

So, if I add the component to the page it styles the text underneath. But if I try to add the component again to the page, the divider line/styling should be ignored. I should only be able to add it once

This is my code:

import React from 'react';
const Divider = () => (
  <>
    <hr className="divider"/>
  </>
);
/* Seperate css file */
hr.divider {
  height: 0;
  border: 0;
  border-top: solid 1px #cdcdcd;
}

hr.divider ~ p.story-text {
  font-size: 0.90rem;
  font-weight: normal;
  font-stretch: normal;
  font-style: normal;
  letter-spacing: normal;
  line-height: 1.75rem;
  color:#707174;
  @include text-styles(.75rem, 1.75em, "Gordita");
  @include breakpoint(tablet) {
    @include text-styles(.90rem, 2em, "Gordita");
  }
}

hr.divider ~ p.story-text:last-of-type {
  border-top: solid 1px red;
}

Upvotes: 0

Views: 188

Answers (2)

Sydney Y
Sydney Y

Reputation: 3152

It may be better to add a condition in the parent component (the one that calls Divider), but given the current snippets:

const Divider = () => (
  let dividers = document.getElementsByClassName('divider')
  if (dividers.length > 0) {
    return null
  } else {
    return <hr className="divider"/>
  }
);

This will not stop your component from rendering. It will only stop more than one hr from rendering.

Upvotes: 0

DadyByte
DadyByte

Reputation: 914

You need to use the component LifeCycle tools provided by ReactJS. ComponenDidMount() loads the only once when the class is loaded but the render() function is called on each action of the user or the app. Here is a link to ReactJS docs telling how to use ComponentDidMount(): https://reactjs.org/docs/react-component.html#componentdidmount

Upvotes: 1

Related Questions