Khoa Võ Đức
Khoa Võ Đức

Reputation: 53

i'm have problem compose between class compenent and stateless function component?

app.js

import React from 'react';
import Header from './Header';
class App extends React.Component{
  render(){
    return(
      <Header />
    )
  }
}

export default App;

Header.js

import React from 'react'
const colorText = (props) => {
     const styles = {
         fontFamily : `${props.color}`
     }
}
class Header extends React.Component{
  constructor(props){
      super(props);
  }
  render(){
      return(
          <header >
             <colorText style = {styles}/>
              <p color = 'red'>Fo Fine!</p>
              <p color = 'green'>By Khoa-VoDuc</p>
              <p color = 'blue'>Great For QuilTing & Sewing</p>
          </header>
      )
      } 
    }
export default Header;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';


ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

error

ERROR : 'styles' is not defined no-undef .

I can't access colorText func in render method of class Header. I want to display on screen these text in tag p with three color above.

Upvotes: 0

Views: 130

Answers (1)

Danziger
Danziger

Reputation: 21181

styles is actually not defined in Header.js. If you want to use the style defined in the colorText function on that file, you have to call it first:

import React from 'react';

const colorText = (color = 'inherit') => {
  const styles = {
    color,
    fontFamily: 'monospace',
  };

  // This `return` here is missing:
  return styles; 
};

class Header extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return(
      <header>
         { /*
           `colorText` return an object with a `color` prop, so you would
           assign that to the `style` attribute of some HTML element, not
           call it as a component as you were doing before.

           So this doesn't make sense because 1) `colorText` is not a
           component and 2) where have you defined this `styles` variable?:

           <colorText style={ styles } />

           Instead, use it like this:
         */ }

         <p style={ colorText('red') }>Fo Fine!</p>
         <p style={ colorText('green') }>By Khoa-VoDuc</p>
         <p style={ colorText('blue') }>Great For QuilTing & Sewing</p>
      </header>
    );
  }
}

export default Header;

Upvotes: 1

Related Questions