Home > Software engineering >  React props and Component
React props and Component

Time:06-06

I have a problem I can not solve myself in relation to react. What I am trying to do is add props to my Component So I can use my compnent again and again just with a string relative to a variable so I can just write e.g.

I really searched for some different things but none that worked.

Just hoping you can get me on.

Hope it makes sense otherwise feel free to ask

My Component

import React, { Component } from "react";
export default class UserSelections extends Component {

    constructor(props) {
        super(props);

        this.state = {
            items: [],
            DataisLoaded: false,

        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);


    }
    handleChange(event) {
        this.setState({value: event.target.value});
    }

    handleSubmit(event) {
        alert('Your favorite flavor is: '   this.state.value);
        event.preventDefault();
    }
    // ComponentDidMount is used to
    // execute the code
    componentDidMount() {
        fetch(
            "URL")
            .then((res) => res.json())
            .then((json) => {
                this.setState({
                    items: json,
                    DataisLoaded: true
                });
            })
    }
    render() {
        const { DataisLoaded, items } = this.state;
        if (!DataisLoaded) return <div>
            <h1> Vent et øjeblik... </h1> </div> ;

        return (
            <div className = "App">
                <h1> Fetch data from an api in react </h1>
                <form onSubmit={this.handleSubmit}>
                    <label><select name={this.state.slug} value={this.state.value} onChange={this.handleChange}>
                {                             --->Need Variable here<--- Down here 
                items.filter(slug => slug.slug === **'bygnings-st'**).map((item, index) => (

                        <option value={ item.outputvalue }  key={index}>{ item.outputvalue }</option>

                ))
            }</select>
            </label>
            <input type="submit" value="Submit" />
                </form>
            </div>
        );
    }

}

import React from "react";
import UserSelections from "./components/UserSelections";

import './App.css';

function App() {
  return (
    <div className="App">
      <UserSelections **Need props here** /> <-------------------
    </div>
  );
}

export default App;

Best regards Morten

CodePudding user response:

If you want to pass a string as prop:

 const value = "hi";
 <UserSelections stringProp={value} />

And you display the value with:

{this.props.stringProp}

inside of the UserSelections component

  • Related