DeloitteAU / react-habitat

⚛️ 🛅 A React DOM Bootstrapper designed to harmonise a hybrid 'CMS + React' application.
Other
262 stars 42 forks source link

Passing Div content to a React component. #36

Closed ImranHishaam closed 6 years ago

ImranHishaam commented 6 years ago

Hi, Is there a possibility of passing a div component to a react component along with the data. At the moment we have implemented react-habitat within the entire project and we have a requirement where a div needs to be embedded to a react component.

Please let me know if there is a possibility on manipulating the DOM.

jenssogaard commented 6 years ago

@ImranHishaam So you want to pass <div>some html</div> as a prop? You just need to encode it before passing it as a string prop and then decode and render like <div dangerouslySetInnerHTML={this.props.myProp} ></div>

jennasalau commented 6 years ago

Hi ImranHishaam,

Jensogaard is correct, that would be the most ideal way doing it. There are few other less pretty solutions I can think of:

Using the proxy prop

Every React Habitat instance is passed in a prop named proxy, this is a reference the original dom element.

So if you put the div inside the react habitat container you could select it that way.

example:

 <div data-component="MyComponent">
      <div>My special div</div>
 </div>

Then

 class MyComponent extends React.Component {
       constructor(props) {
            super(props);
            const specialDiv = props.proxy.getElementsByTagName('div')[0];
            // or
            // const html = props.proxy.innerHtml;
       }
 }

Using the ref prop

You could use the ref prop to pass in a dom reference

 <div id="specialDiv">My Special div</div>

 <script>
      var specialDiv = window.specialDiv = document.getElementById('specialDiv');
 </script>
 <div data-component="MyComponent" data-r-prop-special-div="specialDiv"></div>

Then

 class MyComponent extends React.Component {
       constructor(props) {
            super(props);
            const specialDiv = props.specialDiv;
       }
 }

Using document

There is nothing stopping you from querying the DOM straight from your component. You just need to very careful you don't manipulate DOM nodes owned by ReactDOM. This solution is not recommended unless you know what you are doing.

 class MyComponent extends React.Component {
       constructor(props) {
            super(props);
            const specialDiv = window.document.getElementById('specialDiv');
            if (specialDiv) {
                //Do something with it
            }
       }
 }

Lastly, if you plan on rendering the div html you might want to use something like https://www.npmjs.com/package/html-to-react

or of course use <div dangerouslySetInnerHTML={{__html: '<div>My div</div>'}} />

ryanpcmcquen commented 6 years ago

@ImranHishaam, we have solved for passing child components using React Habitat in slt-ui: https://github.com/SurLaTable/slt-ui#how-did-you-do-this