0

I'm trying to render a simple react component to a html page, but can't figure out how to do it.

// hello.js
import React from 'react';
import ReactDOM from 'react-dom';

export default class Hello extends React.Component {
  render() {
    return (
        <h1>Hello {this.props.name}</h1>
    )
  }
}

// index.html
<html>
<body>
</body>
<head>

    <!-- HTML code -->

    <!-- RENDER HERE -->

</head>
</html>

webpack and babel:

// index.js 
import Hello from './hello.js'

If i put this line at the end of Hello.js:

ReactDOM.render(<Hello/>, document.getElementById('hello'));

I can render the component with:

// index.html
<div id="hello"></div>
<script src="bundle.js"></script>

However, There are times where I don't want to render the component, or render it after a certain time interval. If I remove the div i get an error:

Target container is not a DOM element

I guess I want to do something like this (Which doesn't work)

<html>
<body>
</body>
<head>

    <!-- HTML code -->

    <!-- RENDER HERE -->
    <div id="hello"></div>

    <script src="bundle.js"></script>

    <script>
        setTimeout(function() {
            ReactDOM.render(<Hello/>, document.getElementById('hello'));
        },1000);

        // or 

        if (true) {
            ReactDOM.render(<Hello/>, document.getElementById('hello'));
        } 
    </script>
</head>
</html>

What am I doing wrong here? And question nr 2. How do I pass props to the component?

1
  • You should probably wrap your component with an other component implementing the logic about when you want to render or not the sub component Commented Mar 29, 2017 at 14:57

1 Answer 1

3

You should start with this CodePen and do some experiments first to get comfortable with React.

React example on Codepen

There are times where I don't want to render the component, or render it after a certain time interval.

If you use React the right way, you would achieve this behavior by using States or Props. Each time a State or a Prop changes, all affected Components are re-rendered automatically.

How do I pass props to the component?

This is as simple as this:

<MyComponent firstProp={true} secondProp={new Date()} />

And to access this inside MyComponent:

render() {

console.log( this.props.firstProp );

...

}

You should also check out 8 no-Flux strategies for React component communication. This guide helped me a lot, when I first started with ReactJS.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.