React.js - Show / hide dynamically generated elements from a component

I create form field elements using a component template that imports an array of data. I want to be able to hide some of these elements and show them when some other element criteria have been met; this is quite common in form fields, for example. When you select element A, a field of form X appears; when you select element B, the field of form X is hidden.

I read a fair bit on conditional rendering on the React docs website, but these examples really do not work for m, although the section Preventing components from rendering is close.

I did Codepen , demonstrating my setup, what I want to do is show the second field if the criteria for the first field are met (in this example, the first field should contain 5 characters). I went through the prop to set the initial hide, but how can I find this hidden element and show it?

// Field data
const fieldData = [{
    "type": "text",
    "label": "First",
    "name": "first",
    "placeholder": "Enter first name",
    "hidden": false
  }, {
    "type": "text",
    "label": "Surname",
    "name": "surname",
    "placeholder": "Enter surname",
    "hidden": true
  }];

  // Get form data
  class FormData extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        items: props.data
      };
    }

    render() {
      let els = this.state.items;

      return els.map((el, i) => {
          return <Input key={i} params={el} />
      });
    }
  }

  // Input builder
  class Input extends React.Component {
      constructor(props) {
          super(props);

          // Keep state value
          this.state = {
              value: '',
              valid: false,
              hidden: this.props.params.hidden
          };

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

      handleChange(e) {
          this.setState({
              value: e.target.value,
              valid: e.target.value.length < 5 ? false : true
          });
      }

      render() {
          // Element attributes
          const {type, label, name, placeholder, hidden} = this.props.params;
          const isValid = this.state.valid === true ? <span>Valid! Should show Surname field.</span> : <span>Not valid. Should hide Surname field.</span>;

          if (!hidden) {
            return (
            <div>
                {label ? <label htmlFor={name}>{label}</label> : null}
                <input
                    type={type}
                    name={name}
                    placeholder={placeholder || null}
                    value={this.state.value}
                    onChange={this.handleChange}
                />
                {isValid}
            </div>
            );
          } else {
            return null;
          }
      }
  }

  // App
  class App extends React.Component {

    render() {
      return (
        <div>
            <h1>Show/Hide test</h1>
            <p>What we want here is the surname to appear when firstname has a value (say, it has 5 characters) and hide surname when firstname doesn't.</p>
            <FormData data={fieldData} />
        </div>
      );
    }
  }


  ReactDOM.render(
      <form>
        <App />
      </form>,
      document.getElementById('app')
  );
+4
source share
2 answers

, Input .
"" surname , , , : propertNameValidator.
, , , surnameValidator hidden prop, Input, , false.

:

// Field data
const fieldData = [
  {
    type: "text",
    label: "First",
    name: "first",
    placeholder: "Enter first name",
    hidden: false
  },
  {
    type: "text",
    label: "Surname",
    name: "surname",
    placeholder: "Enter surname",
    hidden: true
  }
];

// Get form data
class FormData extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: props.data.map(el => ({...el, value: ''})) // add the value property
    };
  }

  onInputChange = (inputId, value) => {
    const { items } = this.state;
    const nextState = items.map((item) => {
      if (inputId !== item.name) return item;
      return {
        ...item,
        value,
      }
    });
    this.setState({ items: nextState });
  }

  surnameValidator = () => {
    const { items } = this.state;
    const nameElement = items.find(item => item.name === 'first');
    return nameElement && nameElement.value.length >= 5
  }

  render() {
    let els = this.state.items;

    return (
      <div>
        {
          els.map((el, i) => {
            const validator = this[`${el.name}Validator`];
            return (
              <Input
                key={i}
                {...el}
                inputId={el.name}
                hidden={validator ? !validator() : el.hidden}
                onInputChange={this.onInputChange}
              />
            );
          })
        }
      </div>
    )
  }
}

// Input builder
class Input extends React.Component {

  handleChange = ({ target }) => {
    const { inputId, onInputChange } = this.props;
    onInputChange(inputId, target.value);
  }

  render() {
    // Element attributes
    const { type, label, name, placeholder, hidden, value } = this.props;
    return (
      <div>
        {
          hidden ? '' : (
            <div>
              {label ? <label htmlFor={name}>{label}</label> : null}
              <input
                type={type}
                name={name}
                placeholder={placeholder || null}
                value={value}
                onChange={this.handleChange}
              />
            </div>
          )
        }
      </div>
    );
  }
}

// App
class App extends React.Component {
  render() {
    return (
      <div>
        <h1>Show/Hide test</h1>
        <p>
          What we want here is the surname to appear when firstname has a value
          (say, it has 5 characters) and hide surname when firstname doesn't.
        </p>
        <FormData data={fieldData} />
      </div>
    );
  }
}

ReactDOM.render(
  <form>
    <App />
  </form>,
  document.getElementById("app")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Hide result

/ , CSS class, .

<input className={`${!isValid && 'hide'}`} />
+4

, . , .

render() {
      // Element attributes
      const {type, label, name, placeholder, hidden} = this.props.params;
      const isValid = this.state.valid === true ? <span>Valid! Should show Surname field.</span> : <span>Not valid. Should hide Surname field.</span>;

      if (!hidden) {
        return (
        <div>
            {label ? <label htmlFor={name}>{label}</label> : null}
            <input
                type={type}
                name={name}
                placeholder={placeholder || null}
                value={this.state.value}
                onChange={this.handleChange}
            />
            {this.state.valid && <input placeholder="add surname" />}
        </div>
        );
      } else {
        return null;
      }
 }
0

Source: https://habr.com/ru/post/1691499/


All Articles